blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
listlengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8616e229bfa38df579f20b2ddd6fe4f078a45f3e | bfe1b4f5a8cf18b26dcc9ff670f33f254eb242cb | /data/src/main/java/org/soluvas/data/NormalRepository.java | c0d5510411a4f69458f45a4508e815b20e469438 | []
| no_license | talkvip/soluvas-framework | 796192898ac1a988e7ac6cb09966305ec4d91270 | 596450f3ed097f8f2898723949c3bfc07fd6f87a | refs/heads/master | 2020-04-05T23:32:01.381917 | 2013-04-25T10:52:46 | 2013-04-25T10:52:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 592 | java | package org.soluvas.data;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Qualifier;
import org.soluvas.data.repository.Repository;
/**
* Asks for non-raw repository.
*
* @todo Note: Planned to be deprecated in favor of unified {@link Repository} semantic interfaces.
* (i.e. delete() by default means trash, and we have deletePermanently(), archive(), move(), etc.)
* @author agus
*/
@Qualifier
@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface NormalRepository {
}
| [
"[email protected]"
]
| |
c6472e25dd401c8da508e41313f839a875a442cf | ad79924aa042e3143d5ab78c2e272a29c29aee33 | /src/test/java/com/ScreenFunctions/Recurit_Reg_Form.java | a975e8ab326084e5662a5d53b73dce3cdcc28617 | []
| no_license | umadeviSai/TalentZing | 590a7002efec8dbcf5256fdc588601e877ff32f5 | 29c1ba4b6431927a64aafbbd43ac12f662ebd8c1 | refs/heads/master | 2020-03-24T16:39:57.949886 | 2018-07-30T06:59:42 | 2018-07-30T06:59:42 | 142,831,686 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,967 | java | package com.ScreenFunctions;
import java.util.List;
import javax.net.ssl.HostnameVerifier;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import com.GenericFunctions.GenericFunctions;
public class Recurit_Reg_Form extends GenericFunctions{
@FindBy(how=How.XPATH, using="//input[@type='submit']")
public static WebElement Btn_RecRegform_Submit;
@FindBy(how=How.XPATH, using="//span[@id='ctl00_ContentPlaceHolder2_lblCheck']")
public static WebElement Lbl_RecRegform_TandC;
@FindBy(how=How.XPATH, using="//input[@id='chkTerms']")
public static WebElement Chk_RecRegform_chkTerms;
@FindBy(how=How.XPATH, using="//span[contains(text(),'*')]/parent::label")
public static List<WebElement> List_RecRegform_Labels;
@FindBy(how=How.XPATH, using="//span[contains(text(),'Please specify')]")
public static List<WebElement> List_RecRegform_Validators;
public static void FillRegForm()
{
String label="";
try{
hoverAndClick(Btn_RecRegform_Submit);
if(hoverOverElement(Lbl_RecRegform_TandC))
{
forceClick(Chk_RecRegform_chkTerms);
hoverAndClick(Btn_RecRegform_Submit);
}
for(int i=0;i<List_RecRegform_Labels.size();i++)
{
label =List_RecRegform_Labels.get(i).getText();
label=label.replace("*:","").trim().toLowerCase();
if (i==9)
label="contact number";
if(List_RecRegform_Validators.get(i).getText().contains(label))
{
System.out.println(label +"---matching ----"+List_RecRegform_Validators.get(i).getText());
}
else
{
System.out.println(label +"---not matching----"+List_RecRegform_Validators.get(i).getText());
}
//System.out.println(List_RecRegform_Labels.get(i).getText());
//System.out.println(List_RecRegform_Validators.get(i).getText());
}
}catch(Exception e)
{
}
}
}
| [
"TM@TM-PC"
]
| TM@TM-PC |
957d9957cd0ea32b09294d221ef25b0df4114819 | c446f797efdcefb423d547eb6174f0dca9d700fc | /src/main/java/com/example/java/KalahApplication/Repository/GameBoardRepository.java | f2b8f77f5d706ad170a572d1448b8671d3207a94 | []
| no_license | sanioglusena/Kalah-Game-In-Java | fd91524c03d4b55567074d1cfacaccf2fec8dc1e | 887521b80d7e4e64b8a245e6c9ea47ef4856323c | refs/heads/master | 2020-03-28T23:44:58.568559 | 2018-09-18T15:02:18 | 2018-09-18T15:02:18 | 149,306,651 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 320 | java | package com.example.java.KalahApplication.Repository;
import com.example.java.KalahApplication.Entity.GameBoard;
public interface GameBoardRepository {
public GameBoard save(GameBoard gameBoard);
public GameBoard find(Long id);
public void update(GameBoard gameBoard);
public Long getUniqueId();
}
| [
"[email protected]"
]
| |
2513b6f6855fafb1e5c33dc08bf63b471f532d3d | 0660ce4e29ed8e5b6e8b614b3db8a5c412f5378e | /Cours/src/TD1/Cercle.java | 7c266ec7908da215b07e1c119d19994b4990ea1f | []
| no_license | david-charbonnier/TP-Cours | 1e7f502798c21f268f1d5f131954ed637c99a538 | eac5352c1a6e7a6cff7348e2e123532315429954 | refs/heads/master | 2016-09-10T10:40:55.862268 | 2011-09-09T19:22:33 | 2011-09-09T19:22:33 | 2,357,497 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 61 | java | package TD1;
public class Cercle extends MaFigure {
}
| [
"[email protected]"
]
| |
aa11cb691eddbfd031a4bb00cd546a1e813051f1 | d5708bed37003f38209cf46c4be5d023df9b4c0f | /truyum_practice/src/com/cognizant/truyum/servlet/RemoveCartServlet.java | 1432be883f05f8c6d99a069c751b1ea415ae7d93 | []
| no_license | UdhY07/truyum_practice | 02d10c7d3dd198719be62ad8944db8dd6aae054a | aa078cf7f2db2a05ade0381b523cf5e1604c70ab | refs/heads/master | 2020-09-24T16:36:22.625215 | 2019-12-05T04:41:18 | 2019-12-05T04:41:18 | 225,799,847 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,047 | java | package com.cognizant.truyum.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.cognizant.truyum.dao.CartDao;
import com.cognizant.truyum.dao.CartDaoSqlImpl;
import com.cognizant.truyum.model.MenuItem;
/**
* Servlet implementation class RemoveCartServlet
*/
@WebServlet("/RemoveCartServlet")
public class RemoveCartServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public RemoveCartServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
long userId = 1;
String menuitemId = request.getParameter("menuItemId");
System.out.println(menuitemId);
int menuItemId = Integer.parseInt(menuitemId);
CartDaoSqlImpl cartDaoSqlImpl = new CartDaoSqlImpl();
CartDao cartDao = cartDaoSqlImpl;
cartDao.removeCartItem(userId, menuItemId);
try {
List<MenuItem> menuItemList = cartDao.getAllCartItems(userId);
request.setAttribute("removeCartItemStatus", true);
request.setAttribute("cartMenuList", menuItemList);
request.getRequestDispatcher("cart.jsp").forward(request, response);
} catch (Exception e) {
request.getRequestDispatcher("cart-empty.jsp").forward(request,
response);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
| [
"[email protected]"
]
| |
f9eb6a0d6ebb35be3bffd9f79694fbed6649d28f | faaf0bc6c829a453e8b0dc2a01c5e225e872d6c1 | /lib/src/main/java/org/spatialite/database/SQLiteStatementInfo.java | c1caef0a450e913f63a32799dbbc246146b31f1d | [
"Apache-2.0"
]
| permissive | dalgarins/android-spatialite | e57ef399fbc11e22f8796d80e03f0014f3d04066 | 61b34e6a918007e0b005823811a6d9cabe89fdad | refs/heads/master | 2023-06-26T20:10:44.838015 | 2023-06-11T12:21:01 | 2023-06-11T12:21:01 | 261,042,046 | 1 | 1 | null | 2023-06-11T12:21:02 | 2020-05-03T23:41:59 | C | UTF-8 | Java | false | false | 1,137 | java | /*
* Copyright (C) 2011 The Android Open Source Project
*
* 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.
*/
// modified from original source see README at the top level of this project
package org.spatialite.database;
/**
* Describes a SQLite statement.
*
* @hide
*/
public final class SQLiteStatementInfo {
/**
* The number of parameters that the statement has.
*/
public int numParameters;
/**
* The names of all columns in the result set of the statement.
*/
public String[] columnNames;
/**
* True if the statement is read-only.
*/
public boolean readOnly;
}
| [
"[email protected]"
]
| |
88c0379e24db01ffd209c339f1da85dce967582a | 5598faaaaa6b3d1d8502cbdaca903f9037d99600 | /code_changes/Apache_projects/HDFS-10438/e7b56cf93c7ac269e40b556875f16d0c5ad2f819/~MiniDFSCluster.java | 98f057329780da9aabe07718515f55eaf7986a21 | []
| no_license | SPEAR-SE/LogInBugReportsEmpirical_Data | 94d1178346b4624ebe90cf515702fac86f8e2672 | ab9603c66899b48b0b86bdf63ae7f7a604212b29 | refs/heads/master | 2022-12-18T02:07:18.084659 | 2020-09-09T16:49:34 | 2020-09-09T16:49:34 | 286,338,252 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 111,389 | java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs;
import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY;
import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.NET_TOPOLOGY_NODE_SWITCH_MAPPING_IMPL_KEY;
import static org.apache.hadoop.fs.CommonConfigurationKeys.IPC_CLIENT_CONNECT_MAX_RETRIES_ON_SASL_DEFAULT;
import static org.apache.hadoop.fs.CommonConfigurationKeys.IPC_CLIENT_CONNECT_MAX_RETRIES_ON_SASL_KEY;
import static org.apache.hadoop.hdfs.client.HdfsClientConfigKeys.DFS_DATA_TRANSFER_PROTECTION_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_BLOCKREPORT_INITIAL_DELAY_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_ADDRESS_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_HOST_NAME_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_HTTP_ADDRESS_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_DATANODE_IPC_ADDRESS_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_HA_LOGROLL_PERIOD_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_HA_NAMENODES_KEY_PREFIX;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_HA_NAMENODE_ID_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_HA_STANDBY_CHECKPOINTS_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_HOSTS;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_CHECKPOINT_DIR_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_DECOMMISSION_INTERVAL_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_HTTPS_ADDRESS_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_LIFELINE_RPC_ADDRESS_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_NAME_DIR_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_SAFEMODE_EXTENSION_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_SERVICE_RPC_ADDRESS_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_SHARED_EDITS_DIR_KEY;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMESERVICES;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMESERVICE_ID;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_REPLICATION_KEY;
import static org.apache.hadoop.hdfs.server.common.Util.fileAsURI;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeoutException;
import com.google.common.base.Supplier;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.StorageType;
import org.apache.hadoop.ha.HAServiceProtocol.RequestSource;
import org.apache.hadoop.ha.HAServiceProtocol.StateChangeRequestInfo;
import org.apache.hadoop.ha.ServiceFailedException;
import org.apache.hadoop.hdfs.MiniDFSNNTopology.NNConf;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.protocol.BlockListAsLongs;
import org.apache.hadoop.hdfs.protocol.ClientProtocol;
import org.apache.hadoop.hdfs.protocol.DatanodeID;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.DatanodeReportType;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockManagerTestUtil;
import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeDescriptor;
import org.apache.hadoop.hdfs.server.blockmanagement.DatanodeManager;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.StartupOption;
import org.apache.hadoop.hdfs.server.common.Storage;
import org.apache.hadoop.hdfs.server.common.Util;
import org.apache.hadoop.hdfs.server.datanode.DataNode;
import org.apache.hadoop.hdfs.server.datanode.DataNodeTestUtils;
import org.apache.hadoop.hdfs.server.datanode.DataStorage;
import org.apache.hadoop.hdfs.server.datanode.DatanodeUtil;
import org.apache.hadoop.hdfs.server.datanode.FsDatasetTestUtils;
import org.apache.hadoop.hdfs.server.datanode.FsDatasetTestUtils.MaterializedReplica;
import org.apache.hadoop.hdfs.server.datanode.ReplicaNotFoundException;
import org.apache.hadoop.hdfs.server.datanode.SecureDataNodeStarter;
import org.apache.hadoop.hdfs.server.datanode.SecureDataNodeStarter.SecureResources;
import org.apache.hadoop.hdfs.server.datanode.SimulatedFSDataset;
import org.apache.hadoop.hdfs.server.datanode.fsdataset.FsDatasetSpi;
import org.apache.hadoop.hdfs.server.datanode.fsdataset.FsVolumeSpi;
import org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.FsDatasetUtil;
import org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.FsVolumeImpl;
import org.apache.hadoop.hdfs.server.namenode.EditLogFileOutputStream;
import org.apache.hadoop.hdfs.server.namenode.FSNamesystem;
import org.apache.hadoop.hdfs.server.namenode.NameNode;
import org.apache.hadoop.hdfs.server.namenode.NameNodeAdapter;
import org.apache.hadoop.hdfs.server.protocol.DatanodeStorage;
import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocols;
import org.apache.hadoop.hdfs.tools.DFSAdmin;
import org.apache.hadoop.hdfs.web.HftpFileSystem;
import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
import org.apache.hadoop.net.DNSToSwitchMapping;
import org.apache.hadoop.net.NetUtils;
import org.apache.hadoop.net.StaticMapping;
import org.apache.hadoop.security.SecurityUtil;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.authorize.ProxyUsers;
import org.apache.hadoop.test.GenericTestUtils;
import org.apache.hadoop.util.ExitUtil;
import org.apache.hadoop.util.ShutdownHookManager;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.ToolRunner;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
/**
* This class creates a single-process DFS cluster for junit testing.
* The data directories for non-simulated DFS are under the testing directory.
* For simulated data nodes, no underlying fs storage is used.
*/
@InterfaceAudience.LimitedPrivate({"HBase", "HDFS", "Hive", "MapReduce", "Pig"})
@InterfaceStability.Unstable
public class MiniDFSCluster {
private static final String NAMESERVICE_ID_PREFIX = "nameserviceId";
private static final Log LOG = LogFactory.getLog(MiniDFSCluster.class);
/** System property to set the data dir: {@value} */
public static final String PROP_TEST_BUILD_DATA = "test.build.data";
/** Configuration option to set the data dir: {@value} */
public static final String HDFS_MINIDFS_BASEDIR = "hdfs.minidfs.basedir";
public static final String DFS_NAMENODE_SAFEMODE_EXTENSION_TESTING_KEY
= DFS_NAMENODE_SAFEMODE_EXTENSION_KEY + ".testing";
// Changing this default may break some tests that assume it is 2.
private static final int DEFAULT_STORAGES_PER_DATANODE = 2;
static { DefaultMetricsSystem.setMiniClusterMode(true); }
public int getStoragesPerDatanode() {
return storagesPerDatanode;
}
/**
* Class to construct instances of MiniDFSClusters with specific options.
*/
public static class Builder {
private int nameNodePort = 0;
private int nameNodeHttpPort = 0;
private final Configuration conf;
private int numDataNodes = 1;
private StorageType[][] storageTypes = null;
private StorageType[] storageTypes1D = null;
private int storagesPerDatanode = DEFAULT_STORAGES_PER_DATANODE;
private boolean format = true;
private boolean manageNameDfsDirs = true;
private boolean manageNameDfsSharedDirs = true;
private boolean enableManagedDfsDirsRedundancy = true;
private boolean manageDataDfsDirs = true;
private StartupOption option = null;
private StartupOption dnOption = null;
private String[] racks = null;
private String [] hosts = null;
private long [] simulatedCapacities = null;
private long [][] storageCapacities = null;
private long [] storageCapacities1D = null;
private String clusterId = null;
private boolean waitSafeMode = true;
private boolean setupHostsFile = false;
private MiniDFSNNTopology nnTopology = null;
private boolean checkExitOnShutdown = true;
private boolean checkDataNodeAddrConfig = false;
private boolean checkDataNodeHostConfig = false;
private Configuration[] dnConfOverlays;
private boolean skipFsyncForTesting = true;
private boolean useConfiguredTopologyMappingClass = false;
public Builder(Configuration conf) {
this.conf = conf;
this.storagesPerDatanode =
FsDatasetTestUtils.Factory.getFactory(conf).getDefaultNumOfDataDirs();
}
/**
* Default: 0
*/
public Builder nameNodePort(int val) {
this.nameNodePort = val;
return this;
}
/**
* Default: 0
*/
public Builder nameNodeHttpPort(int val) {
this.nameNodeHttpPort = val;
return this;
}
/**
* Default: 1
*/
public Builder numDataNodes(int val) {
this.numDataNodes = val;
return this;
}
/**
* Default: DEFAULT_STORAGES_PER_DATANODE
*/
public Builder storagesPerDatanode(int numStorages) {
this.storagesPerDatanode = numStorages;
return this;
}
/**
* Set the same storage type configuration for each datanode.
* If storageTypes is uninitialized or passed null then
* StorageType.DEFAULT is used.
*/
public Builder storageTypes(StorageType[] types) {
this.storageTypes1D = types;
return this;
}
/**
* Set custom storage type configuration for each datanode.
* If storageTypes is uninitialized or passed null then
* StorageType.DEFAULT is used.
*/
public Builder storageTypes(StorageType[][] types) {
this.storageTypes = types;
return this;
}
/**
* Set the same storage capacity configuration for each datanode.
* If storageTypes is uninitialized or passed null then
* StorageType.DEFAULT is used.
*/
public Builder storageCapacities(long[] capacities) {
this.storageCapacities1D = capacities;
return this;
}
/**
* Set custom storage capacity configuration for each datanode.
* If storageCapacities is uninitialized or passed null then
* capacity is limited by available disk space.
*/
public Builder storageCapacities(long[][] capacities) {
this.storageCapacities = capacities;
return this;
}
/**
* Default: true
*/
public Builder format(boolean val) {
this.format = val;
return this;
}
/**
* Default: true
*/
public Builder manageNameDfsDirs(boolean val) {
this.manageNameDfsDirs = val;
return this;
}
/**
* Default: true
*/
public Builder manageNameDfsSharedDirs(boolean val) {
this.manageNameDfsSharedDirs = val;
return this;
}
/**
* Default: true
*/
public Builder enableManagedDfsDirsRedundancy(boolean val) {
this.enableManagedDfsDirsRedundancy = val;
return this;
}
/**
* Default: true
*/
public Builder manageDataDfsDirs(boolean val) {
this.manageDataDfsDirs = val;
return this;
}
/**
* Default: null
*/
public Builder startupOption(StartupOption val) {
this.option = val;
return this;
}
/**
* Default: null
*/
public Builder dnStartupOption(StartupOption val) {
this.dnOption = val;
return this;
}
/**
* Default: null
*/
public Builder racks(String[] val) {
this.racks = val;
return this;
}
/**
* Default: null
*/
public Builder hosts(String[] val) {
this.hosts = val;
return this;
}
/**
* Use SimulatedFSDataset and limit the capacity of each DN per
* the values passed in val.
*
* For limiting the capacity of volumes with real storage, see
* {@link FsVolumeImpl#setCapacityForTesting}
* Default: null
*/
public Builder simulatedCapacities(long[] val) {
this.simulatedCapacities = val;
return this;
}
/**
* Default: true
*/
public Builder waitSafeMode(boolean val) {
this.waitSafeMode = val;
return this;
}
/**
* Default: true
*/
public Builder checkExitOnShutdown(boolean val) {
this.checkExitOnShutdown = val;
return this;
}
/**
* Default: false
*/
public Builder checkDataNodeAddrConfig(boolean val) {
this.checkDataNodeAddrConfig = val;
return this;
}
/**
* Default: false
*/
public Builder checkDataNodeHostConfig(boolean val) {
this.checkDataNodeHostConfig = val;
return this;
}
/**
* Default: null
*/
public Builder clusterId(String cid) {
this.clusterId = cid;
return this;
}
/**
* Default: false
* When true the hosts file/include file for the cluster is setup
*/
public Builder setupHostsFile(boolean val) {
this.setupHostsFile = val;
return this;
}
/**
* Default: a single namenode.
* See {@link MiniDFSNNTopology#simpleFederatedTopology(int)} to set up
* federated nameservices
*/
public Builder nnTopology(MiniDFSNNTopology topology) {
this.nnTopology = topology;
return this;
}
/**
* Default: null
*
* An array of {@link Configuration} objects that will overlay the
* global MiniDFSCluster Configuration for the corresponding DataNode.
*
* Useful for setting specific per-DataNode configuration parameters.
*/
public Builder dataNodeConfOverlays(Configuration[] dnConfOverlays) {
this.dnConfOverlays = dnConfOverlays;
return this;
}
/**
* Default: true
* When true, we skip fsync() calls for speed improvements.
*/
public Builder skipFsyncForTesting(boolean val) {
this.skipFsyncForTesting = val;
return this;
}
public Builder useConfiguredTopologyMappingClass(
boolean useConfiguredTopologyMappingClass) {
this.useConfiguredTopologyMappingClass =
useConfiguredTopologyMappingClass;
return this;
}
/**
* Construct the actual MiniDFSCluster
*/
public MiniDFSCluster build() throws IOException {
return new MiniDFSCluster(this);
}
}
/**
* Used by builder to create and return an instance of MiniDFSCluster
*/
protected MiniDFSCluster(Builder builder) throws IOException {
if (builder.nnTopology == null) {
// If no topology is specified, build a single NN.
builder.nnTopology = MiniDFSNNTopology.simpleSingleNN(
builder.nameNodePort, builder.nameNodeHttpPort);
}
assert builder.storageTypes == null ||
builder.storageTypes.length == builder.numDataNodes;
final int numNameNodes = builder.nnTopology.countNameNodes();
LOG.info("starting cluster: numNameNodes=" + numNameNodes
+ ", numDataNodes=" + builder.numDataNodes);
nameNodes = new NameNodeInfo[numNameNodes];
this.storagesPerDatanode = builder.storagesPerDatanode;
// Duplicate the storageType setting for each DN.
if (builder.storageTypes == null && builder.storageTypes1D != null) {
assert builder.storageTypes1D.length == storagesPerDatanode;
builder.storageTypes = new StorageType[builder.numDataNodes][storagesPerDatanode];
for (int i = 0; i < builder.numDataNodes; ++i) {
builder.storageTypes[i] = builder.storageTypes1D;
}
}
// Duplicate the storageCapacity setting for each DN.
if (builder.storageCapacities == null && builder.storageCapacities1D != null) {
assert builder.storageCapacities1D.length == storagesPerDatanode;
builder.storageCapacities = new long[builder.numDataNodes][storagesPerDatanode];
for (int i = 0; i < builder.numDataNodes; ++i) {
builder.storageCapacities[i] = builder.storageCapacities1D;
}
}
initMiniDFSCluster(builder.conf,
builder.numDataNodes,
builder.storageTypes,
builder.format,
builder.manageNameDfsDirs,
builder.manageNameDfsSharedDirs,
builder.enableManagedDfsDirsRedundancy,
builder.manageDataDfsDirs,
builder.option,
builder.dnOption,
builder.racks,
builder.hosts,
builder.storageCapacities,
builder.simulatedCapacities,
builder.clusterId,
builder.waitSafeMode,
builder.setupHostsFile,
builder.nnTopology,
builder.checkExitOnShutdown,
builder.checkDataNodeAddrConfig,
builder.checkDataNodeHostConfig,
builder.dnConfOverlays,
builder.skipFsyncForTesting,
builder.useConfiguredTopologyMappingClass);
}
public class DataNodeProperties {
final DataNode datanode;
final Configuration conf;
String[] dnArgs;
final SecureResources secureResources;
final int ipcPort;
DataNodeProperties(DataNode node, Configuration conf, String[] args,
SecureResources secureResources, int ipcPort) {
this.datanode = node;
this.conf = conf;
this.dnArgs = args;
this.secureResources = secureResources;
this.ipcPort = ipcPort;
}
public void setDnArgs(String ... args) {
dnArgs = args;
}
}
private Configuration conf;
private NameNodeInfo[] nameNodes;
protected int numDataNodes;
protected final ArrayList<DataNodeProperties> dataNodes =
new ArrayList<DataNodeProperties>();
private File base_dir;
private File data_dir;
private boolean waitSafeMode = true;
private boolean federation;
private boolean checkExitOnShutdown = true;
protected final int storagesPerDatanode;
private Set<FileSystem> fileSystems = Sets.newHashSet();
/**
* A unique instance identifier for the cluster. This
* is used to disambiguate HA filesystems in the case where
* multiple MiniDFSClusters are used in the same test suite.
*/
private int instanceId;
private static int instanceCount = 0;
/**
* Stores the information related to a namenode in the cluster
*/
public static class NameNodeInfo {
final NameNode nameNode;
final Configuration conf;
final String nameserviceId;
final String nnId;
StartupOption startOpt;
NameNodeInfo(NameNode nn, String nameserviceId, String nnId,
StartupOption startOpt, Configuration conf) {
this.nameNode = nn;
this.nameserviceId = nameserviceId;
this.nnId = nnId;
this.startOpt = startOpt;
this.conf = conf;
}
public void setStartOpt(StartupOption startOpt) {
this.startOpt = startOpt;
}
}
/**
* This null constructor is used only when wishing to start a data node cluster
* without a name node (ie when the name node is started elsewhere).
*/
public MiniDFSCluster() {
nameNodes = new NameNodeInfo[0]; // No namenode in the cluster
storagesPerDatanode = DEFAULT_STORAGES_PER_DATANODE;
synchronized (MiniDFSCluster.class) {
instanceId = instanceCount++;
}
}
/**
* Modify the config and start up the servers with the given operation.
* Servers will be started on free ports.
* <p>
* The caller must manage the creation of NameNode and DataNode directories
* and have already set {@link DFSConfigKeys#DFS_NAMENODE_NAME_DIR_KEY} and
* {@link DFSConfigKeys#DFS_DATANODE_DATA_DIR_KEY} in the given conf.
*
* @param conf the base configuration to use in starting the servers. This
* will be modified as necessary.
* @param numDataNodes Number of DataNodes to start; may be zero
* @param nameNodeOperation the operation with which to start the servers. If null
* or StartupOption.FORMAT, then StartupOption.REGULAR will be used.
*/
@Deprecated // in 22 to be removed in 24. Use MiniDFSCluster.Builder instead
public MiniDFSCluster(Configuration conf,
int numDataNodes,
StartupOption nameNodeOperation) throws IOException {
this(0, conf, numDataNodes, false, false, false, nameNodeOperation,
null, null, null);
}
/**
* Modify the config and start up the servers. The rpc and info ports for
* servers are guaranteed to use free ports.
* <p>
* NameNode and DataNode directory creation and configuration will be
* managed by this class.
*
* @param conf the base configuration to use in starting the servers. This
* will be modified as necessary.
* @param numDataNodes Number of DataNodes to start; may be zero
* @param format if true, format the NameNode and DataNodes before starting up
* @param racks array of strings indicating the rack that each DataNode is on
*/
@Deprecated // in 22 to be removed in 24. Use MiniDFSCluster.Builder instead
public MiniDFSCluster(Configuration conf,
int numDataNodes,
boolean format,
String[] racks) throws IOException {
this(0, conf, numDataNodes, format, true, true, null, racks, null, null);
}
/**
* Modify the config and start up the servers. The rpc and info ports for
* servers are guaranteed to use free ports.
* <p>
* NameNode and DataNode directory creation and configuration will be
* managed by this class.
*
* @param conf the base configuration to use in starting the servers. This
* will be modified as necessary.
* @param numDataNodes Number of DataNodes to start; may be zero
* @param format if true, format the NameNode and DataNodes before starting up
* @param racks array of strings indicating the rack that each DataNode is on
* @param hosts array of strings indicating the hostname for each DataNode
*/
@Deprecated // in 22 to be removed in 24. Use MiniDFSCluster.Builder instead
public MiniDFSCluster(Configuration conf,
int numDataNodes,
boolean format,
String[] racks, String[] hosts) throws IOException {
this(0, conf, numDataNodes, format, true, true, null, racks, hosts, null);
}
/**
* NOTE: if possible, the other constructors that don't have nameNode port
* parameter should be used as they will ensure that the servers use free
* ports.
* <p>
* Modify the config and start up the servers.
*
* @param nameNodePort suggestion for which rpc port to use. caller should
* use getNameNodePort() to get the actual port used.
* @param conf the base configuration to use in starting the servers. This
* will be modified as necessary.
* @param numDataNodes Number of DataNodes to start; may be zero
* @param format if true, format the NameNode and DataNodes before starting
* up
* @param manageDfsDirs if true, the data directories for servers will be
* created and {@link DFSConfigKeys#DFS_NAMENODE_NAME_DIR_KEY} and
* {@link DFSConfigKeys#DFS_DATANODE_DATA_DIR_KEY} will be set in
* the conf
* @param operation the operation with which to start the servers. If null
* or StartupOption.FORMAT, then StartupOption.REGULAR will be used.
* @param racks array of strings indicating the rack that each DataNode is on
*/
@Deprecated // in 22 to be removed in 24. Use MiniDFSCluster.Builder instead
public MiniDFSCluster(int nameNodePort,
Configuration conf,
int numDataNodes,
boolean format,
boolean manageDfsDirs,
StartupOption operation,
String[] racks) throws IOException {
this(nameNodePort, conf, numDataNodes, format, manageDfsDirs, manageDfsDirs,
operation, racks, null, null);
}
/**
* NOTE: if possible, the other constructors that don't have nameNode port
* parameter should be used as they will ensure that the servers use free ports.
* <p>
* Modify the config and start up the servers.
*
* @param nameNodePort suggestion for which rpc port to use. caller should
* use getNameNodePort() to get the actual port used.
* @param conf the base configuration to use in starting the servers. This
* will be modified as necessary.
* @param numDataNodes Number of DataNodes to start; may be zero
* @param format if true, format the NameNode and DataNodes before starting up
* @param manageDfsDirs if true, the data directories for servers will be
* created and {@link DFSConfigKeys#DFS_NAMENODE_NAME_DIR_KEY} and
* {@link DFSConfigKeys#DFS_DATANODE_DATA_DIR_KEY} will be set in
* the conf
* @param operation the operation with which to start the servers. If null
* or StartupOption.FORMAT, then StartupOption.REGULAR will be used.
* @param racks array of strings indicating the rack that each DataNode is on
* @param simulatedCapacities array of capacities of the simulated data nodes
*/
@Deprecated // in 22 to be removed in 24. Use MiniDFSCluster.Builder instead
public MiniDFSCluster(int nameNodePort,
Configuration conf,
int numDataNodes,
boolean format,
boolean manageDfsDirs,
StartupOption operation,
String[] racks,
long[] simulatedCapacities) throws IOException {
this(nameNodePort, conf, numDataNodes, format, manageDfsDirs, manageDfsDirs,
operation, racks, null, simulatedCapacities);
}
/**
* NOTE: if possible, the other constructors that don't have nameNode port
* parameter should be used as they will ensure that the servers use free ports.
* <p>
* Modify the config and start up the servers.
*
* @param nameNodePort suggestion for which rpc port to use. caller should
* use getNameNodePort() to get the actual port used.
* @param conf the base configuration to use in starting the servers. This
* will be modified as necessary.
* @param numDataNodes Number of DataNodes to start; may be zero
* @param format if true, format the NameNode and DataNodes before starting up
* @param manageNameDfsDirs if true, the data directories for servers will be
* created and {@link DFSConfigKeys#DFS_NAMENODE_NAME_DIR_KEY} and
* {@link DFSConfigKeys#DFS_DATANODE_DATA_DIR_KEY} will be set in
* the conf
* @param manageDataDfsDirs if true, the data directories for datanodes will
* be created and {@link DFSConfigKeys#DFS_DATANODE_DATA_DIR_KEY}
* set to same in the conf
* @param operation the operation with which to start the servers. If null
* or StartupOption.FORMAT, then StartupOption.REGULAR will be used.
* @param racks array of strings indicating the rack that each DataNode is on
* @param hosts array of strings indicating the hostnames of each DataNode
* @param simulatedCapacities array of capacities of the simulated data nodes
*/
@Deprecated // in 22 to be removed in 24. Use MiniDFSCluster.Builder instead
public MiniDFSCluster(int nameNodePort,
Configuration conf,
int numDataNodes,
boolean format,
boolean manageNameDfsDirs,
boolean manageDataDfsDirs,
StartupOption operation,
String[] racks, String hosts[],
long[] simulatedCapacities) throws IOException {
this.nameNodes = new NameNodeInfo[1]; // Single namenode in the cluster
this.storagesPerDatanode = DEFAULT_STORAGES_PER_DATANODE;
initMiniDFSCluster(conf, numDataNodes, null, format,
manageNameDfsDirs, true, manageDataDfsDirs, manageDataDfsDirs,
operation, null, racks, hosts,
null, simulatedCapacities, null, true, false,
MiniDFSNNTopology.simpleSingleNN(nameNodePort, 0),
true, false, false, null, true, false);
}
private void initMiniDFSCluster(
Configuration conf,
int numDataNodes, StorageType[][] storageTypes, boolean format,
boolean manageNameDfsDirs,
boolean manageNameDfsSharedDirs, boolean enableManagedDfsDirsRedundancy,
boolean manageDataDfsDirs, StartupOption startOpt,
StartupOption dnStartOpt, String[] racks,
String[] hosts,
long[][] storageCapacities, long[] simulatedCapacities, String clusterId,
boolean waitSafeMode, boolean setupHostsFile,
MiniDFSNNTopology nnTopology, boolean checkExitOnShutdown,
boolean checkDataNodeAddrConfig,
boolean checkDataNodeHostConfig,
Configuration[] dnConfOverlays,
boolean skipFsyncForTesting,
boolean useConfiguredTopologyMappingClass)
throws IOException {
boolean success = false;
try {
ExitUtil.disableSystemExit();
// Re-enable symlinks for tests, see HADOOP-10020 and HADOOP-10052
FileSystem.enableSymlinks();
synchronized (MiniDFSCluster.class) {
instanceId = instanceCount++;
}
this.conf = conf;
base_dir = new File(determineDfsBaseDir());
data_dir = new File(base_dir, "data");
this.waitSafeMode = waitSafeMode;
this.checkExitOnShutdown = checkExitOnShutdown;
int replication = conf.getInt(DFS_REPLICATION_KEY, 3);
conf.setInt(DFS_REPLICATION_KEY, Math.min(replication, numDataNodes));
int safemodeExtension = conf.getInt(
DFS_NAMENODE_SAFEMODE_EXTENSION_TESTING_KEY, 0);
conf.setInt(DFS_NAMENODE_SAFEMODE_EXTENSION_KEY, safemodeExtension);
conf.setInt(DFS_NAMENODE_DECOMMISSION_INTERVAL_KEY, 3); // 3 second
if (!useConfiguredTopologyMappingClass) {
conf.setClass(NET_TOPOLOGY_NODE_SWITCH_MAPPING_IMPL_KEY,
StaticMapping.class, DNSToSwitchMapping.class);
}
// In an HA cluster, in order for the StandbyNode to perform checkpoints,
// it needs to know the HTTP port of the Active. So, if ephemeral ports
// are chosen, disable checkpoints for the test.
if (!nnTopology.allHttpPortsSpecified() &&
nnTopology.isHA()) {
LOG.info("MiniDFSCluster disabling checkpointing in the Standby node " +
"since no HTTP ports have been specified.");
conf.setBoolean(DFS_HA_STANDBY_CHECKPOINTS_KEY, false);
}
if (!nnTopology.allIpcPortsSpecified() &&
nnTopology.isHA()) {
LOG.info("MiniDFSCluster disabling log-roll triggering in the "
+ "Standby node since no IPC ports have been specified.");
conf.setInt(DFS_HA_LOGROLL_PERIOD_KEY, -1);
}
EditLogFileOutputStream.setShouldSkipFsyncForTesting(skipFsyncForTesting);
federation = nnTopology.isFederated();
try {
createNameNodesAndSetConf(
nnTopology, manageNameDfsDirs, manageNameDfsSharedDirs,
enableManagedDfsDirsRedundancy,
format, startOpt, clusterId, conf);
} catch (IOException ioe) {
LOG.error("IOE creating namenodes. Permissions dump:\n" +
createPermissionsDiagnosisString(data_dir), ioe);
throw ioe;
}
if (format) {
if (data_dir.exists() && !FileUtil.fullyDelete(data_dir)) {
throw new IOException("Cannot remove data directory: " + data_dir +
createPermissionsDiagnosisString(data_dir));
}
}
if (startOpt == StartupOption.RECOVER) {
return;
}
// Start the DataNodes
startDataNodes(conf, numDataNodes, storageTypes, manageDataDfsDirs,
dnStartOpt != null ? dnStartOpt : startOpt,
racks, hosts, storageCapacities, simulatedCapacities, setupHostsFile,
checkDataNodeAddrConfig, checkDataNodeHostConfig, dnConfOverlays);
waitClusterUp();
//make sure ProxyUsers uses the latest conf
ProxyUsers.refreshSuperUserGroupsConfiguration(conf);
success = true;
} finally {
if (!success) {
shutdown();
}
}
for (NameNodeInfo nn : nameNodes) {
Configuration nnConf = nn.conf;
for (NameNodeInfo nnInfo : nameNodes) {
if (nn.equals(nnInfo)) {
continue;
}
copyKeys(conf, nnConf, nnInfo.nameserviceId, nnInfo.nnId);
}
}
}
private static void copyKeys(Configuration srcConf, Configuration destConf,
String nameserviceId, String nnId) {
String key = DFSUtil.addKeySuffixes(DFS_NAMENODE_RPC_ADDRESS_KEY,
nameserviceId, nnId);
destConf.set(key, srcConf.get(key));
copyKey(srcConf, destConf, nameserviceId, nnId,
DFS_NAMENODE_HTTP_ADDRESS_KEY);
copyKey(srcConf, destConf, nameserviceId, nnId,
DFS_NAMENODE_HTTPS_ADDRESS_KEY);
copyKey(srcConf, destConf, nameserviceId, nnId,
DFS_NAMENODE_LIFELINE_RPC_ADDRESS_KEY);
copyKey(srcConf, destConf, nameserviceId, nnId,
DFS_NAMENODE_SERVICE_RPC_ADDRESS_KEY);
}
private static void copyKey(Configuration srcConf, Configuration destConf,
String nameserviceId, String nnId, String baseKey) {
String key = DFSUtil.addKeySuffixes(baseKey, nameserviceId, nnId);
String val = srcConf.get(key);
if (val != null) {
destConf.set(key, srcConf.get(key));
}
}
/**
* @return a debug string which can help diagnose an error of why
* a given directory might have a permissions error in the context
* of a test case
*/
private String createPermissionsDiagnosisString(File path) {
StringBuilder sb = new StringBuilder();
while (path != null) {
sb.append("path '" + path + "': ").append("\n");
sb.append("\tabsolute:").append(path.getAbsolutePath()).append("\n");
sb.append("\tpermissions: ");
sb.append(path.isDirectory() ? "d": "-");
sb.append(FileUtil.canRead(path) ? "r" : "-");
sb.append(FileUtil.canWrite(path) ? "w" : "-");
sb.append(FileUtil.canExecute(path) ? "x" : "-");
sb.append("\n");
path = path.getParentFile();
}
return sb.toString();
}
private void createNameNodesAndSetConf(MiniDFSNNTopology nnTopology,
boolean manageNameDfsDirs, boolean manageNameDfsSharedDirs,
boolean enableManagedDfsDirsRedundancy, boolean format,
StartupOption operation, String clusterId,
Configuration conf) throws IOException {
Preconditions.checkArgument(nnTopology.countNameNodes() > 0,
"empty NN topology: no namenodes specified!");
if (!federation && nnTopology.countNameNodes() == 1) {
NNConf onlyNN = nnTopology.getOnlyNameNode();
// we only had one NN, set DEFAULT_NAME for it. If not explicitly
// specified initially, the port will be 0 to make NN bind to any
// available port. It will be set to the right address after
// NN is started.
conf.set(FS_DEFAULT_NAME_KEY, "hdfs://127.0.0.1:" + onlyNN.getIpcPort());
}
List<String> allNsIds = Lists.newArrayList();
for (MiniDFSNNTopology.NSConf nameservice : nnTopology.getNameservices()) {
if (nameservice.getId() != null) {
allNsIds.add(nameservice.getId());
}
}
if (!allNsIds.isEmpty()) {
conf.set(DFS_NAMESERVICES, Joiner.on(",").join(allNsIds));
}
int nnCounter = 0;
for (MiniDFSNNTopology.NSConf nameservice : nnTopology.getNameservices()) {
String nsId = nameservice.getId();
String lastDefaultFileSystem = null;
Preconditions.checkArgument(
!federation || nsId != null,
"if there is more than one NS, they must have names");
// First set up the configuration which all of the NNs
// need to have - have to do this a priori before starting
// *any* of the NNs, so they know to come up in standby.
List<String> nnIds = Lists.newArrayList();
// Iterate over the NNs in this nameservice
for (NNConf nn : nameservice.getNNs()) {
nnIds.add(nn.getNnId());
initNameNodeAddress(conf, nameservice.getId(), nn);
}
// If HA is enabled on this nameservice, enumerate all the namenodes
// in the configuration. Also need to set a shared edits dir
if (nnIds.size() > 1) {
conf.set(DFSUtil.addKeySuffixes(DFS_HA_NAMENODES_KEY_PREFIX, nameservice.getId()),
Joiner.on(",").join(nnIds));
if (manageNameDfsSharedDirs) {
URI sharedEditsUri = getSharedEditsDir(nnCounter, nnCounter+nnIds.size()-1);
conf.set(DFS_NAMENODE_SHARED_EDITS_DIR_KEY, sharedEditsUri.toString());
// Clean out the shared edits dir completely, including all subdirectories.
FileUtil.fullyDelete(new File(sharedEditsUri));
}
}
// Now format first NN and copy the storage directory from that node to the others.
int i = 0;
Collection<URI> prevNNDirs = null;
int nnCounterForFormat = nnCounter;
for (NNConf nn : nameservice.getNNs()) {
initNameNodeConf(conf, nsId, nn.getNnId(), manageNameDfsDirs,
enableManagedDfsDirsRedundancy, nnCounterForFormat);
Collection<URI> namespaceDirs = FSNamesystem.getNamespaceDirs(conf);
if (format) {
for (URI nameDirUri : namespaceDirs) {
File nameDir = new File(nameDirUri);
if (nameDir.exists() && !FileUtil.fullyDelete(nameDir)) {
throw new IOException("Could not fully delete " + nameDir);
}
}
Collection<URI> checkpointDirs = Util.stringCollectionAsURIs(conf
.getTrimmedStringCollection(DFS_NAMENODE_CHECKPOINT_DIR_KEY));
for (URI checkpointDirUri : checkpointDirs) {
File checkpointDir = new File(checkpointDirUri);
if (checkpointDir.exists() && !FileUtil.fullyDelete(checkpointDir)) {
throw new IOException("Could not fully delete " + checkpointDir);
}
}
}
boolean formatThisOne = format;
if (format && i++ > 0) {
// Don't format the second NN in an HA setup - that
// would result in it having a different clusterID,
// block pool ID, etc. Instead, copy the name dirs
// from the first one.
formatThisOne = false;
assert (null != prevNNDirs);
copyNameDirs(prevNNDirs, namespaceDirs, conf);
}
nnCounterForFormat++;
if (formatThisOne) {
// Allow overriding clusterID for specific NNs to test
// misconfiguration.
if (nn.getClusterId() == null) {
StartupOption.FORMAT.setClusterId(clusterId);
} else {
StartupOption.FORMAT.setClusterId(nn.getClusterId());
}
DFSTestUtil.formatNameNode(conf);
}
prevNNDirs = namespaceDirs;
}
// Start all Namenodes
for (NNConf nn : nameservice.getNNs()) {
Configuration hdfsConf = new Configuration(conf);
initNameNodeConf(hdfsConf, nsId, nn.getNnId(), manageNameDfsDirs,
enableManagedDfsDirsRedundancy, nnCounter);
createNameNode(nnCounter, hdfsConf, numDataNodes, false, operation,
clusterId, nsId, nn.getNnId());
// Record the last namenode uri
lastDefaultFileSystem = hdfsConf.get(FS_DEFAULT_NAME_KEY);
nnCounter++;
}
if (!federation && lastDefaultFileSystem != null) {
// Set the default file system to the actual bind address of NN.
conf.set(FS_DEFAULT_NAME_KEY, lastDefaultFileSystem);
}
}
}
public URI getSharedEditsDir(int minNN, int maxNN) throws IOException {
return formatSharedEditsDir(base_dir, minNN, maxNN);
}
public static URI formatSharedEditsDir(File baseDir, int minNN, int maxNN)
throws IOException {
return fileAsURI(new File(baseDir, "shared-edits-" +
minNN + "-through-" + maxNN));
}
public NameNodeInfo[] getNameNodeInfos() {
return this.nameNodes;
}
private void initNameNodeConf(Configuration conf,
String nameserviceId, String nnId,
boolean manageNameDfsDirs, boolean enableManagedDfsDirsRedundancy,
int nnIndex) throws IOException {
if (nameserviceId != null) {
conf.set(DFS_NAMESERVICE_ID, nameserviceId);
}
if (nnId != null) {
conf.set(DFS_HA_NAMENODE_ID_KEY, nnId);
}
if (manageNameDfsDirs) {
if (enableManagedDfsDirsRedundancy) {
conf.set(DFS_NAMENODE_NAME_DIR_KEY,
fileAsURI(new File(base_dir, "name" + (2*nnIndex + 1)))+","+
fileAsURI(new File(base_dir, "name" + (2*nnIndex + 2))));
conf.set(DFS_NAMENODE_CHECKPOINT_DIR_KEY,
fileAsURI(new File(base_dir, "namesecondary" + (2*nnIndex + 1)))+","+
fileAsURI(new File(base_dir, "namesecondary" + (2*nnIndex + 2))));
} else {
conf.set(DFS_NAMENODE_NAME_DIR_KEY,
fileAsURI(new File(base_dir, "name" + (2*nnIndex + 1))).
toString());
conf.set(DFS_NAMENODE_CHECKPOINT_DIR_KEY,
fileAsURI(new File(base_dir, "namesecondary" + (2*nnIndex + 1))).
toString());
}
}
}
public static void copyNameDirs(Collection<URI> srcDirs, Collection<URI> dstDirs,
Configuration dstConf) throws IOException {
URI srcDir = Lists.newArrayList(srcDirs).get(0);
FileSystem dstFS = FileSystem.getLocal(dstConf).getRaw();
for (URI dstDir : dstDirs) {
Preconditions.checkArgument(!dstDir.equals(srcDir),
"src and dst are the same: " + dstDir);
File dstDirF = new File(dstDir);
if (dstDirF.exists()) {
if (!FileUtil.fullyDelete(dstDirF)) {
throw new IOException("Unable to delete: " + dstDirF);
}
}
LOG.info("Copying namedir from primary node dir "
+ srcDir + " to " + dstDir);
FileUtil.copy(
new File(srcDir),
dstFS, new Path(dstDir), false, dstConf);
}
}
/**
* Initialize the address and port for this NameNode. In the
* non-federated case, the nameservice and namenode ID may be
* null.
*/
private static void initNameNodeAddress(Configuration conf,
String nameserviceId, NNConf nnConf) {
// Set NN-specific specific key
String key = DFSUtil.addKeySuffixes(
DFS_NAMENODE_HTTP_ADDRESS_KEY, nameserviceId,
nnConf.getNnId());
conf.set(key, "127.0.0.1:" + nnConf.getHttpPort());
key = DFSUtil.addKeySuffixes(
DFS_NAMENODE_RPC_ADDRESS_KEY, nameserviceId,
nnConf.getNnId());
conf.set(key, "127.0.0.1:" + nnConf.getIpcPort());
}
private static String[] createArgs(StartupOption operation) {
if (operation == StartupOption.ROLLINGUPGRADE) {
return new String[]{operation.getName(),
operation.getRollingUpgradeStartupOption().name()};
}
String[] args = (operation == null ||
operation == StartupOption.FORMAT ||
operation == StartupOption.REGULAR) ?
new String[] {} : new String[] {operation.getName()};
return args;
}
private void createNameNode(int nnIndex, Configuration hdfsConf,
int numDataNodes, boolean format, StartupOption operation,
String clusterId, String nameserviceId,
String nnId)
throws IOException {
// Format and clean out DataNode directories
if (format) {
DFSTestUtil.formatNameNode(hdfsConf);
}
if (operation == StartupOption.UPGRADE){
operation.setClusterId(clusterId);
}
// Start the NameNode after saving the default file system.
String[] args = createArgs(operation);
NameNode nn = NameNode.createNameNode(args, hdfsConf);
if (operation == StartupOption.RECOVER) {
return;
}
// After the NN has started, set back the bound ports into
// the conf
hdfsConf.set(DFSUtil.addKeySuffixes(DFS_NAMENODE_RPC_ADDRESS_KEY,
nameserviceId, nnId), nn.getNameNodeAddressHostPortString());
if (nn.getHttpAddress() != null) {
hdfsConf.set(DFSUtil.addKeySuffixes(DFS_NAMENODE_HTTP_ADDRESS_KEY,
nameserviceId, nnId), NetUtils.getHostPortString(nn.getHttpAddress()));
}
if (nn.getHttpsAddress() != null) {
hdfsConf.set(DFSUtil.addKeySuffixes(DFS_NAMENODE_HTTPS_ADDRESS_KEY,
nameserviceId, nnId), NetUtils.getHostPortString(nn.getHttpsAddress()));
}
copyKeys(hdfsConf, conf, nameserviceId, nnId);
DFSUtil.setGenericConf(hdfsConf, nameserviceId, nnId,
DFS_NAMENODE_HTTP_ADDRESS_KEY);
nameNodes[nnIndex] = new NameNodeInfo(nn, nameserviceId, nnId,
operation, hdfsConf);
}
/**
* @return URI of the namenode from a single namenode MiniDFSCluster
*/
public URI getURI() {
checkSingleNameNode();
return getURI(0);
}
/**
* @return URI of the given namenode in MiniDFSCluster
*/
public URI getURI(int nnIndex) {
String hostPort =
nameNodes[nnIndex].nameNode.getNameNodeAddressHostPortString();
URI uri = null;
try {
uri = new URI("hdfs://" + hostPort);
} catch (URISyntaxException e) {
NameNode.LOG.warn("unexpected URISyntaxException: " + e );
}
return uri;
}
public int getInstanceId() {
return instanceId;
}
/**
* @return Configuration of for the given namenode
*/
public Configuration getConfiguration(int nnIndex) {
return nameNodes[nnIndex].conf;
}
/**
* wait for the given namenode to get out of safemode.
*/
public void waitNameNodeUp(int nnIndex) {
while (!isNameNodeUp(nnIndex)) {
try {
LOG.warn("Waiting for namenode at " + nnIndex + " to start...");
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
/**
* wait for the cluster to get out of safemode.
*/
public void waitClusterUp() throws IOException {
int i = 0;
if (numDataNodes > 0) {
while (!isClusterUp()) {
try {
LOG.warn("Waiting for the Mini HDFS Cluster to start...");
Thread.sleep(1000);
} catch (InterruptedException e) {
}
if (++i > 10) {
final String msg = "Timed out waiting for Mini HDFS Cluster to start";
LOG.error(msg);
throw new IOException(msg);
}
}
}
}
String makeDataNodeDirs(int dnIndex, StorageType[] storageTypes) throws IOException {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < storagesPerDatanode; ++j) {
if ((storageTypes != null) && (j >= storageTypes.length)) {
break;
}
File dir = getInstanceStorageDir(dnIndex, j);
dir.mkdirs();
if (!dir.isDirectory()) {
throw new IOException("Mkdirs failed to create directory for DataNode " + dir);
}
sb.append((j > 0 ? "," : "") + "[" +
(storageTypes == null ? StorageType.DEFAULT : storageTypes[j]) +
"]" + fileAsURI(dir));
}
return sb.toString();
}
/**
* Modify the config and start up additional DataNodes. The info port for
* DataNodes is guaranteed to use a free port.
*
* Data nodes can run with the name node in the mini cluster or
* a real name node. For example, running with a real name node is useful
* when running simulated data nodes with a real name node.
* If minicluster's name node is null assume that the conf has been
* set with the right address:port of the name node.
*
* @param conf the base configuration to use in starting the DataNodes. This
* will be modified as necessary.
* @param numDataNodes Number of DataNodes to start; may be zero
* @param manageDfsDirs if true, the data directories for DataNodes will be
* created and {@link DFSConfigKeys#DFS_DATANODE_DATA_DIR_KEY} will be set
* in the conf
* @param operation the operation with which to start the DataNodes. If null
* or StartupOption.FORMAT, then StartupOption.REGULAR will be used.
* @param racks array of strings indicating the rack that each DataNode is on
* @param hosts array of strings indicating the hostnames for each DataNode
* @param simulatedCapacities array of capacities of the simulated data nodes
*
* @throws IllegalStateException if NameNode has been shutdown
*/
public synchronized void startDataNodes(Configuration conf, int numDataNodes,
boolean manageDfsDirs, StartupOption operation,
String[] racks, String[] hosts,
long[] simulatedCapacities) throws IOException {
startDataNodes(conf, numDataNodes, manageDfsDirs, operation, racks,
hosts, simulatedCapacities, false);
}
/**
* Modify the config and start up additional DataNodes. The info port for
* DataNodes is guaranteed to use a free port.
*
* Data nodes can run with the name node in the mini cluster or
* a real name node. For example, running with a real name node is useful
* when running simulated data nodes with a real name node.
* If minicluster's name node is null assume that the conf has been
* set with the right address:port of the name node.
*
* @param conf the base configuration to use in starting the DataNodes. This
* will be modified as necessary.
* @param numDataNodes Number of DataNodes to start; may be zero
* @param manageDfsDirs if true, the data directories for DataNodes will be
* created and {@link DFSConfigKeys#DFS_DATANODE_DATA_DIR_KEY} will be
* set in the conf
* @param operation the operation with which to start the DataNodes. If null
* or StartupOption.FORMAT, then StartupOption.REGULAR will be used.
* @param racks array of strings indicating the rack that each DataNode is on
* @param hosts array of strings indicating the hostnames for each DataNode
* @param simulatedCapacities array of capacities of the simulated data nodes
* @param setupHostsFile add new nodes to dfs hosts files
*
* @throws IllegalStateException if NameNode has been shutdown
*/
public synchronized void startDataNodes(Configuration conf, int numDataNodes,
boolean manageDfsDirs, StartupOption operation,
String[] racks, String[] hosts,
long[] simulatedCapacities,
boolean setupHostsFile) throws IOException {
startDataNodes(conf, numDataNodes, null, manageDfsDirs, operation, racks, hosts,
null, simulatedCapacities, setupHostsFile, false, false, null);
}
public synchronized void startDataNodes(Configuration conf, int numDataNodes,
boolean manageDfsDirs, StartupOption operation,
String[] racks, String[] hosts,
long[] simulatedCapacities,
boolean setupHostsFile,
boolean checkDataNodeAddrConfig) throws IOException {
startDataNodes(conf, numDataNodes, null, manageDfsDirs, operation, racks, hosts,
null, simulatedCapacities, setupHostsFile, checkDataNodeAddrConfig, false, null);
}
/**
* Modify the config and start up additional DataNodes. The info port for
* DataNodes is guaranteed to use a free port.
*
* Data nodes can run with the name node in the mini cluster or
* a real name node. For example, running with a real name node is useful
* when running simulated data nodes with a real name node.
* If minicluster's name node is null assume that the conf has been
* set with the right address:port of the name node.
*
* @param conf the base configuration to use in starting the DataNodes. This
* will be modified as necessary.
* @param numDataNodes Number of DataNodes to start; may be zero
* @param manageDfsDirs if true, the data directories for DataNodes will be
* created and {@link DFSConfigKeys#DFS_DATANODE_DATA_DIR_KEY} will be
* set in the conf
* @param operation the operation with which to start the DataNodes. If null
* or StartupOption.FORMAT, then StartupOption.REGULAR will be used.
* @param racks array of strings indicating the rack that each DataNode is on
* @param hosts array of strings indicating the hostnames for each DataNode
* @param simulatedCapacities array of capacities of the simulated data nodes
* @param setupHostsFile add new nodes to dfs hosts files
* @param checkDataNodeAddrConfig if true, only set DataNode port addresses if not already set in config
* @param checkDataNodeHostConfig if true, only set DataNode hostname key if not already set in config
* @param dnConfOverlays An array of {@link Configuration} objects that will overlay the
* global MiniDFSCluster Configuration for the corresponding DataNode.
* @throws IllegalStateException if NameNode has been shutdown
*/
public synchronized void startDataNodes(Configuration conf, int numDataNodes,
StorageType[][] storageTypes, boolean manageDfsDirs, StartupOption operation,
String[] racks, String[] hosts,
long[][] storageCapacities,
long[] simulatedCapacities,
boolean setupHostsFile,
boolean checkDataNodeAddrConfig,
boolean checkDataNodeHostConfig,
Configuration[] dnConfOverlays) throws IOException {
assert storageCapacities == null || simulatedCapacities == null;
assert storageTypes == null || storageTypes.length == numDataNodes;
assert storageCapacities == null || storageCapacities.length == numDataNodes;
if (operation == StartupOption.RECOVER) {
return;
}
if (checkDataNodeHostConfig) {
conf.setIfUnset(DFS_DATANODE_HOST_NAME_KEY, "127.0.0.1");
} else {
conf.set(DFS_DATANODE_HOST_NAME_KEY, "127.0.0.1");
}
int curDatanodesNum = dataNodes.size();
final int curDatanodesNumSaved = curDatanodesNum;
// for mincluster's the default initialDelay for BRs is 0
if (conf.get(DFS_BLOCKREPORT_INITIAL_DELAY_KEY) == null) {
conf.setLong(DFS_BLOCKREPORT_INITIAL_DELAY_KEY, 0);
}
// If minicluster's name node is null assume that the conf has been
// set with the right address:port of the name node.
//
if (racks != null && numDataNodes > racks.length ) {
throw new IllegalArgumentException( "The length of racks [" + racks.length
+ "] is less than the number of datanodes [" + numDataNodes + "].");
}
if (hosts != null && numDataNodes > hosts.length ) {
throw new IllegalArgumentException( "The length of hosts [" + hosts.length
+ "] is less than the number of datanodes [" + numDataNodes + "].");
}
//Generate some hostnames if required
if (racks != null && hosts == null) {
hosts = new String[numDataNodes];
for (int i = curDatanodesNum; i < curDatanodesNum + numDataNodes; i++) {
hosts[i - curDatanodesNum] = "host" + i + ".foo.com";
}
}
if (simulatedCapacities != null
&& numDataNodes > simulatedCapacities.length) {
throw new IllegalArgumentException( "The length of simulatedCapacities ["
+ simulatedCapacities.length
+ "] is less than the number of datanodes [" + numDataNodes + "].");
}
if (dnConfOverlays != null
&& numDataNodes > dnConfOverlays.length) {
throw new IllegalArgumentException( "The length of dnConfOverlays ["
+ dnConfOverlays.length
+ "] is less than the number of datanodes [" + numDataNodes + "].");
}
String [] dnArgs = (operation == null ||
operation != StartupOption.ROLLBACK) ?
null : new String[] {operation.getName()};
DataNode[] dns = new DataNode[numDataNodes];
for (int i = curDatanodesNum; i < curDatanodesNum+numDataNodes; i++) {
Configuration dnConf = new HdfsConfiguration(conf);
if (dnConfOverlays != null) {
dnConf.addResource(dnConfOverlays[i]);
}
// Set up datanode address
setupDatanodeAddress(dnConf, setupHostsFile, checkDataNodeAddrConfig);
if (manageDfsDirs) {
String dirs = makeDataNodeDirs(i, storageTypes == null ?
null : storageTypes[i - curDatanodesNum]);
dnConf.set(DFS_DATANODE_DATA_DIR_KEY, dirs);
conf.set(DFS_DATANODE_DATA_DIR_KEY, dirs);
}
if (simulatedCapacities != null) {
SimulatedFSDataset.setFactory(dnConf);
dnConf.setLong(SimulatedFSDataset.CONFIG_PROPERTY_CAPACITY,
simulatedCapacities[i-curDatanodesNum]);
}
LOG.info("Starting DataNode " + i + " with "
+ DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY + ": "
+ dnConf.get(DFSConfigKeys.DFS_DATANODE_DATA_DIR_KEY));
if (hosts != null) {
dnConf.set(DFSConfigKeys.DFS_DATANODE_HOST_NAME_KEY, hosts[i - curDatanodesNum]);
LOG.info("Starting DataNode " + i + " with hostname set to: "
+ dnConf.get(DFSConfigKeys.DFS_DATANODE_HOST_NAME_KEY));
}
if (racks != null) {
String name = hosts[i - curDatanodesNum];
LOG.info("Adding node with hostname : " + name + " to rack " +
racks[i-curDatanodesNum]);
StaticMapping.addNodeToRack(name,
racks[i-curDatanodesNum]);
}
Configuration newconf = new HdfsConfiguration(dnConf); // save config
if (hosts != null) {
NetUtils.addStaticResolution(hosts[i - curDatanodesNum], "localhost");
}
SecureResources secureResources = null;
if (UserGroupInformation.isSecurityEnabled() &&
conf.get(DFS_DATA_TRANSFER_PROTECTION_KEY) == null) {
try {
secureResources = SecureDataNodeStarter.getSecureResources(dnConf);
} catch (Exception ex) {
ex.printStackTrace();
}
}
final int maxRetriesOnSasl = conf.getInt(
IPC_CLIENT_CONNECT_MAX_RETRIES_ON_SASL_KEY,
IPC_CLIENT_CONNECT_MAX_RETRIES_ON_SASL_DEFAULT);
int numRetries = 0;
DataNode dn = null;
while (true) {
try {
dn = DataNode.instantiateDataNode(dnArgs, dnConf,
secureResources);
break;
} catch (IOException e) {
// Work around issue testing security where rapidly starting multiple
// DataNodes using the same principal gets rejected by the KDC as a
// replay attack.
if (UserGroupInformation.isSecurityEnabled() &&
numRetries < maxRetriesOnSasl) {
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
break;
}
++numRetries;
continue;
}
throw e;
}
}
if(dn == null)
throw new IOException("Cannot start DataNode in "
+ dnConf.get(DFS_DATANODE_DATA_DIR_KEY));
//since the HDFS does things based on host|ip:port, we need to add the
//mapping for the service to rackId
String service =
SecurityUtil.buildTokenService(dn.getXferAddress()).toString();
if (racks != null) {
LOG.info("Adding node with service : " + service +
" to rack " + racks[i-curDatanodesNum]);
StaticMapping.addNodeToRack(service,
racks[i-curDatanodesNum]);
}
dn.runDatanodeDaemon();
dataNodes.add(new DataNodeProperties(dn, newconf, dnArgs,
secureResources, dn.getIpcPort()));
dns[i - curDatanodesNum] = dn;
}
this.numDataNodes += numDataNodes;
waitActive();
if (storageCapacities != null) {
for (int i = curDatanodesNumSaved; i < curDatanodesNumSaved+numDataNodes; ++i) {
final int index = i - curDatanodesNum;
try (FsDatasetSpi.FsVolumeReferences volumes =
dns[index].getFSDataset().getFsVolumeReferences()) {
assert storageCapacities[index].length == storagesPerDatanode;
assert volumes.size() == storagesPerDatanode;
int j = 0;
for (FsVolumeSpi fvs : volumes) {
FsVolumeImpl volume = (FsVolumeImpl) fvs;
LOG.info("setCapacityForTesting " + storageCapacities[index][j]
+ " for [" + volume.getStorageType() + "]" + volume
.getStorageID());
volume.setCapacityForTesting(storageCapacities[index][j]);
j++;
}
}
}
}
}
/**
* Modify the config and start up the DataNodes. The info port for
* DataNodes is guaranteed to use a free port.
*
* @param conf the base configuration to use in starting the DataNodes. This
* will be modified as necessary.
* @param numDataNodes Number of DataNodes to start; may be zero
* @param manageDfsDirs if true, the data directories for DataNodes will be
* created and {@link DFSConfigKeys#DFS_DATANODE_DATA_DIR_KEY} will be
* set in the conf
* @param operation the operation with which to start the DataNodes. If null
* or StartupOption.FORMAT, then StartupOption.REGULAR will be used.
* @param racks array of strings indicating the rack that each DataNode is on
*
* @throws IllegalStateException if NameNode has been shutdown
*/
public void startDataNodes(Configuration conf, int numDataNodes,
boolean manageDfsDirs, StartupOption operation,
String[] racks
) throws IOException {
startDataNodes(conf, numDataNodes, manageDfsDirs, operation, racks, null,
null, false);
}
/**
* Modify the config and start up additional DataNodes. The info port for
* DataNodes is guaranteed to use a free port.
*
* Data nodes can run with the name node in the mini cluster or
* a real name node. For example, running with a real name node is useful
* when running simulated data nodes with a real name node.
* If minicluster's name node is null assume that the conf has been
* set with the right address:port of the name node.
*
* @param conf the base configuration to use in starting the DataNodes. This
* will be modified as necessary.
* @param numDataNodes Number of DataNodes to start; may be zero
* @param manageDfsDirs if true, the data directories for DataNodes will be
* created and {@link DFSConfigKeys#DFS_DATANODE_DATA_DIR_KEY} will
* be set in the conf
* @param operation the operation with which to start the DataNodes. If null
* or StartupOption.FORMAT, then StartupOption.REGULAR will be used.
* @param racks array of strings indicating the rack that each DataNode is on
* @param simulatedCapacities array of capacities of the simulated data nodes
*
* @throws IllegalStateException if NameNode has been shutdown
*/
public void startDataNodes(Configuration conf, int numDataNodes,
boolean manageDfsDirs, StartupOption operation,
String[] racks,
long[] simulatedCapacities) throws IOException {
startDataNodes(conf, numDataNodes, manageDfsDirs, operation, racks, null,
simulatedCapacities, false);
}
/**
* Finalize the namenode. Block pools corresponding to the namenode are
* finalized on the datanode.
*/
private void finalizeNamenode(NameNode nn, Configuration conf) throws Exception {
if (nn == null) {
throw new IllegalStateException("Attempting to finalize "
+ "Namenode but it is not running");
}
ToolRunner.run(new DFSAdmin(conf), new String[]{"-finalizeUpgrade"});
}
/**
* Finalize cluster for the namenode at the given index
* @see MiniDFSCluster#finalizeCluster(Configuration)
* @param nnIndex index of the namenode
* @param conf configuration
* @throws Exception
*/
public void finalizeCluster(int nnIndex, Configuration conf) throws Exception {
finalizeNamenode(nameNodes[nnIndex].nameNode, nameNodes[nnIndex].conf);
}
/**
* If the NameNode is running, attempt to finalize a previous upgrade.
* When this method return, the NameNode should be finalized, but
* DataNodes may not be since that occurs asynchronously.
*
* @throws IllegalStateException if the Namenode is not running.
*/
public void finalizeCluster(Configuration conf) throws Exception {
for (NameNodeInfo nnInfo : nameNodes) {
if (nnInfo == null) {
throw new IllegalStateException("Attempting to finalize "
+ "Namenode but it is not running");
}
finalizeNamenode(nnInfo.nameNode, nnInfo.conf);
}
}
public int getNumNameNodes() {
return nameNodes.length;
}
/**
* Gets the started NameNode. May be null.
*/
public NameNode getNameNode() {
checkSingleNameNode();
return getNameNode(0);
}
/**
* Get an instance of the NameNode's RPC handler.
*/
public NamenodeProtocols getNameNodeRpc() {
checkSingleNameNode();
return getNameNodeRpc(0);
}
/**
* Get an instance of the NameNode's RPC handler.
*/
public NamenodeProtocols getNameNodeRpc(int nnIndex) {
return getNameNode(nnIndex).getRpcServer();
}
/**
* Gets the NameNode for the index. May be null.
*/
public NameNode getNameNode(int nnIndex) {
return nameNodes[nnIndex].nameNode;
}
/**
* Return the {@link FSNamesystem} object.
* @return {@link FSNamesystem} object.
*/
public FSNamesystem getNamesystem() {
checkSingleNameNode();
return NameNodeAdapter.getNamesystem(nameNodes[0].nameNode);
}
public FSNamesystem getNamesystem(int nnIndex) {
return NameNodeAdapter.getNamesystem(nameNodes[nnIndex].nameNode);
}
/**
* Gets a list of the started DataNodes. May be empty.
*/
public ArrayList<DataNode> getDataNodes() {
ArrayList<DataNode> list = new ArrayList<DataNode>();
for (int i = 0; i < dataNodes.size(); i++) {
DataNode node = dataNodes.get(i).datanode;
list.add(node);
}
return list;
}
/** @return the datanode having the ipc server listen port */
public DataNode getDataNode(int ipcPort) {
for(DataNode dn : getDataNodes()) {
if (dn.ipcServer.getListenerAddress().getPort() == ipcPort) {
return dn;
}
}
return null;
}
/**
* Returns the corresponding FsDatasetTestUtils for a DataNode.
* @param dnIdx the index of DataNode.
* @return a FsDatasetTestUtils for the given DataNode.
*/
public FsDatasetTestUtils getFsDatasetTestUtils(int dnIdx) {
Preconditions.checkArgument(dnIdx < dataNodes.size());
return FsDatasetTestUtils.Factory.getFactory(conf)
.newInstance(dataNodes.get(dnIdx).datanode);
}
/**
* Returns the corresponding FsDatasetTestUtils for a DataNode.
* @param dn a DataNode
* @return a FsDatasetTestUtils for the given DataNode.
*/
public FsDatasetTestUtils getFsDatasetTestUtils(DataNode dn) {
Preconditions.checkArgument(dn != null);
return FsDatasetTestUtils.Factory.getFactory(conf)
.newInstance(dn);
}
/**
* Gets the rpc port used by the NameNode, because the caller
* supplied port is not necessarily the actual port used.
* Assumption: cluster has a single namenode
*/
public int getNameNodePort() {
checkSingleNameNode();
return getNameNodePort(0);
}
/**
* Gets the rpc port used by the NameNode at the given index, because the
* caller supplied port is not necessarily the actual port used.
*/
public int getNameNodePort(int nnIndex) {
return nameNodes[nnIndex].nameNode.getNameNodeAddress().getPort();
}
/**
* @return the service rpc port used by the NameNode at the given index.
*/
public int getNameNodeServicePort(int nnIndex) {
return nameNodes[nnIndex].nameNode.getServiceRpcAddress().getPort();
}
/**
* Shutdown all the nodes in the cluster.
*/
public void shutdown() {
shutdown(false);
}
/**
* Shutdown all the nodes in the cluster.
*/
public void shutdown(boolean deleteDfsDir) {
shutdown(deleteDfsDir, true);
}
/**
* Shutdown all the nodes in the cluster.
*/
public void shutdown(boolean deleteDfsDir, boolean closeFileSystem) {
LOG.info("Shutting down the Mini HDFS Cluster");
if (checkExitOnShutdown) {
if (ExitUtil.terminateCalled()) {
LOG.fatal("Test resulted in an unexpected exit",
ExitUtil.getFirstExitException());
ExitUtil.resetFirstExitException();
throw new AssertionError("Test resulted in an unexpected exit");
}
}
if (closeFileSystem) {
for (FileSystem fs : fileSystems) {
try {
fs.close();
} catch (IOException ioe) {
LOG.warn("Exception while closing file system", ioe);
}
}
fileSystems.clear();
}
shutdownDataNodes();
for (NameNodeInfo nnInfo : nameNodes) {
if (nnInfo == null) continue;
stopAndJoinNameNode(nnInfo.nameNode);
}
ShutdownHookManager.get().clearShutdownHooks();
if (base_dir != null) {
if (deleteDfsDir) {
base_dir.delete();
} else {
base_dir.deleteOnExit();
}
}
}
/**
* Shutdown all DataNodes started by this class. The NameNode
* is left running so that new DataNodes may be started.
*/
public void shutdownDataNodes() {
for (int i = dataNodes.size()-1; i >= 0; i--) {
LOG.info("Shutting down DataNode " + i);
DataNode dn = dataNodes.remove(i).datanode;
dn.shutdown();
numDataNodes--;
}
}
/**
* Shutdown all the namenodes.
*/
public synchronized void shutdownNameNodes() {
for (int i = 0; i < nameNodes.length; i++) {
shutdownNameNode(i);
}
}
/**
* Shutdown the namenode at a given index.
*/
public synchronized void shutdownNameNode(int nnIndex) {
NameNode nn = nameNodes[nnIndex].nameNode;
if (nn != null) {
stopAndJoinNameNode(nn);
Configuration conf = nameNodes[nnIndex].conf;
nameNodes[nnIndex] = new NameNodeInfo(null, null, null, null, conf);
}
}
/**
* Fully stop the NameNode by stop and join.
*/
private void stopAndJoinNameNode(NameNode nn) {
if (nn == null) {
return;
}
LOG.info("Shutting down the namenode");
nn.stop();
nn.join();
nn.joinHttpServer();
}
/**
* Restart all namenodes.
*/
public synchronized void restartNameNodes() throws IOException {
for (int i = 0; i < nameNodes.length; i++) {
restartNameNode(i, false);
}
waitActive();
}
/**
* Restart the namenode.
*/
public synchronized void restartNameNode(String... args) throws IOException {
checkSingleNameNode();
restartNameNode(0, true, args);
}
/**
* Restart the namenode. Optionally wait for the cluster to become active.
*/
public synchronized void restartNameNode(boolean waitActive)
throws IOException {
checkSingleNameNode();
restartNameNode(0, waitActive);
}
/**
* Restart the namenode at a given index.
*/
public synchronized void restartNameNode(int nnIndex) throws IOException {
restartNameNode(nnIndex, true);
}
/**
* Restart the namenode at a given index. Optionally wait for the cluster
* to become active.
*/
public synchronized void restartNameNode(int nnIndex, boolean waitActive,
String... args) throws IOException {
String nameserviceId = nameNodes[nnIndex].nameserviceId;
String nnId = nameNodes[nnIndex].nnId;
StartupOption startOpt = nameNodes[nnIndex].startOpt;
Configuration conf = nameNodes[nnIndex].conf;
shutdownNameNode(nnIndex);
if (args.length != 0) {
startOpt = null;
} else {
args = createArgs(startOpt);
}
NameNode nn = NameNode.createNameNode(args, conf);
nameNodes[nnIndex] = new NameNodeInfo(nn, nameserviceId, nnId, startOpt,
conf);
if (waitActive) {
waitClusterUp();
LOG.info("Restarted the namenode");
waitActive();
}
}
private int corruptBlockOnDataNodesHelper(ExtendedBlock block,
boolean deleteBlockFile) throws IOException {
int blocksCorrupted = 0;
for (DataNode dn : getDataNodes()) {
try {
MaterializedReplica replica =
getFsDatasetTestUtils(dn).getMaterializedReplica(block);
if (deleteBlockFile) {
replica.deleteData();
} else {
replica.corruptData();
}
blocksCorrupted++;
} catch (ReplicaNotFoundException e) {
// Ignore.
}
}
return blocksCorrupted;
}
/**
* Return the number of corrupted replicas of the given block.
*
* @param block block to be corrupted
* @throws IOException on error accessing the file for the given block
*/
public int corruptBlockOnDataNodes(ExtendedBlock block) throws IOException{
return corruptBlockOnDataNodesHelper(block, false);
}
/**
* Return the number of corrupted replicas of the given block.
*
* @param block block to be corrupted
* @throws IOException on error accessing the file for the given block
*/
public int corruptBlockOnDataNodesByDeletingBlockFile(ExtendedBlock block)
throws IOException{
return corruptBlockOnDataNodesHelper(block, true);
}
public String readBlockOnDataNode(int i, ExtendedBlock block)
throws IOException {
assert (i >= 0 && i < dataNodes.size()) : "Invalid datanode "+i;
File blockFile = getBlockFile(i, block);
if (blockFile != null && blockFile.exists()) {
return DFSTestUtil.readFile(blockFile);
}
return null;
}
/**
* Corrupt a block on a particular datanode.
*
* @param i index of the datanode
* @param blk name of the block
* @throws IOException on error accessing the given block file.
*/
public void corruptReplica(int i, ExtendedBlock blk)
throws IOException {
getMaterializedReplica(i, blk).corruptData();
}
/**
* Corrupt a block on a particular datanode.
*
* @param dn the datanode
* @param blk name of the block
* @throws IOException on error accessing the given block file.
*/
public void corruptReplica(DataNode dn, ExtendedBlock blk)
throws IOException {
getMaterializedReplica(dn, blk).corruptData();
}
/**
* Corrupt the metadata of a block on a datanode.
* @param i the index of the datanode
* @param blk name of the block
* @throws IOException on error accessing the given metadata file.
*/
public void corruptMeta(int i, ExtendedBlock blk) throws IOException {
getMaterializedReplica(i, blk).corruptMeta();
}
/**
* Corrupt the metadata of a block by deleting it.
* @param i index of the datanode
* @param blk name of the block.
*/
public void deleteMeta(int i, ExtendedBlock blk)
throws IOException {
getMaterializedReplica(i, blk).deleteMeta();
}
/**
* Corrupt the metadata of a block by truncating it to a new size.
* @param i index of the datanode.
* @param blk name of the block.
* @param newSize the new size of the metadata file.
* @throws IOException if any I/O errors.
*/
public void truncateMeta(int i, ExtendedBlock blk, int newSize)
throws IOException {
getMaterializedReplica(i, blk).truncateMeta(newSize);
}
public void changeGenStampOfBlock(int dnIndex, ExtendedBlock blk,
long newGenStamp) throws IOException {
getFsDatasetTestUtils(dnIndex)
.changeStoredGenerationStamp(blk, newGenStamp);
}
/*
* Shutdown a particular datanode
* @param i node index
* @return null if the node index is out of range, else the properties of the
* removed node
*/
public synchronized DataNodeProperties stopDataNode(int i) {
if (i < 0 || i >= dataNodes.size()) {
return null;
}
DataNodeProperties dnprop = dataNodes.remove(i);
DataNode dn = dnprop.datanode;
LOG.info("MiniDFSCluster Stopping DataNode " +
dn.getDisplayName() +
" from a total of " + (dataNodes.size() + 1) +
" datanodes.");
dn.shutdown();
numDataNodes--;
return dnprop;
}
/*
* Shutdown a datanode by name.
* @return the removed datanode or null if there was no match
*/
public synchronized DataNodeProperties stopDataNode(String dnName) {
int node = -1;
for (int i = 0; i < dataNodes.size(); i++) {
DataNode dn = dataNodes.get(i).datanode;
LOG.info("DN name=" + dnName + " found DN=" + dn +
" with name=" + dn.getDisplayName());
if (dnName.equals(dn.getDatanodeId().getXferAddr())) {
node = i;
break;
}
}
return stopDataNode(node);
}
/*
* Shutdown a particular datanode
* @param i node index
* @return null if the node index is out of range, else the properties of the
* removed node
*/
public synchronized DataNodeProperties stopDataNodeForUpgrade(int i)
throws IOException {
if (i < 0 || i >= dataNodes.size()) {
return null;
}
DataNodeProperties dnprop = dataNodes.remove(i);
DataNode dn = dnprop.datanode;
LOG.info("MiniDFSCluster Stopping DataNode " +
dn.getDisplayName() +
" from a total of " + (dataNodes.size() + 1) +
" datanodes.");
dn.shutdownDatanode(true);
numDataNodes--;
return dnprop;
}
/**
* Restart a datanode
* @param dnprop datanode's property
* @return true if restarting is successful
* @throws IOException
*/
public boolean restartDataNode(DataNodeProperties dnprop) throws IOException {
return restartDataNode(dnprop, false);
}
/**
* Restart a datanode, on the same port if requested
* @param dnprop the datanode to restart
* @param keepPort whether to use the same port
* @return true if restarting is successful
* @throws IOException
*/
public synchronized boolean restartDataNode(DataNodeProperties dnprop,
boolean keepPort) throws IOException {
Configuration conf = dnprop.conf;
String[] args = dnprop.dnArgs;
SecureResources secureResources = dnprop.secureResources;
Configuration newconf = new HdfsConfiguration(conf); // save cloned config
if (keepPort) {
InetSocketAddress addr = dnprop.datanode.getXferAddress();
conf.set(DFS_DATANODE_ADDRESS_KEY,
addr.getAddress().getHostAddress() + ":" + addr.getPort());
conf.set(DFS_DATANODE_IPC_ADDRESS_KEY,
addr.getAddress().getHostAddress() + ":" + dnprop.ipcPort);
}
DataNode newDn = DataNode.createDataNode(args, conf, secureResources);
dataNodes.add(new DataNodeProperties(
newDn, newconf, args, secureResources, newDn.getIpcPort()));
numDataNodes++;
return true;
}
/*
* Restart a particular datanode, use newly assigned port
*/
public boolean restartDataNode(int i) throws IOException {
return restartDataNode(i, false);
}
/*
* Restart a particular datanode, on the same port if keepPort is true
*/
public synchronized boolean restartDataNode(int i, boolean keepPort)
throws IOException {
return restartDataNode(i, keepPort, false);
}
/**
* Restart a particular DataNode.
* @param idn index of the DataNode
* @param keepPort true if should restart on the same port
* @param expireOnNN true if NameNode should expire the DataNode heartbeat
* @return
* @throws IOException
*/
public synchronized boolean restartDataNode(
int idn, boolean keepPort, boolean expireOnNN) throws IOException {
DataNodeProperties dnprop = stopDataNode(idn);
if(expireOnNN) {
setDataNodeDead(dnprop.datanode.getDatanodeId());
}
if (dnprop == null) {
return false;
} else {
return restartDataNode(dnprop, keepPort);
}
}
/**
* Expire a DataNode heartbeat on the NameNode
* @param dnId
* @throws IOException
*/
public void setDataNodeDead(DatanodeID dnId) throws IOException {
DatanodeDescriptor dnd =
NameNodeAdapter.getDatanode(getNamesystem(), dnId);
DFSTestUtil.setDatanodeDead(dnd);
BlockManagerTestUtil.checkHeartbeat(getNamesystem().getBlockManager());
}
public void setDataNodesDead() throws IOException {
for (DataNodeProperties dnp : dataNodes) {
setDataNodeDead(dnp.datanode.getDatanodeId());
}
}
/*
* Restart all datanodes, on the same ports if keepPort is true
*/
public synchronized boolean restartDataNodes(boolean keepPort)
throws IOException {
for (int i = dataNodes.size() - 1; i >= 0; i--) {
if (!restartDataNode(i, keepPort))
return false;
LOG.info("Restarted DataNode " + i);
}
return true;
}
/*
* Restart all datanodes, use newly assigned ports
*/
public boolean restartDataNodes() throws IOException {
return restartDataNodes(false);
}
/**
* Returns true if the NameNode is running and is out of Safe Mode
* or if waiting for safe mode is disabled.
*/
public boolean isNameNodeUp(int nnIndex) {
NameNode nameNode = nameNodes[nnIndex].nameNode;
if (nameNode == null) {
return false;
}
long[] sizes;
sizes = NameNodeAdapter.getStats(nameNode.getNamesystem());
boolean isUp = false;
synchronized (this) {
isUp = ((!nameNode.isInSafeMode() || !waitSafeMode) &&
sizes[ClientProtocol.GET_STATS_CAPACITY_IDX] != 0);
}
return isUp;
}
/**
* Returns true if all the NameNodes are running and is out of Safe Mode.
*/
public boolean isClusterUp() {
for (int index = 0; index < nameNodes.length; index++) {
if (!isNameNodeUp(index)) {
return false;
}
}
return true;
}
/**
* Returns true if there is at least one DataNode running.
*/
public boolean isDataNodeUp() {
if (dataNodes == null || dataNodes.size() == 0) {
return false;
}
for (DataNodeProperties dn : dataNodes) {
if (dn.datanode.isDatanodeUp()) {
return true;
}
}
return false;
}
/**
* Get a client handle to the DFS cluster with a single namenode.
*/
public DistributedFileSystem getFileSystem() throws IOException {
checkSingleNameNode();
return getFileSystem(0);
}
/**
* Get a client handle to the DFS cluster for the namenode at given index.
*/
public DistributedFileSystem getFileSystem(int nnIndex) throws IOException {
DistributedFileSystem dfs = (DistributedFileSystem) FileSystem.get(
getURI(nnIndex), nameNodes[nnIndex].conf);
fileSystems.add(dfs);
return dfs;
}
/**
* Get another FileSystem instance that is different from FileSystem.get(conf).
* This simulating different threads working on different FileSystem instances.
*/
public FileSystem getNewFileSystemInstance(int nnIndex) throws IOException {
FileSystem dfs = FileSystem.newInstance(getURI(nnIndex), nameNodes[nnIndex].conf);
fileSystems.add(dfs);
return dfs;
}
/**
* @return a http URL
*/
public String getHttpUri(int nnIndex) {
return "http://"
+ nameNodes[nnIndex].conf
.get(DFS_NAMENODE_HTTP_ADDRESS_KEY);
}
/**
* @return a {@link HftpFileSystem} object.
*/
public HftpFileSystem getHftpFileSystem(int nnIndex) throws IOException {
String uri = "hftp://"
+ nameNodes[nnIndex].conf
.get(DFS_NAMENODE_HTTP_ADDRESS_KEY);
try {
return (HftpFileSystem)FileSystem.get(new URI(uri), conf);
} catch (URISyntaxException e) {
throw new IOException(e);
}
}
/**
* @return a {@link HftpFileSystem} object as specified user.
*/
public HftpFileSystem getHftpFileSystemAs(final String username,
final Configuration conf, final int nnIndex, final String... groups)
throws IOException, InterruptedException {
final UserGroupInformation ugi = UserGroupInformation.createUserForTesting(
username, groups);
return ugi.doAs(new PrivilegedExceptionAction<HftpFileSystem>() {
@Override
public HftpFileSystem run() throws Exception {
return getHftpFileSystem(nnIndex);
}
});
}
/**
* Get the directories where the namenode stores its image.
*/
public Collection<URI> getNameDirs(int nnIndex) {
return FSNamesystem.getNamespaceDirs(nameNodes[nnIndex].conf);
}
/**
* Get the directories where the namenode stores its edits.
*/
public Collection<URI> getNameEditsDirs(int nnIndex) throws IOException {
return FSNamesystem.getNamespaceEditsDirs(nameNodes[nnIndex].conf);
}
public void transitionToActive(int nnIndex) throws IOException,
ServiceFailedException {
getNameNode(nnIndex).getRpcServer().transitionToActive(
new StateChangeRequestInfo(RequestSource.REQUEST_BY_USER_FORCED));
}
public void transitionToStandby(int nnIndex) throws IOException,
ServiceFailedException {
getNameNode(nnIndex).getRpcServer().transitionToStandby(
new StateChangeRequestInfo(RequestSource.REQUEST_BY_USER_FORCED));
}
public void triggerBlockReports()
throws IOException {
for (DataNode dn : getDataNodes()) {
DataNodeTestUtils.triggerBlockReport(dn);
}
}
public void triggerDeletionReports()
throws IOException {
for (DataNode dn : getDataNodes()) {
DataNodeTestUtils.triggerDeletionReport(dn);
}
}
public void triggerHeartbeats()
throws IOException {
for (DataNode dn : getDataNodes()) {
DataNodeTestUtils.triggerHeartbeat(dn);
}
}
/** Wait until the given namenode gets registration from all the datanodes */
public void waitActive(int nnIndex) throws IOException {
if (nameNodes.length == 0 || nameNodes[nnIndex] == null
|| nameNodes[nnIndex].nameNode == null) {
return;
}
InetSocketAddress addr = nameNodes[nnIndex].nameNode.getServiceRpcAddress();
assert addr.getPort() != 0;
DFSClient client = new DFSClient(addr, conf);
// ensure all datanodes have registered and sent heartbeat to the namenode
while (shouldWait(client.datanodeReport(DatanodeReportType.LIVE), addr)) {
try {
LOG.info("Waiting for cluster to become active");
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
client.close();
}
/** Wait until the given namenode gets first block reports from all the datanodes */
public void waitFirstBRCompleted(int nnIndex, int timeout) throws
IOException, TimeoutException, InterruptedException {
if (nameNodes.length == 0 || nameNodes[nnIndex] == null
|| nameNodes[nnIndex].nameNode == null) {
return;
}
final FSNamesystem ns = getNamesystem(nnIndex);
final DatanodeManager dm = ns.getBlockManager().getDatanodeManager();
GenericTestUtils.waitFor(new Supplier<Boolean>() {
@Override
public Boolean get() {
List<DatanodeDescriptor> nodes = dm.getDatanodeListForReport
(DatanodeReportType.LIVE);
for (DatanodeDescriptor node : nodes) {
if (!node.checkBlockReportReceived()) {
return false;
}
}
return true;
}
}, 100, timeout);
}
/**
* Wait until the cluster is active and running.
*/
public void waitActive() throws IOException {
for (int index = 0; index < nameNodes.length; index++) {
int failedCount = 0;
while (true) {
try {
waitActive(index);
break;
} catch (IOException e) {
failedCount++;
// Cached RPC connection to namenode, if any, is expected to fail once
if (failedCount > 1) {
LOG.warn("Tried waitActive() " + failedCount
+ " time(s) and failed, giving up. "
+ StringUtils.stringifyException(e));
throw e;
}
}
}
}
LOG.info("Cluster is active");
}
private synchronized boolean shouldWait(DatanodeInfo[] dnInfo,
InetSocketAddress addr) {
// If a datanode failed to start, then do not wait
for (DataNodeProperties dn : dataNodes) {
// the datanode thread communicating with the namenode should be alive
if (!dn.datanode.isConnectedToNN(addr)) {
LOG.warn("BPOfferService in datanode " + dn.datanode
+ " failed to connect to namenode at " + addr);
return false;
}
}
// Wait for expected number of datanodes to start
if (dnInfo.length != numDataNodes) {
LOG.info("dnInfo.length != numDataNodes");
return true;
}
// if one of the data nodes is not fully started, continue to wait
for (DataNodeProperties dn : dataNodes) {
if (!dn.datanode.isDatanodeFullyStarted()) {
LOG.info("!dn.datanode.isDatanodeFullyStarted()");
return true;
}
}
// make sure all datanodes have sent first heartbeat to namenode,
// using (capacity == 0) as proxy.
for (DatanodeInfo dn : dnInfo) {
if (dn.getCapacity() == 0 || dn.getLastUpdate() <= 0) {
LOG.info("No heartbeat from DataNode: " + dn.toString());
return true;
}
}
// If datanode dataset is not initialized then wait
for (DataNodeProperties dn : dataNodes) {
if (DataNodeTestUtils.getFSDataset(dn.datanode) == null) {
LOG.info("DataNodeTestUtils.getFSDataset(dn.datanode) == null");
return true;
}
}
return false;
}
public void formatDataNodeDirs() throws IOException {
base_dir = new File(determineDfsBaseDir());
data_dir = new File(base_dir, "data");
if (data_dir.exists() && !FileUtil.fullyDelete(data_dir)) {
throw new IOException("Cannot remove data directory: " + data_dir);
}
}
/**
*
* @param dataNodeIndex - data node whose block report is desired - the index is same as for getDataNodes()
* @return the block report for the specified data node
*/
public Map<DatanodeStorage, BlockListAsLongs> getBlockReport(String bpid, int dataNodeIndex) {
if (dataNodeIndex < 0 || dataNodeIndex > dataNodes.size()) {
throw new IndexOutOfBoundsException();
}
final DataNode dn = dataNodes.get(dataNodeIndex).datanode;
return DataNodeTestUtils.getFSDataset(dn).getBlockReports(bpid);
}
/**
*
* @return block reports from all data nodes
* BlockListAsLongs is indexed in the same order as the list of datanodes returned by getDataNodes()
*/
public List<Map<DatanodeStorage, BlockListAsLongs>> getAllBlockReports(String bpid) {
int numDataNodes = dataNodes.size();
final List<Map<DatanodeStorage, BlockListAsLongs>> result
= new ArrayList<Map<DatanodeStorage, BlockListAsLongs>>(numDataNodes);
for (int i = 0; i < numDataNodes; ++i) {
result.add(getBlockReport(bpid, i));
}
return result;
}
/**
* This method is valid only if the data nodes have simulated data
* @param dataNodeIndex - data node i which to inject - the index is same as for getDataNodes()
* @param blocksToInject - the blocks
* @param bpid - (optional) the block pool id to use for injecting blocks.
* If not supplied then it is queried from the in-process NameNode.
* @throws IOException
* if not simulatedFSDataset
* if any of blocks already exist in the data node
*
*/
public void injectBlocks(int dataNodeIndex,
Iterable<Block> blocksToInject, String bpid) throws IOException {
if (dataNodeIndex < 0 || dataNodeIndex > dataNodes.size()) {
throw new IndexOutOfBoundsException();
}
final DataNode dn = dataNodes.get(dataNodeIndex).datanode;
final FsDatasetSpi<?> dataSet = DataNodeTestUtils.getFSDataset(dn);
if (!(dataSet instanceof SimulatedFSDataset)) {
throw new IOException("injectBlocks is valid only for SimilatedFSDataset");
}
if (bpid == null) {
bpid = getNamesystem().getBlockPoolId();
}
SimulatedFSDataset sdataset = (SimulatedFSDataset) dataSet;
sdataset.injectBlocks(bpid, blocksToInject);
dataNodes.get(dataNodeIndex).datanode.scheduleAllBlockReport(0);
}
/**
* Multiple-NameNode version of injectBlocks.
*/
public void injectBlocks(int nameNodeIndex, int dataNodeIndex,
Iterable<Block> blocksToInject) throws IOException {
if (dataNodeIndex < 0 || dataNodeIndex > dataNodes.size()) {
throw new IndexOutOfBoundsException();
}
final DataNode dn = dataNodes.get(dataNodeIndex).datanode;
final FsDatasetSpi<?> dataSet = DataNodeTestUtils.getFSDataset(dn);
if (!(dataSet instanceof SimulatedFSDataset)) {
throw new IOException("injectBlocks is valid only for SimilatedFSDataset");
}
String bpid = getNamesystem(nameNodeIndex).getBlockPoolId();
SimulatedFSDataset sdataset = (SimulatedFSDataset) dataSet;
sdataset.injectBlocks(bpid, blocksToInject);
dataNodes.get(dataNodeIndex).datanode.scheduleAllBlockReport(0);
}
/**
* Set the softLimit and hardLimit of client lease periods
*/
public void setLeasePeriod(long soft, long hard) {
NameNodeAdapter.setLeasePeriod(getNamesystem(), soft, hard);
}
public void setLeasePeriod(long soft, long hard, int nnIndex) {
NameNodeAdapter.setLeasePeriod(getNamesystem(nnIndex), soft, hard);
}
public void setWaitSafeMode(boolean wait) {
this.waitSafeMode = wait;
}
/**
* Returns the current set of datanodes
*/
DataNode[] listDataNodes() {
DataNode[] list = new DataNode[dataNodes.size()];
for (int i = 0; i < dataNodes.size(); i++) {
list[i] = dataNodes.get(i).datanode;
}
return list;
}
/**
* Access to the data directory used for Datanodes
*/
public String getDataDirectory() {
return data_dir.getAbsolutePath();
}
/**
* Get the base directory for this MiniDFS instance.
* <p/>
* Within the MiniDFCluster class and any subclasses, this method should be
* used instead of {@link #getBaseDirectory()} which doesn't support
* configuration-specific base directories.
* <p/>
* First the Configuration property {@link #HDFS_MINIDFS_BASEDIR} is fetched.
* If non-null, this is returned.
* If this is null, then {@link #getBaseDirectory()} is called.
* @return the base directory for this instance.
*/
protected String determineDfsBaseDir() {
if (conf != null) {
final String dfsdir = conf.get(HDFS_MINIDFS_BASEDIR, null);
if (dfsdir != null) {
return dfsdir;
}
}
return getBaseDirectory();
}
/**
* Get the base directory for any DFS cluster whose configuration does
* not explicitly set it. This is done by retrieving the system property
* {@link #PROP_TEST_BUILD_DATA} (defaulting to "build/test/data" ),
* and returning that directory with a subdir of /dfs.
* @return a directory for use as a miniDFS filesystem.
*/
public static String getBaseDirectory() {
return System.getProperty(PROP_TEST_BUILD_DATA, "build/test/data") + "/dfs/";
}
/**
* Get a storage directory for a datanode in this specific instance of
* a MiniCluster.
*
* @param dnIndex datanode index (starts from 0)
* @param dirIndex directory index (0 or 1). Index 0 provides access to the
* first storage directory. Index 1 provides access to the second
* storage directory.
* @return Storage directory
*/
public File getInstanceStorageDir(int dnIndex, int dirIndex) {
return new File(base_dir, getStorageDirPath(dnIndex, dirIndex));
}
/**
* Get a storage directory for a datanode.
* <ol>
* <li><base directory>/data/data<2*dnIndex + 1></li>
* <li><base directory>/data/data<2*dnIndex + 2></li>
* </ol>
*
* @param dnIndex datanode index (starts from 0)
* @param dirIndex directory index.
* @return Storage directory
*/
public File getStorageDir(int dnIndex, int dirIndex) {
return new File(getBaseDirectory(), getStorageDirPath(dnIndex, dirIndex));
}
/**
* Calculate the DN instance-specific path for appending to the base dir
* to determine the location of the storage of a DN instance in the mini cluster
* @param dnIndex datanode index
* @param dirIndex directory index.
* @return storage directory path
*/
private String getStorageDirPath(int dnIndex, int dirIndex) {
return "data/data" + (storagesPerDatanode * dnIndex + 1 + dirIndex);
}
/**
* Get current directory corresponding to the datanode as defined in
* (@link Storage#STORAGE_DIR_CURRENT}
* @param storageDir the storage directory of a datanode.
* @return the datanode current directory
*/
public static String getDNCurrentDir(File storageDir) {
return storageDir + "/" + Storage.STORAGE_DIR_CURRENT + "/";
}
/**
* Get directory corresponding to block pool directory in the datanode
* @param storageDir the storage directory of a datanode.
* @return the block pool directory
*/
public static String getBPDir(File storageDir, String bpid) {
return getDNCurrentDir(storageDir) + bpid + "/";
}
/**
* Get directory relative to block pool directory in the datanode
* @param storageDir storage directory
* @return current directory in the given storage directory
*/
public static String getBPDir(File storageDir, String bpid, String dirName) {
return getBPDir(storageDir, bpid) + dirName + "/";
}
/**
* Get finalized directory for a block pool
* @param storageDir storage directory
* @param bpid Block pool Id
* @return finalized directory for a block pool
*/
public static File getRbwDir(File storageDir, String bpid) {
return new File(getBPDir(storageDir, bpid, Storage.STORAGE_DIR_CURRENT)
+ DataStorage.STORAGE_DIR_RBW );
}
/**
* Get finalized directory for a block pool
* @param storageDir storage directory
* @param bpid Block pool Id
* @return finalized directory for a block pool
*/
public static File getFinalizedDir(File storageDir, String bpid) {
return new File(getBPDir(storageDir, bpid, Storage.STORAGE_DIR_CURRENT)
+ DataStorage.STORAGE_DIR_FINALIZED );
}
/**
* Get materialized replica that can be corrupted later.
* @param i the index of DataNode.
* @param blk name of the block.
* @return a materialized replica.
* @throws ReplicaNotFoundException if the replica does not exist on the
* DataNode.
*/
public MaterializedReplica getMaterializedReplica(
int i, ExtendedBlock blk) throws ReplicaNotFoundException {
return getFsDatasetTestUtils(i).getMaterializedReplica(blk);
}
/**
* Get materialized replica that can be corrupted later.
* @param dn the index of DataNode.
* @param blk name of the block.
* @return a materialized replica.
* @throws ReplicaNotFoundException if the replica does not exist on the
* DataNode.
*/
public MaterializedReplica getMaterializedReplica(
DataNode dn, ExtendedBlock blk) throws ReplicaNotFoundException {
return getFsDatasetTestUtils(dn).getMaterializedReplica(blk);
}
/**
* Get file correpsonding to a block
* @param storageDir storage directory
* @param blk the block
* @return data file corresponding to the block
*/
public static File getBlockFile(File storageDir, ExtendedBlock blk) {
return new File(DatanodeUtil.idToBlockDir(getFinalizedDir(storageDir,
blk.getBlockPoolId()), blk.getBlockId()), blk.getBlockName());
}
/**
* Get the latest metadata file correpsonding to a block
* @param storageDir storage directory
* @param blk the block
* @return metadata file corresponding to the block
*/
public static File getBlockMetadataFile(File storageDir, ExtendedBlock blk) {
return new File(DatanodeUtil.idToBlockDir(getFinalizedDir(storageDir,
blk.getBlockPoolId()), blk.getBlockId()), blk.getBlockName() + "_" +
blk.getGenerationStamp() + Block.METADATA_EXTENSION);
}
/**
* Return all block metadata files in given directory (recursive search)
*/
public static List<File> getAllBlockMetadataFiles(File storageDir) {
List<File> results = new ArrayList<File>();
File[] files = storageDir.listFiles();
if (files == null) {
return null;
}
for (File f : files) {
if (f.getName().startsWith(Block.BLOCK_FILE_PREFIX) &&
f.getName().endsWith(Block.METADATA_EXTENSION)) {
results.add(f);
} else if (f.isDirectory()) {
List<File> subdirResults = getAllBlockMetadataFiles(f);
if (subdirResults != null) {
results.addAll(subdirResults);
}
}
}
return results;
}
/**
* Shut down a cluster if it is not null
* @param cluster cluster reference or null
*/
public static void shutdownCluster(MiniDFSCluster cluster) {
if (cluster != null) {
cluster.shutdown();
}
}
/**
* Get all files related to a block from all the datanodes
* @param block block for which corresponding files are needed
*/
public File[] getAllBlockFiles(ExtendedBlock block) {
if (dataNodes.size() == 0) return new File[0];
ArrayList<File> list = new ArrayList<File>();
for (int i=0; i < dataNodes.size(); i++) {
File blockFile = getBlockFile(i, block);
if (blockFile != null) {
list.add(blockFile);
}
}
return list.toArray(new File[list.size()]);
}
/**
* Get the block data file for a block from a given datanode
* @param dnIndex Index of the datanode to get block files for
* @param block block for which corresponding files are needed
*/
public File getBlockFile(int dnIndex, ExtendedBlock block) {
// Check for block file in the two storage directories of the datanode
for (int i = 0; i <=1 ; i++) {
File storageDir = getStorageDir(dnIndex, i);
File blockFile = getBlockFile(storageDir, block);
if (blockFile.exists()) {
return blockFile;
}
}
return null;
}
/**
* Get the block metadata file for a block from a given datanode
*
* @param dnIndex Index of the datanode to get block files for
* @param block block for which corresponding files are needed
*/
public File getBlockMetadataFile(int dnIndex, ExtendedBlock block) {
// Check for block file in the two storage directories of the datanode
for (int i = 0; i <=1 ; i++) {
File storageDir = getStorageDir(dnIndex, i);
File blockMetaFile = getBlockMetadataFile(storageDir, block);
if (blockMetaFile.exists()) {
return blockMetaFile;
}
}
return null;
}
/**
* Throw an exception if the MiniDFSCluster is not started with a single
* namenode
*/
private void checkSingleNameNode() {
if (nameNodes.length != 1) {
throw new IllegalArgumentException("Namenode index is needed");
}
}
/**
* Add a namenode to a federated cluster and start it. Configuration of
* datanodes in the cluster is refreshed to register with the new namenode.
*
* @return newly started namenode
*/
public void addNameNode(Configuration conf, int namenodePort)
throws IOException {
if(!federation)
throw new IOException("cannot add namenode to non-federated cluster");
int nnIndex = nameNodes.length;
int numNameNodes = nameNodes.length + 1;
NameNodeInfo[] newlist = new NameNodeInfo[numNameNodes];
System.arraycopy(nameNodes, 0, newlist, 0, nameNodes.length);
nameNodes = newlist;
String nameserviceId = NAMESERVICE_ID_PREFIX + (nnIndex + 1);
String nameserviceIds = conf.get(DFS_NAMESERVICES);
nameserviceIds += "," + nameserviceId;
conf.set(DFS_NAMESERVICES, nameserviceIds);
String nnId = null;
initNameNodeAddress(conf, nameserviceId,
new NNConf(nnId).setIpcPort(namenodePort));
initNameNodeConf(conf, nameserviceId, nnId, true, true, nnIndex);
createNameNode(nnIndex, conf, numDataNodes, true, null, null,
nameserviceId, nnId);
// Refresh datanodes with the newly started namenode
for (DataNodeProperties dn : dataNodes) {
DataNode datanode = dn.datanode;
datanode.refreshNamenodes(conf);
}
// Wait for new namenode to get registrations from all the datanodes
waitActive(nnIndex);
}
protected void setupDatanodeAddress(Configuration conf, boolean setupHostsFile,
boolean checkDataNodeAddrConfig) throws IOException {
if (setupHostsFile) {
String hostsFile = conf.get(DFS_HOSTS, "").trim();
if (hostsFile.length() == 0) {
throw new IOException("Parameter dfs.hosts is not setup in conf");
}
// Setup datanode in the include file, if it is defined in the conf
String address = "127.0.0.1:" + NetUtils.getFreeSocketPort();
if (checkDataNodeAddrConfig) {
conf.setIfUnset(DFS_DATANODE_ADDRESS_KEY, address);
} else {
conf.set(DFS_DATANODE_ADDRESS_KEY, address);
}
addToFile(hostsFile, address);
LOG.info("Adding datanode " + address + " to hosts file " + hostsFile);
} else {
if (checkDataNodeAddrConfig) {
conf.setIfUnset(DFS_DATANODE_ADDRESS_KEY, "127.0.0.1:0");
} else {
conf.set(DFS_DATANODE_ADDRESS_KEY, "127.0.0.1:0");
}
}
if (checkDataNodeAddrConfig) {
conf.setIfUnset(DFS_DATANODE_HTTP_ADDRESS_KEY, "127.0.0.1:0");
conf.setIfUnset(DFS_DATANODE_IPC_ADDRESS_KEY, "127.0.0.1:0");
} else {
conf.set(DFS_DATANODE_HTTP_ADDRESS_KEY, "127.0.0.1:0");
conf.set(DFS_DATANODE_IPC_ADDRESS_KEY, "127.0.0.1:0");
}
}
private void addToFile(String p, String address) throws IOException {
File f = new File(p);
f.createNewFile();
PrintWriter writer = new PrintWriter(new FileWriter(f, true));
try {
writer.println(address);
} finally {
writer.close();
}
}
}
| [
"[email protected]"
]
| |
2664e932ef49a352ce1c158891f4d007c2e18a9a | 932ec1443fb0e0e692bf71ac626c1c90da3c4b14 | /src/test/java/Rough/Fake.java | 57c3c0a34bf0b96412585c60429419df5960c029 | []
| no_license | GitAccountTesting/AAPC001 | c4600994eb51c5644468335a3f861f12eb480693 | 4c1e273fe280f569e52d6afbf283488709ffb448 | refs/heads/master | 2021-01-20T20:35:42.417894 | 2016-07-29T07:23:07 | 2016-07-29T07:23:07 | 64,413,718 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,056 | java | package Rough;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Fake {
public static void main(String[] args) {
WebDriver driver=new FirefoxDriver();
driver.get("https://www.aapc.com/login.aspx?r=https://www.aapc.com/index.aspx");
driver.findElement(By.id("ctl00_body_UserName")).sendKeys("[email protected]");
driver.findElement(By.id("ctl00_body_Password")).sendKeys("123456789");
driver.findElement(By.id("ctl00_body_LoginButton")).click();
/*driver.findElement(By.xpath("//*[@id='MyAAPCMenuItem']/a")).click();
driver.findElement(By.xpath("//*[@id='ctl00_MasterPageBodyTag']/div[1]/div/a")).click();
driver.findElement(By.linkText("Membership")).click();*/
//WebDriverWait wait=new WebDriverWait(driver, 10);
//wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id='aspnetForm']/div[4]/div[4]/div[3]/div[3]/div/div[3]/ul/li[1]/a")));
driver.findElement(By.cssSelector(".textual-link.pre-header-link-icd10>a")).click();
driver.findElement(By.cssSelector(".textual-link.pre-header-link-blog>a")).click();
driver.findElement(By.cssSelector(".textual-link.pre-header-link-forum>a")).click();
driver.findElement(By.cssSelector(".forum.textual-link.pre-header-link-events>a")).click();
driver.findElement(By.cssSelector(".contactus>a")).click();
driver.findElement(By.cssSelector(".do-not-hide-search-box")).click();
driver.navigate().back();
driver.findElement(By.cssSelector(".cart>a>i")).click();
driver.navigate().back();
/* driver.findElement(By.xpath("//*[@id='aspnetForm']/div[4]/div[4]/div[3]/div[3]/div/div[3]/ul/li[2]/a")).click();
driver.findElement(By.xpath("//*[@id='aspnetForm']/div[4]/div[4]/div[3]/div[3]/div/div[3]/ul/li[3]/a")).click();
driver.findElement(By.xpath("//*[@id='aspnetForm']/div[4]/div[4]/div[3]/div[3]/div/div[3]/ul/li[4]/a")).click();
*/
}
}
| [
"[email protected]"
]
| |
59defc6efaa02f2556ef4968a7b5de802e340f81 | cb2c56f38e5713105869012501b9fce71454910b | /src/main/java/com/fortify/ssc/restclient/model/CloudPoolWorkerActionResponse.java | e4e9c68183d22e17c4ff4bad266d9923e504800d | [
"MIT"
]
| permissive | ilatypov/ssc-restapi-client | 0c0d87d23f7f88cae04c2ed23b77798fafbfd112 | 1a632fc021a07e0a609efbb6c90caa4238cbda27 | refs/heads/master | 2022-01-23T04:41:55.217639 | 2020-06-22T06:59:22 | 2020-06-22T07:32:54 | 248,676,011 | 0 | 0 | MIT | 2021-12-29T19:29:27 | 2020-03-20T05:33:51 | Java | UTF-8 | Java | false | false | 2,886 | java | /*
* Fortify Software Security Center API
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: 1:18.20
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package com.fortify.ssc.restclient.model;
import java.util.Objects;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Result of cloud scan workers related actions
*/
@ApiModel(description = "Result of cloud scan workers related actions")
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2018-07-09T13:54:27.094-07:00")
public class CloudPoolWorkerActionResponse {
@SerializedName("workerUuids")
private List<String> workerUuids = null;
public CloudPoolWorkerActionResponse workerUuids(List<String> workerUuids) {
this.workerUuids = workerUuids;
return this;
}
public CloudPoolWorkerActionResponse addWorkerUuidsItem(String workerUuidsItem) {
if (this.workerUuids == null) {
this.workerUuids = new ArrayList<String>();
}
this.workerUuids.add(workerUuidsItem);
return this;
}
/**
* Cloud scan worker uuids
* @return workerUuids
**/
@ApiModelProperty(value = "Cloud scan worker uuids")
public List<String> getWorkerUuids() {
return workerUuids;
}
public void setWorkerUuids(List<String> workerUuids) {
this.workerUuids = workerUuids;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CloudPoolWorkerActionResponse cloudPoolWorkerActionResponse = (CloudPoolWorkerActionResponse) o;
return Objects.equals(this.workerUuids, cloudPoolWorkerActionResponse.workerUuids);
}
@Override
public int hashCode() {
return Objects.hash(workerUuids);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class CloudPoolWorkerActionResponse {\n");
sb.append(" workerUuids: ").append(toIndentedString(workerUuids)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| [
"[email protected]"
]
| |
8513ccf6415786294e83d9d20c5b58c8fff9fc9f | 145957bdde25d225ec6687fc9b769e3e2632182f | /esc/src/main/java/org/apache/commons/vfs2/provider/smb/SmbFileProvider.java | 5528fc39a6793e3dacc36236a40db0dc59e74034 | [
"Apache-2.0"
]
| permissive | tamirko/cloudify | 1d96082bc2c58ca019cbaf0dc7394b59c5328676 | 14618621241fb69a6936905e57f5d7e1216f1404 | refs/heads/master | 2021-01-17T23:07:06.407471 | 2013-04-24T09:02:14 | 2013-04-29T07:52:47 | 9,743,818 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,854 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.smb;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.UserAuthenticationData;
import org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider;
import org.apache.commons.vfs2.provider.FileProvider;
/**
* A provider for SMB (Samba, Windows share) file systems.
* CHECKSTYLE:OFF
* @author <a href="mailto:[email protected]">Adam Murdoch</a>
*/
public class SmbFileProvider
extends AbstractOriginatingFileProvider
implements FileProvider
{
protected final static Collection<Capability> capabilities = Collections.unmodifiableCollection(Arrays.asList(
Capability.CREATE,
Capability.DELETE,
Capability.RENAME,
Capability.GET_TYPE,
Capability.GET_LAST_MODIFIED,
Capability.LIST_CHILDREN,
Capability.READ_CONTENT,
Capability.URI,
Capability.WRITE_CONTENT,
Capability.APPEND_CONTENT,
Capability.RANDOM_ACCESS_READ,
Capability.RANDOM_ACCESS_WRITE
));
public final static UserAuthenticationData.Type[] AUTHENTICATOR_TYPES = new UserAuthenticationData.Type[]
{
UserAuthenticationData.USERNAME, UserAuthenticationData.PASSWORD, UserAuthenticationData.DOMAIN
};
public SmbFileProvider()
{
super();
setFileNameParser(SmbFileNameParser.getInstance());
}
/**
* Creates the filesystem.
*/
@Override
protected FileSystem doCreateFileSystem(final FileName name, final FileSystemOptions fileSystemOptions)
throws FileSystemException
{
return new SmbFileSystem(name, fileSystemOptions);
}
@Override
public Collection<Capability> getCapabilities()
{
return capabilities;
}
}
| [
"[email protected]"
]
| |
b70af977c0cf4e523e216605386e9831ad8c7a3f | d335779cb557b6aa8fa92bc67af391c26bd4426f | /src/gui/SearchGUI.java | 883912c40a5a7d9f0af4ee19e18c91171134a651 | []
| no_license | fionamac89/InformationAccess | 4f2915179e89d8adccea81ffde7a6153761e9a43 | 3eca35c14239f8eeb1bd49f94c7e652a461f928b | refs/heads/master | 2021-01-16T19:02:32.569977 | 2014-01-07T17:55:51 | 2014-01-07T17:55:51 | 13,311,089 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,901 | java | package gui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JTree;
import javax.swing.WindowConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import parser.Article;
import system.WallStreetSystem;
public class SearchGUI extends JFrame implements TreeSelectionListener {
private JRadioButton bodyBox;
private JTextPane docPane;
private JLabel docTitle;
private JTree docTree;
private JRadioButton headLineBox;
private JRadioButton leadParBox;
private JLabel resultsLabel;
private JButton searchButton;
private JTextField searchField;
private JPanel searchPanel;
private JButton searchViewButton;
private JLabel suggestLabel;
private JRadioButton tagsBox;
private JRadioButton allBox;
private JScrollPane textScroll;
private JLabel titleLabel;
private JScrollPane treeScroll;
private JPanel viewPanel;
private JPanel searchHolder;
private JPanel fieldsHolder;
private JSplitPane splitPane;
private JPanel titlePanel;
private ButtonGroup group;
private JPanel suggestPanel;
private List<Article> articles = null;
private WallStreetSystem system = null;
private String action = "contents";
public SearchGUI() {
initComponents();
system = new WallStreetSystem();
}
public void initComponents() {
searchPanel = new JPanel();
searchHolder = new JPanel();
fieldsHolder = new JPanel();
searchField = new JTextField(32);
searchButton = new JButton("Search");
titleLabel = new JLabel("Wall Street Journal System");
suggestLabel = new JLabel();
headLineBox = new JRadioButton("Headline");
tagsBox = new JRadioButton("Tags");
leadParBox = new JRadioButton("Leading Paragraph");
bodyBox = new JRadioButton("Text Body");
allBox = new JRadioButton("Full Text");
viewPanel = new JPanel();
docPane = new JTextPane();
textScroll = new JScrollPane(docPane,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
docTitle = new JLabel("Document Viewer");
resultsLabel = new JLabel("Results");
docTree = new JTree(new DefaultMutableTreeNode(null));
treeScroll = new JScrollPane(docTree,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
searchViewButton = new JButton("Search View");
splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, treeScroll,
textScroll);
titlePanel = new JPanel();
group = new ButtonGroup();
suggestPanel = new JPanel();
searchButton.setName("searchButton");
searchViewButton.setName("searchView");
searchField.getDocument().addDocumentListener(new MyDocumentListener());
// JFrame
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setTitle("Wall Street Journal Viewer");
setMinimumSize(new Dimension(480, 360));
setName("mainFrame"); // NOI18N
setResizable(true);
setPreferredSize(new Dimension(720, 480));
headLineBox.addActionListener(new radioListener());
leadParBox.addActionListener(new radioListener());
bodyBox.addActionListener(new radioListener());
tagsBox.addActionListener(new radioListener());
allBox.addActionListener(new radioListener());
headLineBox.setActionCommand("headline");
leadParBox.setActionCommand("leadPar");
bodyBox.setActionCommand("body");
tagsBox.setActionCommand("in");
allBox.setActionCommand("contents");
suggestLabel.setPreferredSize(new Dimension(250, 100));
docPane.setContentType("text/html");
suggestPanel.setPreferredSize(new Dimension(500, 200));
suggestPanel.add(suggestLabel);
searchHolder.add(searchField, BorderLayout.PAGE_END);
searchHolder.add(searchButton, BorderLayout.PAGE_END);
// fieldsHolder.setLayout(new FlowLayout());
fieldsHolder.add(headLineBox, BorderLayout.NORTH);
fieldsHolder.add(leadParBox, BorderLayout.NORTH);
fieldsHolder.add(bodyBox, BorderLayout.NORTH);
fieldsHolder.add(tagsBox, BorderLayout.NORTH);
fieldsHolder.add(allBox, BorderLayout.NORTH);
// fieldsHolder.add(suggestLabel, BorderLayout.SOUTH);
group.add(headLineBox);
group.add(leadParBox);
group.add(tagsBox);
group.add(allBox);
group.add(bodyBox);
titleLabel.setPreferredSize(new Dimension(300, 150));
titleLabel.setAlignmentX(CENTER_ALIGNMENT);
searchPanel.setLayout(new BoxLayout(searchPanel, BoxLayout.PAGE_AXIS));
searchPanel.add(titleLabel);
searchPanel.add(searchHolder);
searchPanel.add(fieldsHolder);
searchPanel.add(suggestPanel);
searchPanel.setPreferredSize(this.getPreferredSize());
resultsLabel.setPreferredSize(new Dimension(200, 50));
docTitle.setPreferredSize(new Dimension(200, 50));
titlePanel.setPreferredSize(new Dimension(500, 50));
titlePanel.add(resultsLabel);
titlePanel.add(docTitle);
viewPanel.setPreferredSize(new Dimension(720, 480));
docTree.setEditable(false);
docTree.setName("docTree");
docTree.setRowHeight(0);
docTree.setCellRenderer(new ResultsCellRenderer());
docTree.addTreeSelectionListener(this);
splitPane.setOneTouchExpandable(true);
splitPane.setDividerLocation(200);
splitPane.setPreferredSize(new Dimension(620, 330));
Dimension minimumSize = new Dimension(100, 100);
treeScroll.setMinimumSize(minimumSize);
treeScroll.setViewportView(docTree);
textScroll.setMinimumSize(minimumSize);
textScroll.setViewportView(docPane);
viewPanel.add(titlePanel, BorderLayout.PAGE_START);
viewPanel.add(splitPane, BorderLayout.CENTER);
viewPanel.add(searchViewButton, BorderLayout.PAGE_END);
// setSearchVisible();
searchButton.addActionListener(new searchButtonListener());
searchViewButton.addActionListener(new searchViewListener());
setSearchVisible();
this.add(searchPanel);
this.add(viewPanel);
this.setResizable(false);
this.pack();
this.setVisible(true);
}
public void setSearchVisible() {
getContentPane().removeAll();
getContentPane().add(searchPanel);
docTree.setModel(null);
docPane.setText("");
repaint();
pack();
}
public void setViewVisible() {
getContentPane().removeAll();
getContentPane().add(viewPanel);
repaint();
pack();
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SearchGUI();
}
});
}
@Override
public void valueChanged(TreeSelectionEvent evt) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) docTree
.getLastSelectedPathComponent();
if (node == null)
return;
Object nodeInfo = node.getUserObject();
if (node.isLeaf() && nodeInfo instanceof Article) {
Article art = (Article) nodeInfo;
docPane.setText(art.displayInfo());
} else if (node == null || node.isRoot()) {
docPane.setText("No Results");
}
docPane.updateUI();
}
public void populateTree() {
DefaultMutableTreeNode node = buildNodeFromString();
DefaultTreeModel model = new DefaultTreeModel(node);
docTree.setModel(model);
docTree.updateUI();
}
public DefaultMutableTreeNode buildNodeFromString() {
DefaultMutableTreeNode node = null, root = null;
root = new DefaultMutableTreeNode("Query: " + searchField.getText());
for (Article key : articles) {
node = new DefaultMutableTreeNode(key);
root.add(node);
}
return root;
}
class searchButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (searchField.getText().length() < 2) {
JOptionPane
.showConfirmDialog(
searchPanel,
"You must enter a valid query to be able to perform a search.",
"Search", JOptionPane.WARNING_MESSAGE,
JOptionPane.OK_OPTION);
searchField.setText("");
} else {
String[] fields = { action };
system.search(searchField.getText(), fields);
articles = system.getResults();
populateTree();
setViewVisible();
}
}
}
class searchViewListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
setSearchVisible();
}
}
class radioListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
action = e.getActionCommand();
}
}
class MyDocumentListener implements DocumentListener {
String newline = "\n";
public void insertUpdate(DocumentEvent e) {
updateLog(e);
}
public void removeUpdate(DocumentEvent e) {
updateLog(e);
}
public void changedUpdate(DocumentEvent e) {
// Plain text components do not fire these events
}
public void updateLog(DocumentEvent e) {
Document doc = (Document) e.getDocument();
try {
String s = doc.getText(0, doc.getLength());
if (s.length() > 0) {
String suggestions[] = system.suggestions(s);
String temp = "<html>";
if (suggestions != null && suggestions.length > 0) {
for (String word : suggestions) {
temp = temp + "Did you mean: " + word + "<br>";
}
temp = temp + "</html>";
suggestLabel.setText(temp);
//repaint();
} else {
temp = "No suggestions found for word:" + s;
}
} else {
suggestLabel.setText("");
//repaint();
}
} catch (BadLocationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
| [
"[email protected]"
]
| |
25d51bd8b9c768d947256d89f42c8039d644274c | 3e3d6be6a13598a57350166e259f50041d6e5f31 | /user/user-domain/src/main/java/com/zkteco/user/domain/entity/Role.java | ac04c188592f9f12ce3b61fb89a52eaa7d0bef8f | [
"Apache-2.0"
]
| permissive | fengkai/bionest | ea101564d45ced238d478ac5510191c2e4056bf3 | ea96198ab4a9d4df758d90c0c3e0b252eec36892 | refs/heads/main | 2023-08-14T14:13:10.388085 | 2021-09-16T01:02:31 | 2021-09-16T01:02:31 | 391,029,495 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 259 | java | package com.zkteco.user.domain.entity;
import java.util.Set;
import lombok.Data;
import org.springframework.lang.Nullable;
@Data
public class Role {
@Nullable
private Long id;
private String name;
@Nullable
private Set<Authority> authoritySet;
}
| [
"[email protected]"
]
| |
2ce3162318fc1f1e794f0e4a660961b5309a398d | 748ae693dd3552dbbe7c72cf718ad8b917b082f6 | /src/Day19/JavaSetTask16.java | d71d5d17985b71f26af3cdc48726136321d01543 | []
| no_license | Ezra7777/TechnoStudyJava | 2337be450568fda6e3c5ab8562054fd770d77b90 | a8e8d691fd4790890811ae21932156c69409cea7 | refs/heads/master | 2020-08-28T15:34:59.985010 | 2019-12-08T21:03:34 | 2019-12-08T21:03:34 | 217,741,195 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,338 | java | package Day19;
import java.util.ArrayList;
import java.util.HashSet;
public class JavaSetTask16 {
//16. You have list of numbers, determine if you have duplication there
//ex: [1, 2, 3, 4, 4, 5, 6] => has duplications
//ex2: [1, 2, 3] => no duplications
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(4);
list.add(5);
list.add(6);
System.out.println(list + " size:" + list.size());
// 1, 1, 2, 3....
// HashSet<Integer> mySet = new HashSet<>(list);
// System.out.println(mySet + " size:" + mySet.size());
//
// System.out.println("1. way");
// if (list.size() != mySet.size()) {
// System.out.println("has duplications");
// } else {
// System.out.println("no duplications");
// }
// 1, 1, 2, 3....
System.out.println("2. way");
HashSet<Integer> mySet = new HashSet<>();
for (Integer number : list) {
if (mySet.contains(number)) {
System.out.println("Set already has this number: " + number);
break;
} else {
mySet.add(number);
}
}
}
}
| [
"[email protected]"
]
| |
6d7521ed890ec43c5f5cc556749e73d38d97f1f0 | 0f7cc0ce031b66206cd432f7368fd6a52b067999 | /src/composition/Test.java | 670675cfb443563ee757c2d4ee5e2aa34bd8c976 | []
| no_license | JisooJang/EffectiveJava | bdeab7aacd8b26790bb5a42ed724655b67522b58 | 677913e89dab14fec75099884db0948281932bdc | refs/heads/master | 2022-10-19T10:43:14.197897 | 2020-06-14T14:29:00 | 2020-06-14T14:29:00 | 265,797,585 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 944 | java | package composition;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class Test {
public static void main(String[] args) {
InstrumentedHashSet<String> s = new InstrumentedHashSet<>();
s.addAll(List.of("a", "aa", "aaa"));
System.out.println(s.getCount()); // 기대한 값인 3이 아니라 6이다.
InstrumentedSet<String> s2 = new InstrumentedSet<>();
s2.addAll(List.of("b", "bb,", "bbb"));
System.out.println(s2.getCount()); // 컴포지션 클래스인 InstrumentedSet을 이용하여 기대한 갑인 3을 리턴한다.
System.out.println("======================");
Set<Integer> s3 = new InstrumentedSet<>(new TreeSet<>());
Set<Integer> s4 = new InstrumentedSet<>(new HashSet<>(10));
Sub sub = new Sub();
System.out.println("======================");
sub.overrideMe();
}
}
| [
"[email protected]"
]
| |
9ef38f901f8ea866f31d3baff26831c77f0cfbeb | 588a14abcf44e81c83cd6fc17421bd3436eb364b | /src/main/java/org/jzkangta/tlspc/wechat/service/impl/WechatBaseServiceImpl.java | 21b9fdccf3bd084f39b3679aa70de51830659e4d | []
| no_license | wangjun1984/tlspc | ea9d494a82e39f60f64dc6aa8490bbf114b6c625 | 9464ae0e0e2693f5042fa332ad18c182127cc429 | refs/heads/master | 2016-09-14T18:28:19.645249 | 2016-04-14T09:29:41 | 2016-04-14T09:29:41 | 56,148,209 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,138 | java | package org.jzkangta.tlspc.wechat.service.impl;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import org.jzkangta.tlspc.wechat.entity.Articles;
import org.jzkangta.tlspc.wechat.entity.Video;
import org.jzkangta.tlspc.wechat.service.WechatService;
import org.jzkangta.tlspc.wechat.util.ReceiveMessageUtil;
import org.jzkangta.tlspc.framework.util.DateUtil;
import org.jzkangta.tlspc.framework.util.PropertyUtil;
import org.jzkangta.tlspc.framework.util.StringUtil;
/**
*
* @author wushubin
*
*/
public abstract class WechatBaseServiceImpl implements WechatService{
private static Logger log = LoggerFactory.getLogger(WechatBaseServiceImpl.class);
private static Logger subscribeLog = LoggerFactory.getLogger("subscribe.user");
private static String propertiesFileName = "wechat";
private static String DEBUG ;
static{
DEBUG = PropertyUtil.getProperty(propertiesFileName, "debug");
}
/**
* 接收请求后,推送信息
* @param request
* @return
*/
@Override
public String push(HttpServletRequest request) {
String respMessage = null;
try {
Map<String, String> requestMap = ReceiveMessageUtil.parseXml(request);
String msgType = requestMap.get("MsgType");//消息类型
if ("true".equals(DEBUG)) {
log.debug("func[processRequest] requestMap[{}] ", new Object[] { JSON.toJSONString(requestMap) });
}
if (ReceiveMessageUtil.REQ_MESSAGE_TYPE_EVENT.equalsIgnoreCase(msgType)) {
respMessage = this.getEventResult(requestMap);
} else if (ReceiveMessageUtil.REQ_MESSAGE_TYPE_DEVICE_TEXT.equalsIgnoreCase(msgType)) {
respMessage = this.getDeviceMessageResult(requestMap);
} else if (ReceiveMessageUtil.REQ_MESSAGE_TYPE_DEVICE_EVENT.equalsIgnoreCase(msgType)) {
respMessage = this.getDeviceEventResult(requestMap);
} else if (ReceiveMessageUtil.getRequestMessageTypeMap(msgType) != null) {
respMessage = this.getMessageResult(requestMap);
} else {
respMessage = this.getUnknowResult(requestMap);
}
} catch (Exception e) {
log.error("func[processRequest] exception[{} - {}] desc[fail]",
new Object[] { e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
}
return respMessage;
}
/**
* 根据事件返回信息
* @param requestMap
* @param articleList
* @return
*/
public String getEventResult(Map<String, String> requestMap ){
String fromUserName = requestMap.get("FromUserName");//接收方帐号(收到的OpenID)
String toUserName = requestMap.get("ToUserName");//开发者微信号
String eventType = requestMap.get("Event");//事件类型
String instructions = requestMap.get("Content");//用户上行内容
String eventKey = requestMap.get("EventKey");//企业微信用户输入的认证信息
String cardId = requestMap.get("CardId");//审核卡券的ID
String friendUserName = requestMap.get("FriendUserName");//赠送方账号(一个 OpenID),"IsGiveByFriend” 为 1 时填写该参数
String isGiveByFriend = requestMap.get("IsGiveByFriend");//是否为转赠, 1 代表是, 0 代表否。
String userCardCode = requestMap.get("UserCardCode");//code 序列号。
String outerId = requestMap.get("OuterId");//领取场景值,用于领取渠道数据统计。
String ticket = requestMap.get("Ticket");//用于查询推广渠道id
String logMessage = "";
String respMessage = "";
//事件请求
if (eventType.equalsIgnoreCase(ReceiveMessageUtil.EVENT_TYPE_SUBSCRIBE)) {
if(!StringUtil.isEmpty(ticket))
subscribeLog.info("{},{},{}",new Object[]{fromUserName ,ticket , DateUtil.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss") });
logMessage = " 关注了";
respMessage = this.handleSubscribeEventMessage(requestMap);
} else if (eventType.equalsIgnoreCase(ReceiveMessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
logMessage = " 取消关注了";
respMessage = this.handleUnsubscribeEventMessage(requestMap);
} else if (eventType.equalsIgnoreCase(ReceiveMessageUtil.EVENT_TYPE_CLICK)) {
logMessage = " 点击投诉建议";
Object contentList = this.getContentText(eventKey);
respMessage = ReceiveMessageUtil.getTextMessage(fromUserName, toUserName, (String)contentList);
} else if (eventType.equalsIgnoreCase(ReceiveMessageUtil.EVENT_TYPE_QY_VERIFY)) {
logMessage = " 企业微信用户二次身份验证";
respMessage = verifyQywechatUser(fromUserName, eventKey);
} else if (eventType.equalsIgnoreCase(ReceiveMessageUtil.EVENT_TYPE_LOCATION)) {
logMessage = " 首次上报地理位置事件";
Object contentList = this.getContentList(instructions);
respMessage = ReceiveMessageUtil.getNewsMessage(fromUserName, toUserName, (List<Articles>)contentList);
}
if ("true".equalsIgnoreCase(DEBUG)) {
log.debug(toUserName + logMessage);
}
return respMessage;
}
public abstract String handleSubscribeEventMessage(Map<String, String> requestMap);
public abstract String handleUnsubscribeEventMessage(Map<String, String> requestMap);
/**
* 根据指令返回信息
* @param requestMap
* @param articleList
* @return
*/
public String getMessageResult(Map<String, String> requestMap){
String fromUserName = requestMap.get("FromUserName");//接收方帐号(收到的OpenID)
String toUserName = requestMap.get("ToUserName");//开发者微信号
String msgType = requestMap.get("MsgType");//消息类型
String instructions = requestMap.get("Content");//用户上行内容
//
String logMessage = ReceiveMessageUtil.getRequestMessageTypeMap(msgType);
String respMessage = "";
if(msgType.equalsIgnoreCase(ReceiveMessageUtil.REQ_MESSAGE_TYPE_LOCATION)){
//上行地理信息
String latitude = requestMap.get("Latitude");//用户纬度
String longitude = requestMap.get("Longitude");//用户经度
String precision = requestMap.get("Precision");//用户精度
respMessage = ReceiveMessageUtil.getNewsMessage(fromUserName, toUserName, this.getContentList(latitude, longitude));
} else if(msgType.equalsIgnoreCase(ReceiveMessageUtil.REQ_MESSAGE_TYPE_TEXT)){
//上行指令
// respMessage = ReceiveMessageUtil.getTextMessage(fromUserName, toUserName, this.getContentText(fromUserName, instructions));
respMessage = this.replyTextMessage(fromUserName, toUserName, instructions);
} else if(msgType.equalsIgnoreCase(ReceiveMessageUtil.REQ_MESSAGE_TYPE_IMAGE)){
//上行图片
//respMessage = ReceiveMessageUtil.getImageMessage(fromUserName, toUserName, this.getContentText(instructions));
respMessage = "success";
} else if(msgType.equalsIgnoreCase(ReceiveMessageUtil.REQ_MESSAGE_TYPE_VOICE)){
//上行语音
//respMessage = ReceiveMessageUtil.getVoiceMessage(fromUserName, toUserName, this.getContentText(instructions));
respMessage = "success";
} else if(msgType.equalsIgnoreCase(ReceiveMessageUtil.REQ_MESSAGE_TYPE_VIDEO)){
//上行视频
//respMessage = ReceiveMessageUtil.getVideoMessage(fromUserName, toUserName, this.getContentVideo(instructions));
respMessage = "success";
}
if ("true".equals(DEBUG)) {
log.debug(toUserName + logMessage);
}
return respMessage;
}
/**
* 未知指令,下发默认信息
* @param requestMap
* @return
*/
public String getUnknowResult(Map<String, String> requestMap){
String fromUserName = requestMap.get("FromUserName");//开发者微信号
String toUserName = requestMap.get("ToUserName");//接收方帐号(收到的OpenID)
String msgType = requestMap.get("MsgType");//消息类型
String logMessage = " 发出了未知的msgType请求:" + msgType;
String respMessage = ReceiveMessageUtil.getTextMessage(fromUserName, toUserName,"");
if ("true".equalsIgnoreCase(DEBUG)) {
log.debug(toUserName + logMessage);
}
return respMessage;
}
/**
* 获取视频内容
* @param instructions 微信指令
* @return
*/
public abstract Video getContentVideo(String instructions);
/**
* 获取内容
* @param instructions 微信指令
* @return
*/
public abstract String getContentText(String instructions);
/**
* 获取内容
* @param instructions 微信指令
* @return
*/
public abstract String getContentText(String toUserName, String instructions);
/**
* 获取列表内容
* @param instructions 微信指令
* @return
*/
public abstract List<Articles> getContentList(String instructions);
/**
* 根据用户经纬度,下发信息
* @param latitude 用户纬度
* @param longitude 用户经度
* @return
*/
public abstract List<Articles> getContentList(String latitude,String longitude );
/**
* 企业微信用户二次身份验证
* @param fromUserName 员工userid
* @param key 员工输入的认证信息
* @return
*/
public abstract String verifyQywechatUser(String fromUserName,String key);
/**
* 通知卡券审核信息
* @param cardId 卡券ID
* @param result 审核结果 0通过 1不通过
* @return
*/
public abstract String notifyCardStatus(String cardId,int result);
/**
* 用户领取,赠送卡券通知
* @param cardId
* @param fromUserName 领券方帐号(一个 OpenID)
* @param friendUserName 赠送方账号(一个 OpenID),"IsGiveByFriend” 为 1 时填写该参数。
* @param isGiveByFriend 是否为转赠, 1 代表是, 0 代表否
* @param userCardCode code 序列号
* @param outerId 领取场景值,用于领取渠道数据统计。
* @return
*/
public abstract String notifyReceiveCardCode(String cardId,String fromUserName,String friendUserName,String isGiveByFriend,String userCardCode,String outerId);
/**
* 用户删除卡券通知
* @param cardId
* @param fromUserName 发送方帐号(一个 OpenID)
* @param userCardCode 商户自定义 code 值。 非自定 code 推送为空串。
* @return
*/
public abstract String notifyDeleteCardCode(String cardId,String fromUserName,String userCardCode );
/**
* 根据事件返回信息
* @param requestMap
* @param articleList
* @return
*/
public String getDeviceEventResult(Map<String, String> requestMap ){
//String fromUserName = requestMap.get("FromUserName");//发送方(微信用户)的 user name
String toUserName = requestMap.get("ToUserName");//接收方(公众号)的 user name
//String createTime = requestMap.get("CreateTime");//消息创建时间,消息后台生成
String eventType = requestMap.get("Event");//事件类型,取值为 bind/unbind ,bind:绑定设备 unbind:解除绑定
//String msgType = requestMap.get("MsgType");//消息类型:device_event
//String deviceType = requestMap.get("DeviceType");//设备类型,目前为“公众账号原始 ID”
//String deviceID = requestMap.get("DeviceID");//设备 ID,第三方提供
//String content = requestMap.get("Content");//当 Event 为 bind 时, Content 字段存放二维码中 第三方追加的自定义的数据(详情见 1.5 章节 获取设备二维码 或 1.11.1 章节 API:获取 deviceid 和二维码)
//String sessionID = requestMap.get("SessionID");//微信客户端生成的 session id,用于 request 和response 对应,因此响应中该字段第三方需要原封不变的带回
//String openID = requestMap.get("OpenID");//微信账号的 OpenID
//String opType = requestMap.get("OpType");//请求类型:0:退订设备状态;1:心跳;(心跳的处理方式跟订阅一样);2:订阅设备状态;
String respMessage = "";
String logMessage = "";
//事件请求
/*if (eventType.equalsIgnoreCase(ReceiveMessageUtil.EVENT_TYPE_DEVICE_BIND)) {
logMessage = " 绑定蓝牙设备";
DeviceBluetoothMessage deviceMessage = this.handleBluetoothBindEventMessage(requestMap);
respMessage = ReceiveMessageUtil.getBluetoothEventMessage(deviceMessage);
} else if (eventType.equalsIgnoreCase(ReceiveMessageUtil.EVENT_TYPE_DEVICE_UNBIND)) {
logMessage = " 解绑蓝牙设备";
DeviceBluetoothMessage deviceMessage = this.handleBluetoothUnbindEventMessage(requestMap);
respMessage = ReceiveMessageUtil.getBluetoothEventMessage(deviceMessage);
} else if (eventType.equalsIgnoreCase(ReceiveMessageUtil.EVENT_TYPE_DEVICE_SUBSCRIBE)) {
logMessage = " 订阅WIFI设备";
DeviceWifiMessage deviceMessage = this.handleWifiSubscribeEventMessage(requestMap);
respMessage = ReceiveMessageUtil.getWifiEventMessage(deviceMessage);
} else if (eventType.equalsIgnoreCase(ReceiveMessageUtil.EVENT_TYPE_DEVICE_UNSUBSCRIBE)) {
logMessage = " 退订WIFI设备";
DeviceWifiMessage deviceMessage = this.handleWifiUnsubscribeEventMessage(requestMap);
respMessage = ReceiveMessageUtil.getWifiEventMessage(deviceMessage);
}*/
if ("true".equalsIgnoreCase(DEBUG)) {
log.debug(toUserName + logMessage);
}
return respMessage;
}
/* public abstract DeviceBluetoothMessage handleBluetoothUnbindEventMessage(Map<String, String> requestMap);
public abstract DeviceBluetoothMessage handleBluetoothBindEventMessage(Map<String, String> requestMap);
public abstract DeviceWifiMessage handleWifiSubscribeEventMessage(Map<String, String> requestMap);
public abstract DeviceWifiMessage handleWifiUnsubscribeEventMessage(Map<String, String> requestMap);*/
/**
* 根据指令返回信息
* 注意:这个方法需要到时测试,现在还不知道有什么作用
* @param requestMap
* @param articleList
* @return
*/
public String getDeviceMessageResult(Map<String, String> requestMap){
//String fromUserName = requestMap.get("FromUserName");//发送方(微信用户)的 user name
//String toUserName = requestMap.get("ToUserName");//接收方(公众号)的 user name
//String createTime = requestMap.get("CreateTime");//消息创建时间,消息后台生成
//String msgType = requestMap.get("MsgType");//消息类型:device_text
//String deviceType = requestMap.get("DeviceType");//设备类型,目前为“公众账号原始 ID”
//String deviceID = requestMap.get("DeviceID");//设备 ID,第三方提供
//String content = requestMap.get("Content");//消息内容,BASE64 编码
//String sessionID = requestMap.get("SessionID");//微信客户端生成的 sessionid,用于 request 和response 对应,因此响应中该字段第三方需要原封不变的带回
//String msgID = requestMap.get("MsgID");//消息 id,微信后台生成
//String openID = requestMap.get("OpenID");//微信用户账号的 OpenID
// DeviceMessage deviceMessage = this.handleDeviceTextMessage(requestMap);
//
// String respMessage = ReceiveMessageUtil.getDeviceMessage(deviceMessage);
//
// if ("true".equals(DEBUG)) {
// log.info("func[getMessageResult] respMessage[{}] ",respMessage);
// }
//
// return respMessage;
return null;
}
//public abstract DeviceMessage handleDeviceTextMessage(Map<String, String> requestMap);
public abstract String replyTextMessage(String fromUserName, String toUserName, String instructions);
}
| [
"[email protected]"
]
| |
55181e03da0d47b8068b0aeda0332c8a4ad5a801 | eebdda52ce1a0924284dca99aaff75558f6e65d3 | /willow-endoor/src/main/java/com/willow/door/admin/filecatalog/dao/FileCatalogDao.java | e7c53ea6cd9e73e632aeda52011891e6c0dde0c9 | []
| no_license | zhuxj/willow_mvn | 5fb3c845ebfcf819f247719b483953c4c3e0810d | 9e8bfbbfd6b86612381be64cee86f704edf53bde | refs/heads/master | 2020-06-12T12:52:46.224223 | 2015-09-07T08:10:33 | 2015-09-07T08:10:33 | 41,652,947 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 628 | java | /**
* 版权声明:贤俊工作室 版权所有 违者必究
* 日 期:2013-01-11
*/
package com.willow.door.admin.filecatalog.dao;
import com.willow.platform.core.base.dao.BaseDao;
import com.willow.door.admin.filecatalog.domain.FileCatalog;
import com.willow.door.admin.filecatalog.mapper.FileCatalogMapper;
import org.springframework.stereotype.Repository;
/**
* <pre>
* 订单信息持久层
* </pre>
*
* @author 朱贤俊
* @version 1.0
*/
@Repository
public class FileCatalogDao extends BaseDao<FileCatalog> {
@Override
public Class getMapperClass() {
return FileCatalogMapper.class;
}
}
| [
"zhuxianjun1985"
]
| zhuxianjun1985 |
2a5fea6deaaa744812e6a9b59fb663ed946087b9 | c5d988ae16a5485dc22d874ce3e5edc9595dcd35 | /domain/src/main/java/com/customer/domain/interactor/SendOtpUseCase.java | e8d80c7d4ae0aa95b3f34517dc6b2623528fb6fb | []
| no_license | suryakishore/ecom_customer | 4fcaa7ba32611a4fa40b858deed7fe89ba6316ac | d4663eab1381f83dd17c380bf756a7f5b973dad5 | refs/heads/master | 2022-12-12T04:34:31.587675 | 2020-08-31T08:50:32 | 2020-08-31T08:50:32 | 291,661,347 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,080 | java | package com.customer.domain.interactor;
import com.customer.domain.executor.PostExecutionThread;
import com.customer.domain.executor.ThreadExecutor;
import com.customer.domain.model.ForgotPasswordData;
import com.customer.domain.repository.SendOtpRepository;
import io.reactivex.Single;
import javax.inject.Inject;
public class SendOtpUseCase extends
UseCase<SendOtpUseCase.RequestValues, SendOtpUseCase.ResponseValues> {
private SendOtpRepository mRepository;
@Inject
public SendOtpUseCase(ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread,
SendOtpRepository repository) {
super(threadExecutor, postExecutionThread);
this.mRepository = repository;
}
@Override
protected Single<SendOtpUseCase.ResponseValues> buildUseCaseObservable(
RequestValues requestValues) {
return mRepository.sendOTP(requestValues.mMobile, requestValues.mCountryCode,
requestValues.mEmail, requestValues.mVerifyType, requestValues.mTriggeredBy,
requestValues.mUserName, requestValues.mType
);
}
public static class RequestValues implements UseCase.RequestValues {
private String mMobile;
private String mCountryCode;
private String mEmail;
private int mVerifyType;
private String mTriggeredBy;
private String mUserName;
private int mType;
public RequestValues(String mobile, String countryCode, String email, int verifyType,
String triggeredBy, String userName, int type) {
this.mMobile = mobile;
this.mCountryCode = countryCode;
this.mEmail = email;
this.mVerifyType = verifyType;
this.mTriggeredBy = triggeredBy;
this.mUserName = userName;
this.mType = type;
}
}
public static class ResponseValues implements UseCase.ResponseValue {
private ForgotPasswordData mData;
public ResponseValues(ForgotPasswordData data) {
this.mData = data;
}
public ForgotPasswordData getData() {
return mData;
}
public void setData(ForgotPasswordData data) {
this.mData = data;
}
}
}
| [
"[email protected]"
]
| |
7ab26c59c886fd876689db91346afbb0046bc69a | 907c49b70521d16c6d3bf88995a1f7909070eb2e | /study-server-one/src/main/java/studyserverone/okhttp3/CreateScript.java | d4de4a4866df114e60fc1de7bacfa13736724405 | []
| no_license | zhutonglmh/spring-cloud | 5192e56ffd73d3b4231cb58232a5e8dcbb983a71 | 2e702929c33f053731005b032b3e08172a15457d | refs/heads/master | 2022-12-08T11:19:11.448420 | 2020-04-14T13:56:09 | 2020-04-14T13:56:09 | 143,993,915 | 0 | 0 | null | 2022-11-21T22:37:52 | 2018-08-08T09:49:37 | Java | UTF-8 | Java | false | false | 19,290 | java | package com.script;
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName CreateScript
* @Description: 生成odps用到的 建表和dataX脚本
* @Author honghuaao
* @Date 2019/12/11
**/
public class CreateScript {
private static String PREFIX = "boh_base_";
public static Map<String, String[]> tableName2ColumnMap = new HashMap<String,String[]>();
static {
tableName2ColumnMap.put("t_order",getColumnArray(getOrderColumn()));
//tableName2ColumnMap.put("t_order_detail",getColumnArray(getOrderDetailColumn()));
//tableName2ColumnMap.put("t_order_pay",getColumnArray(getOrderPayColumn()));
//tableName2ColumnMap.put("t_order_delproducts",getColumnArray(getOrderDelproductsColumn()));
//tableName2ColumnMap.put("t_order_itemsexsales",getColumnArray(getOrderItemsexsalesColumn()));
//tableName2ColumnMap.put("acl_store",getColumnArray(getAclStoreColumn()));
//tableName2ColumnMap.put("t_food",getColumnArray(getFoodColumn()));
//tableName2ColumnMap.put("t_order_detail",getColumnArray(ColumnSource.vDetail()));
//tableName2ColumnMap.put("t_order_pay",getColumnArray(ColumnSource.orderPayColumn()));
//tableName2ColumnMap.put("t_order_delproducts",getColumnArray(ColumnSource.returnColumn()));
//tableName2ColumnMap.put("store_operation_data",getColumnArray(ColumnSource.t()));
//tableName2ColumnMap.put("acl_tenant",getColumnArray(ColumnSource.aclTenantColumn()));
//tableName2ColumnMap.put("bas_daily_amt_estimate",getColumnArray(ColumnSource.basDaily()));
}
public static void main(String[] args) {
for(Map.Entry<String, String[]> entry:tableName2ColumnMap.entrySet()){
String tableName = entry.getKey();
String columnArray[] = entry.getValue();
String createSqlScript = getCreateSqlScript(tableName,columnArray);
System.out.println(createSqlScript);
String createDataXScript = getCreateDataXScript(tableName,columnArray);
System.out.println(createDataXScript);
}
}
/**
* split字符串 去掉空格
* 得到表的所有字段放入数组
* @param clumnStr
* @return
*/
public static String[] getColumnArray(String clumnStr){
String [] clumnArray = clumnStr.split("\n") ;
for(int i=0;i<clumnArray.length;i++){
clumnArray[i]=clumnArray[i].trim();
}
return clumnArray;
}
public static String getCreateSqlScript(String tableName,String[] clumnArray){
StringBuilder sb = new StringBuilder();
for(int i=0;i<clumnArray.length;i++){
sb.append(" `").append(clumnArray[i]).append("` string");
if(i<clumnArray.length-1){
//sb.append(",\n");
sb.append(",");
}
}
String clumnStr = sb.toString();
String createSqlScript = templateCreateSql.replace("&targetTableName",PREFIX+tableName);
createSqlScript = createSqlScript.replace("&clumn",clumnStr);
return createSqlScript;
}
public static String getCreateDataXScript(String tableName,String[] clumnArray){
StringBuilder sb = new StringBuilder();
for(int i=0;i<clumnArray.length;i++){
sb.append(" \"").append(clumnArray[i]).append("\" ");
if(i<clumnArray.length-1){
sb.append(",\n");
}
}
String clumnStr = sb.toString();
String createDataXScript = templateDataX.replace("&sourceTableName",tableName);
createDataXScript = createDataXScript.replace("&targetTableName",PREFIX+tableName);
createDataXScript = createDataXScript.replace("&clumn",clumnStr);
return createDataXScript;
}
public static String getFoodColumn(){
String temp = "id\n" +
"dishCode\n" +
"dishName\n" +
"phoneticCode\n" +
"sortId\n" +
"sellPrice\n" +
"tenantId\n" +
"dishImg\n" +
"dishSort\n" +
"membPrice\n" +
"updateTime\n" +
"theoMargin\n" +
"dishHeat\n" +
"unitName\n" +
"assistUnitName\n" +
"status\n" +
"dishIngredients\n" +
"outBizId\n" +
"source\n" +
"ruleIds\n" +
"cookeryIds\n" +
"createTime\n" +
"box_price\n" +
"prices\n" +
"discateid\n" +
"cookery_info\n" +
"is_show\n" +
"is_take\n" +
"is_book\n" +
"is_featured\n" +
"is_gum\n" +
"is_new\n" +
"is_spicy\n" +
"description\n" +
"image_md5\n" +
"cost\n" +
"max_count\n" +
"sale_count_times\n" +
"is_visrec2\n" +
"visrec2_price\n" +
"max_order_number";
return temp;
}
public static String getAclStoreColumn(){
String temp = "id\n" +
"tenant_id\n" +
"code\n" +
"name\n" +
"parent_id\n" +
"is_leaf\n" +
"country\n" +
"province\n" +
"province_name\n" +
"city\n" +
"city_name\n" +
"district\n" +
"address\n" +
"status\n" +
"contact_man\n" +
"contact_teln\n" +
"create_user\n" +
"create_time\n" +
"update_user\n" +
"update_time\n" +
"delete_flag\n" +
"boh_code\n" +
"shopid\n" +
"pid\n" +
"org_type\n" +
"source\n" +
"source_id\n" +
"parent_source_id\n" +
"store_desc\n" +
"brand_name\n" +
"business_type\n" +
"area\n" +
"area_name\n" +
"email\n" +
"post_num\n" +
"park_info\n" +
"store_short_name\n" +
"third_code\n" +
"store_type_name\n" +
"store_mgr\n" +
"governor\n" +
"street\n" +
"stime\n" +
"etime\n" +
"open_time\n" +
"close_time\n" +
"breakfast_status\n" +
"breakfast_stime\n" +
"breakfast_etime\n" +
"breakfast_weekday_stime\n" +
"breakfast_weekday_etime\n" +
"breakfast_cncode\n" +
"lunch_status\n" +
"lunch_stime\n" +
"lunch_etime\n" +
"lunch_weekday_stime\n" +
"lunch_weekday_etime\n" +
"lunch_cncode\n" +
"dinner_status\n" +
"dinner_stime\n" +
"dinner_etime\n" +
"dinner_weekday_stime\n" +
"dinner_weekday_etime\n" +
"dinner_cncode\n" +
"morning_tea_status\n" +
"morning_tea_stime\n" +
"morning_tea_etime\n" +
"morning_tea_weekday_stime\n" +
"morning_tea_weekday_etime\n" +
"morning_tea_cncode\n" +
"afternoon_tea_status\n" +
"afternoon_tea_stime\n" +
"afternoon_tea_etime\n" +
"afternoon_tea_weekday_stime\n" +
"afternoon_tea_weekday_etime\n" +
"afternoon_tea_cncode\n" +
"night_status\n" +
"night_stime\n" +
"night_etime\n" +
"night_weekday_stime\n" +
"night_weekday_etime\n" +
"night_cncode\n" +
"spaces\n" +
"install_time\n" +
"lobby_size\n" +
"kitchen_size\n" +
"table_count\n" +
"front_num\n" +
"kitchen_num\n" +
"style\n" +
"position\n" +
"is_storearea_pubitem\n" +
"paytaxtyp\n" +
"taxrate\n" +
"brand_tag_id";
return temp;
}
public static String getOrderItemsexsalesColumn(){
String temp ="id\n" +
"tenant_id\n" +
"vscode\n" +
"dworkdate\n" +
"vbcode\n" +
"vorclass\n" +
"vposid\n" +
"vpcode\n" +
"istate\n" +
"nfcount\n" +
"nfmoney\n" +
"nfymoney\n" +
"nfzmoney\n" +
"nservicefee\n" +
"nyservicefee\n" +
"nzservicefee\n" +
"vfcode\n" +
"vfname\n" +
"visproduct\n" +
"vitemid\n" +
"istc\n" +
"create_time";
return temp;
}
public static String getOrderDelproductsColumn(){
String temp = "ID_NO\n" +
"id\n" +
"vgroupcode\n" +
"dworkdate\n" +
"vbcode\n" +
"vscode\n" +
"icount\n" +
"vpcode\n" +
"vpname\n" +
"nprice\n" +
"vdataged\n" +
"verrorname\n" +
"npriceeatin\n" +
"verrorstring\n" +
"vdeletetype\n" +
"vunit\n" +
"measdoc\n" +
"pubitem\n" +
"practice\n" +
"vorclass\n" +
"createtime\n" +
"grptypcode\n" +
"grptypname\n" +
"grpcode\n" +
"grpname\n" +
"vtypcode\n" +
"vtypname";
return temp;
}
public static String getOrderPayColumn(){
String temp = "oid\n" +
"id\n" +
"vgroupcode\n" +
"dworkdate\n" +
"vbcode\n" +
"vscode\n" +
"vypayflag\n" +
"voperate\n" +
"vpaymentdes\n" +
"vactcode\n" +
"acttypcode\n" +
"acttypname\n" +
"acttypmincode\n" +
"acttypminname\n" +
"vtypcode\n" +
"vtypname\n" +
"isno\n" +
"VORDERS\n" +
"vecode\n" +
"tctime\n" +
"igroupid\n" +
"isshow\n" +
"nrefundamt\n" +
"npayamt\n" +
"nmoney\n" +
"noveramt\n" +
"nserviceamt\n" +
"vorclass\n" +
"createtime\n" +
"vhungacountno\n" +
"vhungacountname";
return temp;
}
public static String getOrderDetailColumn(){
String temp="oid\n" +
"id\n" +
"vgroupcode\n" +
"dworkdate\n" +
"vbcode\n" +
"vscode\n" +
"ordertype\n" +
"nrestprice\n" +
"npackcnt\n" +
"nzmoney\n" +
"ndiscount\n" +
"nrefund\n" +
"nprice\n" +
"ncount\n" +
"nfamt\n" +
"namt\n" +
"njamt\n" +
"nymamt\n" +
"npricestd\n" +
"ntax\n" +
"nymoney\n" +
"nsvcchg\n" +
"nservicefee\n" +
"nroomamt\n" +
"npackdisc\n" +
"nactymamt\n" +
"nbzeroamt\n" +
"vrecode\n" +
"vpkgtag\n" +
"vpackcode\n" +
"vpackno\n" +
"vpackname\n" +
"packagetypecode\n" +
"packagetypename\n" +
"vvoidrsn\n" +
"vvoidrsndes\n" +
"vdataged\n" +
"vquick\n" +
"vspecialprice\n" +
"vhighprice\n" +
"vdese\n" +
"grptypcode\n" +
"grptypname\n" +
"grpcode\n" +
"grpname\n" +
"deptcode\n" +
"deptname\n" +
"vpcode\n" +
"vpname\n" +
"vunit\n" +
"measdoc\n" +
"pubitem\n" +
"practice\n" +
"vistemp\n" +
"vorclass\n" +
"nzsmoney\n" +
"nzcount\n" +
"vgiveaccredit\n" +
"vzsreason\n" +
"vtypcode\n" +
"vtypname\n" +
"createtime\n" +
"pubpackattr\n" +
"vitemid";
return temp;
}
public static String getOrderColumn() {
String temp = "oid\n" +
"id\n" +
"vgroupcode\n" +
"dworkdate\n" +
"vbcode\n" +
"vscode\n" +
"pk_store\n" +
"vsname\n" +
"tstime\n" +
"brandcode\n" +
"brandname\n" +
"marketcode\n" +
"marketname\n" +
"bohcode\n" +
"bohname\n" +
"governorcode\n" +
"governorname\n" +
"sftcode\n" +
"sftname\n" +
"ilclass\n" +
"ilclassname\n" +
"vorclass\n" +
"dbrtime\n" +
"dertime\n" +
"VTABLENUM\n" +
"vtbldes\n" +
"sitetypecode\n" +
"sitetypename\n" +
"varea\n" +
"iclasses\n" +
"vmemo\n" +
"vsetupby\n" +
"dbtabletime\n" +
"vlastemp\n" +
"detabletime\n" +
"verrorstring\n" +
"vresvtype\n" +
"vresvtypename\n" +
"vinputname\n" +
"icclass\n" +
"source\n" +
"voldorderid\n" +
"vorderid\n" +
"weeks\n" +
"isholidy\n" +
"itblcnt\n" +
"maxpeople\n" +
"ipeolenum\n" +
"tc\n" +
"namt\n" +
"nfamt\n" +
"nzamt\n" +
"nactymamt\n" +
"nbzero\n" +
"nroomamt\n" +
"nsvcchg\n" +
"nsvcitem\n" +
"ntaxitem\n" +
"ncomp\n" +
"ntmptsfr\n" +
"ninvoicemoney\n" +
"nmoney\n" +
"nymoney\n" +
"nactrefundamt\n" +
"nzmoney\n" +
"ndiscitem\n" +
"nrefund\n" +
"vposid\n" +
"vjecode\n" +
"vjename\n" +
"createtime\n" +
"outtradeno\n" +
"ityp\n" +
"cloud_serialnum\n" +
"verrorname\n" +
"icclassname\n" +
"VTOADDRESS\n" +
"dtoreceivetime\n" +
"dtodeliverytime\n" +
"dtorequiretime\n" +
"VTOCUSTOMERNAME\n" +
"vtocustomertel\n" +
"vopenid\n" +
"cardno\n" +
"vcardid\n" +
"alipayid\n" +
"vpassengertypecode\n" +
"vpassengertypename\n" +
"newservicefee\n" +
"boxfee\n" +
"teefee\n" +
"bottolefee";
return temp;
}
/** 生成建表语句的模板*/
public static String templateCreateSql = "create table IF NOT EXISTS &targetTableName\n" +
"(\n" +
"&clumn\n" +
")\n" +
"PARTITIONED BY (ds string)\n" +
"LIFECYCLE 7;";
/** 生成导数据的脚本模板*/
public static String templateDataX = "{\n" +
" \"type\": \"job\",\n" +
" \"steps\": [\n" +
" {\n" +
" \"stepType\": \"mysql\",\n" +
" \"parameter\": {\n" +
" \"column\": [\n" +
"&clumn\n" +
" ],\n" +
" \"connection\": [\n" +
" {\n" +
" \"datasource\": \"choiceaccount_213\",\n" +
" \"table\": [\n" +
" \"&sourceTableName\"\n" +
" ]\n" +
" }\n" +
" ],\n" +
" \"where\": \"\",\n" +
" \"splitPk\": \"id\",\n" +
" \"encoding\": \"UTF-8\"\n" +
" },\n" +
" \"name\": \"Reader\",\n" +
" \"category\": \"reader\"\n" +
" },\n" +
" {\n" +
" \"stepType\": \"odps\",\n" +
" \"parameter\": {\n" +
" \"partition\": \"ds=${bizdate}\",\n" +
" \"truncate\": false,\n" +
" \"datasource\": \"odps_first\",\n" +
" \"column\": [\n" +
"&clumn\n" +
" ],\n" +
" \"emptyAsNull\": false,\n" +
" \"table\": \"&targetTableName\"\n" +
" },\n" +
" \"name\": \"Writer\",\n" +
" \"category\": \"writer\"\n" +
" }\n" +
" ],\n" +
" \"version\": \"2.0\",\n" +
" \"order\": {\n" +
" \"hops\": [\n" +
" {\n" +
" \"from\": \"Reader\",\n" +
" \"to\": \"Writer\"\n" +
" }\n" +
" ]\n" +
" },\n" +
" \"setting\": {\n" +
" \"errorLimit\": {\n" +
" \"record\": \"\"\n" +
" },\n" +
" \"speed\": {\n" +
" \"throttle\": true,\n" +
" \"concurrent\": 2,\n" +
" \"mbps\": \"20\"\n" +
" }\n" +
" }\n" +
"}";
}
| [
"[email protected]"
]
| |
d35a676e31fc14c0b5f4c73b7d86bd31dcc4c595 | c9796d96a4b3d21532e301b230962c4136a88487 | /src/main/java/com/inxedu/os/edu/entity/user/UserLoginLog.java | 97dd721d51a2346c36a0e65db319d26f96246d96 | []
| no_license | wangyupu222/edu_java | 88b0ee9c86ddae705c8e322fc6e53b107e8d4278 | 04405e166e45f143dbf43c76abf8d42b24f05bf2 | refs/heads/master | 2022-12-21T14:54:47.019863 | 2019-07-29T07:05:42 | 2019-07-29T07:05:42 | 186,603,991 | 2 | 0 | null | 2022-12-16T01:41:52 | 2019-05-14T10:58:29 | JavaScript | UTF-8 | Java | false | false | 1,762 | java | package com.inxedu.os.edu.entity.user;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* 用户登录日志
* @author www.inxedu.com
*/
@Data
public class UserLoginLog implements Serializable{
private static final long serialVersionUID = 1L;
private int logId;//ID
private Date loginTime;//登录时间
private String ip;//登录IP
/**
* @return the logId
*/
public int getLogId() {
return logId;
}
/**
* @param logId the logId to set
*/
public void setLogId(int logId) {
this.logId = logId;
}
/**
* @return the loginTime
*/
public Date getLoginTime() {
return loginTime;
}
/**
* @param loginTime the loginTime to set
*/
public void setLoginTime(Date loginTime) {
this.loginTime = loginTime;
}
/**
* @return the ip
*/
public String getIp() {
return ip;
}
/**
* @param ip the ip to set
*/
public void setIp(String ip) {
this.ip = ip;
}
/**
* @return the userId
*/
public int getUserId() {
return userId;
}
/**
* @param userId the userId to set
*/
public void setUserId(int userId) {
this.userId = userId;
}
/**
* @return the osName
*/
public String getOsName() {
return osName;
}
/**
* @param osName the osName to set
*/
public void setOsName(String osName) {
this.osName = osName;
}
/**
* @return the userAgent
*/
public String getUserAgent() {
return userAgent;
}
/**
* @param userAgent the userAgent to set
*/
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
/**
* @return the serialversionuid
*/
public static long getSerialversionuid() {
return serialVersionUID;
}
private int userId;//用户ID
private String osName;//操作系统
private String userAgent;//浏览器
}
| [
"[email protected]"
]
| |
4df8d7b7a08330eb43570c3036ba6e5fa3aa9a3a | 71fd6e8e78aaae86b4589c2bef42f4730c1f0020 | /src/demo13/Hello.java | e3dabd0f8afc3da04f8881d831196a3d5a7b4129 | [
"Apache-2.0"
]
| permissive | qsLI/java-profiling-presentation | 143689b5cc233763741cfdc76cbb1461ae687f16 | 9e5d6dc8fe0731e0addf4e3ffa2081afab1ce5a8 | refs/heads/master | 2023-03-16T18:51:58.294254 | 2020-11-24T01:35:00 | 2020-11-24T01:35:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 532 | java | package demo13;
/**
* How many objects are created when running "Hello World" application?
* Where are these objects are created?
*
* async-profiler can trace every single created object -
* just run allocation profiling with G1 GC and TLAB disabled:
* `java -XX:+UseG1GC -XX:-UseTLAB -agentlib:asyncProfiler=start,event=alloc,file=alloc.html`
*
* Add `cstack=fp` option to include native stack traces.
*/
public class Hello {
public static void main(String[] args) {
System.out.println("It works!");
}
}
| [
"[email protected]"
]
| |
c7fc86c5906db2cb0a0a8def44519014532849ef | 3d7c9d285ed12310b5b70a98249e93380582f31b | /employeeweb/src/main/java/com/jlr/employeeweb/dao/EmployeeDao.java | c815626c803e4ec9a66d9f9cc29016c6761c2518 | []
| no_license | raviasthana/employeeweb | c7ec08e36cff2016686867fb33f632e78684ae20 | 6872fb5164c329c3e86b2570d4c0e6da0c0f37c0 | refs/heads/master | 2021-01-10T05:00:44.703701 | 2015-12-24T13:21:40 | 2015-12-24T13:21:40 | 45,036,747 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 382 | java | package com.jlr.employeeweb.dao;
import java.util.List;
import com.jlr.employeeweb.entity.Employee;
import com.jlr.employeeweb.entity.EmployeeId;
public interface EmployeeDao extends GenericDao<Employee, EmployeeId> {
Employee getEmployee(long employeeId);
List<Employee> getAllEmployees();
List<Employee> getEmployeesPaginated(int pageNumber, int pageSize);
}
| [
"[email protected]"
]
| |
c1e8bf26d2601e196155fbe992d45a1a8eee6a90 | 352e99e8b0c132ec8ea6d9702e9a658e6907ea0e | /MagicalCoder/windows64bit/project/youyamvc/youyamvc-service/src/main/java/com/magicalcoder/youyamvc/app/classes/service/impl/ClassesServiceImpl.java | f732f9c0d469015a7cbc064d9af9f1c91c942cf0 | []
| no_license | tonggc1668/MagicalCoder-smart | 6a2618124a3b046d37592403a9a869a32e08a1eb | 9f7a7ce95fa18f8e7d01d185df25ecfa398d2a4d | refs/heads/master | 2020-04-14T12:10:41.795541 | 2019-01-02T11:36:09 | 2019-01-02T11:36:09 | 163,776,265 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,282 | java |
package com.magicalcoder.youyamvc.app.classes.service.impl;
import com.magicalcoder.youyamvc.app.classes.dao.ClassesDao;
import com.magicalcoder.youyamvc.app.classes.service.ClassesService;
import com.magicalcoder.youyamvc.app.model.Classes;
import com.magicalcoder.youyamvc.core.common.utils.ListUtils;
import com.magicalcoder.youyamvc.core.common.utils.ProjectUtil;
import com.magicalcoder.youyamvc.core.common.utils.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.magicalcoder.youyamvc.core.common.utils.copy.CopyerSpringUtil;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
/**
* Created by www.magicalcoder.com
* 如果你改变了此类 read 请将此行删除
* [email protected]
*/
@Component("classesService")
public class ClassesServiceImpl implements ClassesService{
@Resource(name="classesDao")
private ClassesDao classesDao;
@Override
public Classes getClasses(Long id) {
Map<String,Object> query = new HashMap<String,Object>();
query.put("id", id);
return classesDao.getClasses(query);
}
@Override
public Classes selectOneClassesWillThrowException(Map<String, Object> query){
return classesDao.getClasses(query);
}
@Override
public List<Classes> getClassesList(Map<String, Object> query) {
return classesDao.getClassesList(query);
}
@Override
public Integer getClassesListCount(Map<String, Object> query) {
return classesDao.getClassesListCount(query);
}
@Override
public Long insertClasses(Classes entity) {
return classesDao.insertClasses(entity);
}
@Override
public void updateClasses(Classes entity) {
//校验
classesDao.updateClasses(entity);
}
@Override
public void updateClassesWithoutNull(Classes entity) {
//校验
classesDao.updateClassesWithoutNull(entity);
}
@Override
public void updateClassesByWhereSql(Map<String,Object> entity,String whereSql) {
if(entity==null ||entity.isEmpty()){
throw new RuntimeException("entity不能为空");
}
if(StringUtils.isBlank(whereSql)){
throw new RuntimeException("whereSql不能为空");
}
entity.put("whereSql",whereSql);
//校验
classesDao.updateClassesByWhereSql(entity);
}
@Override
public void deleteClasses(Long id) {
Map<String,Object> query = new HashMap<String,Object>();
query.put("id", id);
classesDao.deleteClasses(query);
}
@Override
public void deleteClassesList(Map<String,Object> entity){
classesDao.deleteClassesList(entity);
}
@Override
public void deleteClassesByWhereSql(String whereSql) {
if(StringUtils.isBlank(whereSql)){
throw new RuntimeException("whereSql不能为空");
}
Map<String,Object> query = new HashMap<String,Object>();
query.put("whereSql", whereSql);
classesDao.deleteClassesByWhereSql(query);
}
@Override
public List<Classes> getClassesOneToOneRelateList(Map<String, Object> query){
return classesDao.getClassesOneToOneRelateList(query);
}
@Override
public Integer getClassesOneToOneRelateListCount(Map<String, Object> query){
return classesDao.getClassesOneToOneRelateListCount(query);
}
@Override
public void truncateClasses() {
classesDao.truncateClasses();
}
@Override
public void batchInsertClasses(List<Classes> list) {
//校验
classesDao.batchInsertClasses(list);
}
@Override
public void batchUpdateClasses(List<Classes> list) {
//校验
classesDao.batchUpdateClasses(list);
}
@Override
public void batchDeleteClasses(List<Long> idList) {
classesDao.batchDeleteClasses(idList);
}
@Override
public void batchDeleteClassesList(List<Classes> entityList){
classesDao.batchDeleteClassesList(entityList);
}
@Transactional
@Override
public void transactionImportJsonList(List<Classes> list) {
if(list!=null && list.size()>0){
for(Classes classes : list){
if (classes.getId() == null) {
insertClasses(classes);
} else {
Classes entity = getClasses(classes.getId());
if(entity==null){
insertClasses(classes);
}else {
CopyerSpringUtil.copyProperties(classes, entity);
updateClasses(entity);
}
}
}
}
}
public List<Classes> tryQueryList(String keyword,String selectValue, String foreignJavaField){
List<Classes> list;
if(StringUtils.isBlank(keyword) || "全部".equals(keyword)){
return getClassesList(ProjectUtil.buildMap("limitIndex",0,"limit", 20));
}else{
list = searchList("classNameFirst",keyword);
if(ListUtils.isNotBlank(list)){
return list;
}
if(ProjectUtil.isNum(keyword)){
list = searchList("studentCountFirst",keyword);
if(ListUtils.isNotBlank(list)){
return list;
}
}
if(ProjectUtil.isNum(keyword)){
list = searchList("schoolIdFirst",keyword);
if(ListUtils.isNotBlank(list)){
return list;
}
}
}
return new ArrayList<Classes>();
}
private List<Classes> searchList(String field,String keyword){
List<Classes> list = getClassesList(ProjectUtil.buildMap(field,keyword,"limitIndex",0,"limit", 20));
if(ListUtils.isNotBlank(list)){
return list;
}
String[] keys = keyword.split("-");
for(String key:keys){
list = getClassesList(ProjectUtil.buildMap(field,key,"limitIndex",0,"limit", 20));
if(ListUtils.isNotBlank(list)){
return list;
}
}
return null;
}
}
| [
"[email protected]"
]
| |
d312109f37c062dd290421b41258c8985d828651 | c94f888541c0c430331110818ed7f3d6b27b788a | /mycharity/java/src/main/java/com/antgroup/antchain/openapi/mycharity/models/BatchcreateAlipaysignResponse.java | 1ee5e9286674109de3b68634df9256f07d23c769 | [
"MIT",
"Apache-2.0"
]
| permissive | alipay/antchain-openapi-prod-sdk | 48534eb78878bd708a0c05f2fe280ba9c41d09ad | 5269b1f55f1fc19cf0584dc3ceea821d3f8f8632 | refs/heads/master | 2023-09-03T07:12:04.166131 | 2023-09-01T08:56:15 | 2023-09-01T08:56:15 | 275,521,177 | 9 | 10 | MIT | 2021-03-25T02:35:20 | 2020-06-28T06:22:14 | PHP | UTF-8 | Java | false | false | 1,383 | java | // This file is auto-generated, don't edit it. Thanks.
package com.antgroup.antchain.openapi.mycharity.models;
import com.aliyun.tea.*;
public class BatchcreateAlipaysignResponse extends TeaModel {
// 请求唯一ID,用于链路跟踪和问题排查
@NameInMap("req_msg_id")
public String reqMsgId;
// 结果码,一般OK表示调用成功
@NameInMap("result_code")
public String resultCode;
// 异常信息的文本描述
@NameInMap("result_msg")
public String resultMsg;
public static BatchcreateAlipaysignResponse build(java.util.Map<String, ?> map) throws Exception {
BatchcreateAlipaysignResponse self = new BatchcreateAlipaysignResponse();
return TeaModel.build(map, self);
}
public BatchcreateAlipaysignResponse setReqMsgId(String reqMsgId) {
this.reqMsgId = reqMsgId;
return this;
}
public String getReqMsgId() {
return this.reqMsgId;
}
public BatchcreateAlipaysignResponse setResultCode(String resultCode) {
this.resultCode = resultCode;
return this;
}
public String getResultCode() {
return this.resultCode;
}
public BatchcreateAlipaysignResponse setResultMsg(String resultMsg) {
this.resultMsg = resultMsg;
return this;
}
public String getResultMsg() {
return this.resultMsg;
}
}
| [
"[email protected]"
]
| |
135acd6f25305b981e88f54542576ab95d813ef0 | 4a43f4be8d0efb74672a752ba42367c89e761916 | /geb-spock-samples/src/main/java/de/scrum_master/stackoverflow/q58279620/ClassUnderTest.java | 0f61c1382eb9979ec5dab502df5848cbd41fcfb1 | []
| no_license | kriegaex/GebSpockSamples | 138057141dc1f4079adb3dc1dd601af9dcd5d932 | 115f95f3d33d354165c6e9681f7c99f9daf97a92 | refs/heads/master | 2023-07-26T01:13:37.460490 | 2023-07-07T07:59:46 | 2023-07-07T10:38:33 | 83,425,424 | 0 | 0 | null | 2023-03-10T02:59:26 | 2017-02-28T11:37:41 | Groovy | UTF-8 | Java | false | false | 266 | java | package de.scrum_master.stackoverflow.q58279620;
public class ClassUnderTest {
public static Object someMethod(String n) {
return n == null ? "nothing" : "something";
}
public static Object someMethod(Integer n) {
return n == null ? -999 : 11;
}
}
| [
"[email protected]"
]
| |
0f74ce0a5f506aebcd53c110234f2eaf3ee5ffc0 | 7038e25ce514d6024146e002e9fc0c868214d9ae | /java/jobs/jobs-toolkit/jobs-toolkit-zookeeper/src/main/java/jobs/toolkit/support/zookeeper/impl/ZKSessionWatcherImpl.java | d8f0e6e399e86b29794b9adb3384c8c5662725b8 | []
| no_license | 3qwasd/jobs | d63f67ec08f9de36e32c4ab401ea0ab73b64636c | 8c21066062ecbb71d630c2f0cbebe0635547887d | refs/heads/master | 2023-01-02T11:24:43.780319 | 2019-07-22T16:49:13 | 2019-07-22T16:49:13 | 64,465,190 | 1 | 0 | null | 2022-12-16T02:53:31 | 2016-07-29T08:40:14 | Java | UTF-8 | Java | false | false | 3,364 | java | package jobs.toolkit.support.zookeeper.impl;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import jobs.toolkit.support.zookeeper.ZKSessionWatcher;
import jobs.toolkit.support.zookeeper.fun.EventFun;
import jobs.toolkit.support.zookeeper.holder.ZKSessionEventFunHolder;
abstract class ZKSessionWatcherImpl<T> extends ZKHelperImpl<T> implements ZKSessionWatcher<T> {
ThreadLocal<ZKSessionEventFunHolder> sessionEventFunHolder = new ThreadLocal<ZKSessionEventFunHolder>();
@SuppressWarnings("unchecked")
@Override
public T errorEventFun(EventFun fun) {
// TODO Auto-generated method stub
this.sessionEventFunHolder.get().setErrorEventFun(fun);
return (T) this;
}
@SuppressWarnings("unchecked")
@Override
public T authFailedFun(EventFun fun) {
// TODO Auto-generated method stub
this.sessionEventFunHolder.get().setAuthFailedFun(fun);
return (T) this;
}
@SuppressWarnings("unchecked")
@Override
public T disconnedFun(EventFun fun) {
// TODO Auto-generated method stub
this.sessionEventFunHolder.get().setDisconnedFun(fun);
return (T) this;
}
@SuppressWarnings("unchecked")
@Override
public T expiredFun(EventFun fun) {
// TODO Auto-generated method stub
this.sessionEventFunHolder.get().setExpiredFun(fun);
return (T) this;
}
@SuppressWarnings("unchecked")
@Override
public T saslAuthedFun(EventFun fun) {
// TODO Auto-generated method stub
this.sessionEventFunHolder.get().setSaslAuthedFun(fun);
return (T) this;
}
@SuppressWarnings("unchecked")
@Override
public T syncConnedFun(EventFun fun) {
// TODO Auto-generated method stub
this.sessionEventFunHolder.get().setSyncConnedFun(fun);
return (T) this;
}
@SuppressWarnings("unchecked")
@Override
T resetFunHolder() {
ZKSessionEventFunHolder efh = this.sessionEventFunHolder.get();
if(efh == null){
efh = new ZKSessionEventFunHolder();
this.sessionEventFunHolder.set(efh);
}else{
efh.reset();
}
return (T) this;
}
protected Watcher createWatcher(){
final EventFun errorEventFun = this.sessionEventFunHolder.get().getErrorEventFun();
final EventFun authFailedFun = this.sessionEventFunHolder.get().getAuthFailedFun();
final EventFun disconnedFun = this.sessionEventFunHolder.get().getDisconnedFun();
final EventFun expiredFun = this.sessionEventFunHolder.get().getExpiredFun();
final EventFun saslAuthedFun = this.sessionEventFunHolder.get().getSaslAuthedFun();
final EventFun syncConnedFun = this.sessionEventFunHolder.get().getSyncConnedFun();
Watcher watcher = new Watcher() {
@Override
public void process(WatchedEvent event) {
switch (event.getState()) {
case SyncConnected:
if(syncConnedFun != null) syncConnedFun.process(event);
break;
case AuthFailed:
if(authFailedFun != null) authFailedFun.process(event);
break;
case Disconnected:
if(disconnedFun != null) disconnedFun.process(event);
break;
case Expired:
if(expiredFun != null) expiredFun.process(event);
break;
case SaslAuthenticated:
if(saslAuthedFun != null) saslAuthedFun.process(event);
break;
default:
if(errorEventFun != null) errorEventFun.process(event);
break;
}
}
};
return watcher;
}
}
| [
"[email protected]"
]
| |
89f0d29202b9ed8458701bbe4aff37f6c709dc6f | 622f7dcdb94e0682531647b51b30f75351552fca | /scr_homework/test/scr/utility/ProcessaSegnaliTest.java | e30fd2a00469b25dfcd1387cdedb1e3d7c9f84aa | []
| no_license | ale-pavel/scr_hw | 2224bd0cf9319dc0a40cb2f204431fe7b9a2a720 | da1411fe894b1f7c2ddac75d70fa8808ab8e5209 | refs/heads/master | 2021-01-21T12:58:33.850382 | 2019-09-18T22:02:58 | 2019-09-18T22:02:58 | 91,804,682 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,193 | java | package scr.utility;
import static org.junit.Assert.*;
import java.util.Random;
import org.junit.Test;
import scr.object.*;
public class ProcessaSegnaliTest {
@Test
public void test() {
CaricatoreSequenza cs = new CaricatoreSequenza(1000000);
Segnale s = cs.parseRighe(cs.leggiSequenza("Sequenze/seq1/output_1.dat"),"\t");
ProcessaSegnali sp = new ProcessaSegnali();
double[] reali_1000 = sp.campionaSequenza(s.getReali(), 10000);
double[] imm_1000 = sp.campionaSequenza(s.getImmaginari(), 10000);
assertEquals(10000, reali_1000.length);
Segnale s_1000 = new Segnale(reali_1000.length,reali_1000,imm_1000);
System.out.println("power_100 = " + s_1000.potenza());
System.out.println("power = " + s.potenza());
}
@Test
public void testPotenzaSequenzaRumorosa() {
int num_sequenze = 1000;
int num_campioni = 1000;
ProcessaSegnali sp = new ProcessaSegnali();
/*
Rumore[] seq1 = sp.generaSequenzeRumorose(num_sequenze, num_campioni, -13);
Rumore[] seq2 = sp.generaSequenzeRumorose(num_sequenze, num_campioni, -8);
Rumore[] seq3 = sp.generaSequenzeRumorose(num_sequenze, num_campioni, -5);
Rumore[] seq4 = sp.generaSequenzeRumorose(num_sequenze, num_campioni, 2);
//Valori arrotondati alla seconda cifra decimale calcolati con formula SNR linearizzato
System.out.println("Pn:19.95 = " + sp.potenzaMediaSequenza(seq1));
System.out.println("Pn:6.31 = " + sp.potenzaMediaSequenza(seq2));
System.out.println("Pn:3.16 = " + sp.potenzaMediaSequenza(seq3));
System.out.println("Pn:0.63 = " + sp.potenzaMediaSequenza(seq4));
*/
Rumore[] seq1 = sp.generaSequenzeRumorose(num_sequenze, num_campioni, -3);
Rumore[] seq2 = sp.generaSequenzeRumorose(num_sequenze, num_campioni, 2);
Rumore[] seq3 = sp.generaSequenzeRumorose(num_sequenze, num_campioni, -8);
Rumore[] seq4 = sp.generaSequenzeRumorose(num_sequenze, num_campioni, -13);
//Valori arrotondati alla seconda cifra decimale calcolati con formula SNR linearizzato
System.out.println("Pn:1.99 = " + sp.potenzaMediaSequenza(seq1));
System.out.println("Pn:0.63 = " + sp.potenzaMediaSequenza(seq2));
System.out.println("Pn:6.31 = " + sp.potenzaMediaSequenza(seq3));
System.out.println("Pn:19.95 = " + sp.potenzaMediaSequenza(seq4));
}
@Test
public void testVarianzaGaussianaAWGN() {
Random r = new Random();
int length = 1000;
double sigma = 0;
for(int i=0;i<length;i++) {
double casuale = r.nextGaussian();
sigma+=casuale*casuale;
}
double risultato = sigma/length;
System.out.println("Varianza:1 = " + risultato); //Circa uguale a 1, OK
}
@Test
public void testSeparaSequenzaInBlocchi() {
double[] rea = {1,2,3,4,5,6,7,8,9,10};
double[] imm = {1,2,3,4,5,6,7,8,9,10};
Segnale s = new Segnale(rea.length, rea, imm);
Segnale[] s_chunks = s.separaSegnaleInBlocchi(2);
for(int i=0;i<s_chunks.length;i++) {
for(int j=0; j<s_chunks[i].getLength();j++) {
System.out.print(s_chunks[i].getReali()[j]+" J"+s_chunks[i].getImmaginari()[j]+" | ");
}
System.out.println();
}
assertSame(2, s_chunks.length);
assertSame(5, s_chunks[0].getLength());
}
}
| [
"[email protected]"
]
| |
db18ea63079d7538f82d8c42805d336e25c70ae7 | 8e934702b9925631c8934caae11389537ee3885a | /src/main/java/kr/ispark/common/web/BaseController.java | 807a9e6f13ae2440f3d9f887c7ff56871f9c1491 | []
| no_license | junwojjang27/StrategyGate | a2a7a67c100ad0b5a9f8490c24e91d104bc47f16 | 7747ba311914762dbbab7ee979555c3320e2dd6c | refs/heads/master | 2023-09-05T12:04:14.749901 | 2021-11-17T11:58:45 | 2021-11-17T11:58:45 | 397,871,871 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,629 | java | /*************************************************************************
* CLASS 명 : BaseController
* 작 업 자 : kimyh
* 작 업 일 : 2017. 12. 11.
* 기 능 : 모든 Controller의 공통적으로 사용하는 메소드와 변수를 모아놓은 Controller
* 모든 Controller는 BaseController를 extends해서 생성해야 함
* ---------------------------- 변 경 이 력 --------------------------------
* 번호 작 업 자 작 업 일 변 경 내 용 비고
* ---- --------- ---------------- --------------------- -----------
* 1 kimyh 2017. 12. 11. 최 초 작 업
**************************************************************************/
package kr.ispark.common.web;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.NoSuchMessageException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;
import org.springmodules.validation.commons.DefaultBeanValidator;
import egovframework.com.cmm.EgovMessageSource;
import kr.ispark.common.CommonVO;
public class BaseController {
public final Logger log = LoggerFactory.getLogger(this.getClass());
@Resource(name="egovMessageSource")
public EgovMessageSource egovMessageSource;
@Autowired
public DefaultBeanValidator beanValidator;
// ajax 프로세스 처리 성공시 (common.js에도 선언 필요)
public final String AJAX_SUCCESS = "SUCCESS";
// ajax 처리 성공 메시지 코드
public final String AJAX_SUCCESS_MSG_CODE = "success.request.msg";
// ajax 프로세스 처리 실패시 (common.js에도 선언 필요)
public final String AJAX_FAIL = "FAIL";
// ajax 처리 실패 메시지 코드
public final String AJAX_FAIL_MSG_CODE = "fail.request.msg";
// IE9용 파일 업로드 콜백 페이지
public final String FILE_UPLOAD_CALLBACK_URL = "/common/fileUploadCallback.do";
// 상세 조회용 json 데이터 생성
public ModelAndView makeJsonData(CommonVO dataVO) {
HashMap<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("dataVO", dataVO);
return new ModelAndView("jsonView", resultMap);
}
// list json 데이터 생성
public ModelAndView makeJsonListData(List<? extends CommonVO> list) {
HashMap<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("list", list);
return new ModelAndView("jsonView", resultMap);
}
// jqgrid용 json 데이터 생성 (데이터 전체 조회 또는 그리드 내에서 페이징 처리할 때 사용)
public ModelAndView makeGridJsonData(List<? extends CommonVO> list) {
HashMap<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("rows", list);
resultMap.put("page", 1);
resultMap.put("total", 1);
resultMap.put("records", list.size());
return new ModelAndView("jsonView", resultMap);
}
// jqgrid용 json 데이터 생성 (페이징 쿼리 적용시 사용)
public ModelAndView makeGridJsonData(List<?> list, int listCnt, CommonVO searchVO) {
int page = searchVO.getPage();
int rows = searchVO.getRows();
HashMap<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("rows", list);
resultMap.put("page", page);
resultMap.put("total", listCnt/rows + (listCnt%rows==0?0:1));
resultMap.put("records", listCnt);
return new ModelAndView("jsonView", resultMap);
}
// ajax용 성공 응답 생성(json)
public ModelAndView makeSuccessJsonData() {
HashMap<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("result", AJAX_SUCCESS);
resultMap.put("msg", egovMessageSource.getMessage(AJAX_SUCCESS_MSG_CODE));
return makeSuccessJsonData(new HashMap<String, Object>());
}
// ajax용 성공 응답 생성(json) - 에러 msg 추가
public ModelAndView makeSuccessJsonData(String msg) {
HashMap<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("msg", msg);
return makeSuccessJsonData(resultMap);
}
// ajax용 성공 응답 생성(json)
public ModelAndView makeSuccessJsonData(HashMap<String, Object> resultMap) {
resultMap.put("result", AJAX_SUCCESS);
if(resultMap.get("msg") == null) {
resultMap.put("msg", egovMessageSource.getMessage(AJAX_SUCCESS_MSG_CODE));
}
return new ModelAndView("jsonView", resultMap);
}
// ajax용 성공 응답 생성(json) 듀얼화면 저장용(설문조사)
public ModelAndView makeSuccessJsonDataDual(String key) {
HashMap<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("key", key);
resultMap.put("result", AJAX_SUCCESS);
if(resultMap.get("msg") == null) {
resultMap.put("msg", egovMessageSource.getMessage(AJAX_SUCCESS_MSG_CODE));
}
return new ModelAndView("jsonView", resultMap);
}
// ajax용 실패 응답 생성(json)
public ModelAndView makeFailJsonData() {
return makeFailJsonData(new HashMap<String, Object>());
}
// ajax용 실패 응답 생성(json) - 에러 msg 추가
public ModelAndView makeFailJsonData(String msg) {
HashMap<String, Object> resultMap = new HashMap<String, Object>();
resultMap.put("msg", msg);
return makeFailJsonData(resultMap);
}
// ajax용 실패 응답 생성(json)
public ModelAndView makeFailJsonData(HashMap<String, Object> resultMap) {
resultMap.put("result", AJAX_FAIL);
if(resultMap.get("msg") == null) {
resultMap.put("msg", egovMessageSource.getMessage(AJAX_FAIL_MSG_CODE));
}
return new ModelAndView("jsonView", resultMap);
}
/**
* 결과값이 0 또는 -1이면 실패, 아니면 성공 json 응답 생성
* @param int resultCnt
* @return ModelAndView
*/
public ModelAndView makeJsonDataByResultCnt(int resultCnt) {
if(resultCnt == 0 || resultCnt == -1) {
return makeFailJsonData();
}
return makeSuccessJsonData();
}
/*
* 성공/실패 응답 처리
* - ajax 호출인 경우 : json으로 응답
* - form submit인 경우(IE9) : 응답 페이지로 포워딩
*/
/**
* 성공/실패 응답 처리
* - ajax 호출인 경우 : json으로 응답
* - form submit인 경우(IE9) : 응답 페이지로 포워딩
* @param boolean isSuccess : true : 성공, false : 실패
* @param MultipartHttpServletRequest multiRequest
* @param HttpServletResponse response
* @param CommonVO dataVO
* @param String msg : 메시지
* @throws Exception
*/
public void resultHandling (boolean isSuccess, MultipartHttpServletRequest multiRequest, HttpServletResponse response, CommonVO dataVO) throws Exception {
resultHandling(isSuccess, multiRequest, response, dataVO, null);
}
public void resultHandling (
boolean isSuccess, MultipartHttpServletRequest multiRequest, HttpServletResponse response,
CommonVO dataVO, String msg) throws Exception {
// ajax 호출 여부 체크.
boolean isAjaxCall = "XMLHttpRequest".equals(multiRequest.getHeader("X-Requested-With"));
String result = isSuccess ? AJAX_SUCCESS : AJAX_FAIL;
String msgCode = isSuccess ? AJAX_SUCCESS_MSG_CODE : AJAX_FAIL_MSG_CODE;
String callbackFunc = isSuccess ? dataVO.getDoneCallbackFunc() : dataVO.getFailCallbackFunc();
if(msg == null) {
msg = egovMessageSource.getMessage(msgCode);
}
if(isAjaxCall) {
String data = StringUtils.join(new String[] {
" { ",
" \"result\" : \"", result ,"\", ",
" \"msg\" : \"", msg , "\" ",
" } "
});
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.print(data);
out.flush();
out.close();
} else {
multiRequest.setAttribute("result", result);
multiRequest.setAttribute("msg", msg);
multiRequest.setAttribute("callbackFunc", callbackFunc);
multiRequest.getRequestDispatcher(FILE_UPLOAD_CALLBACK_URL).forward(multiRequest, response);
}
}
// grid, list용 validation
public void validateList(List<? extends CommonVO> gridDataList, BindingResult bindingResult) {
for(Object vo : gridDataList) {
beanValidator.validate(vo, bindingResult);
if(bindingResult.hasErrors()) {
break;
}
}
}
// list validation의 에러메시지 확인
public String getListErrorMsg(BindingResult bindingResult) {
String msg = null;
FieldError fieldError = bindingResult.getFieldError();
if(fieldError != null) {
try {
msg = egovMessageSource.getMessage(fieldError);
} catch(NoSuchMessageException e) {
msg = egovMessageSource.getMessage(AJAX_FAIL_MSG_CODE);
}
}
if(msg == null) {
msg = egovMessageSource.getMessage(AJAX_FAIL_MSG_CODE);
}
return msg;
}
// 사용자 쿠키에서 값을 가져옴
public String getCookie(HttpServletRequest request, String cookieName) {
return WebUtils.getCookie(request, cookieName) == null ? null : WebUtils.getCookie(request, cookieName).getValue();
}
/**
* jqgrid용 List to Map (페이징이 없는 경우)
* @param List<CommonVO> dataList
* @return HashMap<String, Object>
*/
public HashMap<String, Object> makeResultMapForGrid(List<?> dataList) {
HashMap<String, Object> resultMap = new HashMap<String, Object>();
int listCnt = dataList.size();
resultMap.put("rows", dataList);
resultMap.put("page", 1);
resultMap.put("total", 1);
resultMap.put("records", listCnt);
return resultMap;
}
}
| [
"[email protected]"
]
| |
a96215a29a7f020d2d839372efc59ab77f5c0f7f | c685431ab0fce369b586fd1ded28f1bff8a9a205 | /src/main/java/com/maxhyeon/ndays/repo/UserJpaRepo.java | 16eae060048e2e2ae797ceda2976c9e597e99cdb | []
| no_license | maxHyeon/ndays | f906846128718eb73ee8a4a4398d3e752811ff58 | b8cb29465199fc2c701941335bdac971e79dfd13 | refs/heads/master | 2020-11-28T17:31:32.025588 | 2020-01-09T14:56:39 | 2020-01-09T14:56:39 | 229,880,961 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 203 | java | package com.maxhyeon.ndays.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import com.maxhyeon.ndays.entity.Users;
public interface UserJpaRepo extends JpaRepository<Users,Long> {
}
| [
"[email protected]"
]
| |
fe2559c3a8dbe0c2876c301003ef6f2be3a0cd27 | 1c7c8ecdcecbe8772cbd06808b79a2561fe58d34 | /src/main/java/af/dfi/lang/exception/SubmissionException.java | 9b4d539baae55e047cd71f9aef5c58a7f3d8cbec | []
| no_license | mohbadar/mpower-prototype | 54f7c400d2519e3eefe83037cabc8df19cc8419d | 3fb8425cce110687e88cc35c8015af407bb472b8 | refs/heads/master | 2023-04-27T19:57:08.710475 | 2019-09-25T10:14:30 | 2019-09-25T10:14:30 | 206,965,069 | 2 | 0 | null | 2023-04-14T17:48:46 | 2019-09-07T12:28:15 | Java | UTF-8 | Java | false | false | 230 | java | package af.dfi.lang.exception;
public class SubmissionException extends Exception {
public SubmissionException(String msg) {
super(msg);
}
public SubmissionException(Throwable e) {
super(e);
}
}
| [
"[email protected]"
]
| |
7859c359f053373b63b72342d71d1825c2f92db4 | 7fc500624d95b378727a2edf09adad45e2142660 | /src/main/java/com/bridgelabz/datastructure/PrimeAnagram.java | ae1d885185e0938d7f3267acd2c017811cc17b51 | []
| no_license | meghajagadale99/AlgorithmAndDataStructure | 3fc80621c6a5d736a0cdc28d75c14863ecff3a8f | d907822f18c0ece897cfce5d5a3ff517fc07671a | refs/heads/main | 2023-07-15T06:40:12.131575 | 2021-08-24T06:18:16 | 2021-08-24T06:18:16 | 399,355,731 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,182 | java | package com.bridgelabz.datastructure;
import com.bridgelabz.utility.Utility;
public class PrimeAnagram {
public static void main(String[] args) {
int array[][]=new int[10][100];
int prime[][]=new int[10][100];
int temp=1;
for (int i = 0; i< 10; i++) {
for (int j = 0; j < 100; j++) {
array[i][j]=temp;
temp++;
}
}
for (int i = 0; i <10; i++) {
for (int j = 0; j < 100; j++) {
if(Utility.isPrime(array[i][j]))
{
prime[i][j]=array[i][j];
}
else
{
prime[i][j]=-1;
}
}
}
for(int i = 0 ; i<10 ; i++) {
for(int j = 0 ; j<100;j++) {
if(prime[i][j]!=-1) {
for(int k = j+1 ; k <100;k++ ) {
if(prime[i][k]!=-1&& Utility.anagram(prime[i][j],prime[i][k])) {
System.out.println(prime[i][j]+" "+ prime[i][k]);
}
}
}
}
}
}
}
| [
"[email protected]"
]
| |
5f882f196f65315d0bff87d756098306284b0eb6 | 03f4832c97910d49c79c6dd774a66ab6e460445f | /src/main/java/com/staff/config/LoginHandlerInterceptor.java | 25ab5704355f5d268d003da8f48fa77fc35965db | []
| no_license | gzsba/staff-manage | ffb943124dbb3d9b7c1fd63ba5d1a58a24935548 | aaaeb9554e08d3db18028500172e2190581918fb | refs/heads/main | 2023-01-20T07:03:03.861085 | 2020-11-26T04:17:59 | 2020-11-26T04:17:59 | 315,051,939 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 858 | java | package com.staff.config;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
//用户登录成功后,应该有自己的session
Object session = request.getSession().getAttribute( "LoginUser" );
if (session==null){
request.setAttribute( "msg","权限不够,请先登录" );
request.getRequestDispatcher( "index.html" ).forward( request,response );
return false;
}
return true;
}
}
| [
"[email protected]"
]
| |
ce1275354543b2512b9a8bd371131cdf553ebab4 | 05570e35508f2b8f8b41e39b49f3e7a02b922d30 | /src/main/omr/glyph/Evaluation.java | 0d9d77bc6f5be38af4c09781972f87116c769f87 | []
| no_license | brennn-rpi/SightReaderPro | 98b214a481c9cf893e8341f7335eb9e69812de11 | ec235c3f14c90850983e1dcaf687033bc113d221 | refs/heads/master | 2021-01-15T22:19:33.959618 | 2016-02-11T22:31:01 | 2016-02-11T22:31:01 | 51,522,243 | 0 | 0 | null | 2016-02-11T15:04:36 | 2016-02-11T15:04:35 | null | UTF-8 | Java | false | false | 4,867 | java | //----------------------------------------------------------------------------//
// //
// E v a l u a t i o n //
// //
//----------------------------------------------------------------------------//
// <editor-fold defaultstate="collapsed" desc="hdr"> //
// Copyright © Hervé Bitteur and others 2000-2013. All rights reserved. //
// This software is released under the GNU General Public License. //
// Goto http://kenai.com/projects/audiveris to report bugs or suggestions. //
//----------------------------------------------------------------------------//
// </editor-fold>
package omr.glyph;
import omr.constant.Constant;
/**
* Class {@code Evaluation} gathers a glyph shape, its grade and,
* if any, details about its failure (name of the check that failed).
*
* @author Hervé Bitteur
*/
public class Evaluation
implements Comparable<Evaluation>
{
//~ Static fields/initializers ---------------------------------------------
/** Absolute confidence in shape manually assigned by the user. */
public static final double MANUAL = 300;
/** Confidence for in structurally assigned. */
public static final double ALGORITHM = 200;
//~ Instance fields --------------------------------------------------------
/** The evaluated shape. */
public Shape shape;
/**
* The evaluation grade (larger is better), generally provided by
* the neural network evaluator in the range 0 - 100.
*/
public double grade;
/** The specific check that failed, if any. */
public Failure failure;
//~ Constructors -----------------------------------------------------------
//------------//
// Evaluation //
//------------//
/**
* Create an initialized evaluation instance.
*
* @param shape the shape this evaluation measures
* @param grade the measurement result (larger is better)
*/
public Evaluation (Shape shape,
double grade)
{
this.shape = shape;
this.grade = grade;
}
//~ Methods ----------------------------------------------------------------
//-----------//
// compareTo //
//-----------//
/**
* To sort from best to worst.
*
* @param that the other evaluation instance
* @return -1,0 or +1
*/
@Override
public int compareTo (Evaluation that)
{
if (this.grade > that.grade) {
return -1;
}
if (this.grade < that.grade) {
return +1;
}
return 0;
}
//----------//
// toString //
//----------//
@Override
public String toString ()
{
StringBuilder sb = new StringBuilder();
sb.append(shape);
sb.append("(");
if (grade == MANUAL) {
sb.append("MANUAL");
} else if (grade == ALGORITHM) {
sb.append("ALGORITHM");
} else {
sb.append((float) grade);
}
if (failure != null) {
sb.append(" failure:")
.append(failure);
}
sb.append(")");
return sb.toString();
}
//~ Inner Classes ----------------------------------------------------------
//---------//
// Failure //
//---------//
/**
* A class to handle which specific check has failed in the
* evaluation.
*/
public static class Failure
{
//~ Instance fields ----------------------------------------------------
/** The name of the test that failed. */
public final String test;
//~ Constructors -------------------------------------------------------
public Failure (String test)
{
this.test = test;
}
//~ Methods ------------------------------------------------------------
@Override
public String toString ()
{
return test;
}
}
//-------//
// Grade //
//-------//
/**
* A subclass of Constant.Double, meant to store a grade constant.
*/
public static class Grade
extends Constant.Double
{
//~ Constructors -------------------------------------------------------
/**
* Specific constructor, where unit & name are assigned later.
*
* @param defaultValue the (double) default value
* @param description the semantic of the constant
*/
public Grade (double defaultValue,
java.lang.String description)
{
super("Grade", defaultValue, description);
}
}
}
| [
"[email protected]"
]
| |
d0ad035859469d5136fa86ff4c44db9c352ecd56 | 1056b2be073781055c402b6264516cdf4843f2e5 | /app/src/main/java/model/Vehiculo.java | 6ee6381aee2c125cc0da075e1f0689ddc42fd471 | []
| no_license | ecg88g/Concesionario-VolleyREST-APP | f93d3f3265b06fb0a353b59c8d471eb7c22ac625 | 93c1b8b12e4fc0936a743d62a64e68d074192a65 | refs/heads/master | 2020-05-20T14:53:11.464171 | 2017-03-09T20:52:44 | 2017-03-09T20:52:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,289 | java | package model;
public class Vehiculo {
private String Kms;
private String Matricula;
private String IdConcesionario;
/**
* No args constructor for use in serialization
*
*
*/
public Vehiculo() {
}
/**
*
* @param Kms
* @param idConcesionario
* @param matricula
*/
public Vehiculo(String Kms, String matricula, String idConcesionario) {
super();
this.Kms = Kms;
this.Matricula = matricula;
this.IdConcesionario = idConcesionario;
}
public String getKms() {
return Kms;
}
public void setKms(String kms) {
this.Kms = kms;
}
public String getMatricula() {
return Matricula;
}
public void setMatricula(String matricula) {
this.Matricula = matricula;
}
public String getIdConcesionario() {
return IdConcesionario;
}
public void setIdConcesionario(String idConcesionario) {
this.IdConcesionario = idConcesionario;
}
@Override
public String toString() {
return "Vehiculo{" +
"Kms='" + Kms + '\'' +
", Matricula='" + Matricula + '\'' +
", IdConcesionario='" + IdConcesionario + '\'' +
'}';
}
}
| [
"[email protected]"
]
| |
b7b92617b0020632ad5705a1c8fd33ac5a70d0be | 38c4451ab626dcdc101a11b18e248d33fd8a52e0 | /identifiers/lucene-3.6.2/core/src/java/org/apache/lucene/analysis/tokenattributes/PayloadAttributeImpl.java | be1fdcf77590aa3a424339025eac5caca9a83a68 | []
| no_license | habeascorpus/habeascorpus-data | 47da7c08d0f357938c502bae030d5fb8f44f5e01 | 536d55729f3110aee058ad009bcba3e063b39450 | refs/heads/master | 2020-06-04T10:17:20.102451 | 2013-02-19T15:19:21 | 2013-02-19T15:19:21 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,171 | java | org PACKAGE_IDENTIFIER false
apache PACKAGE_IDENTIFIER false
lucene PACKAGE_IDENTIFIER false
analysis PACKAGE_IDENTIFIER false
tokenattributes PACKAGE_IDENTIFIER false
java PACKAGE_IDENTIFIER false
io PACKAGE_IDENTIFIER false
Serializable TYPE_IDENTIFIER false
org PACKAGE_IDENTIFIER false
apache PACKAGE_IDENTIFIER false
lucene PACKAGE_IDENTIFIER false
index PACKAGE_IDENTIFIER false
Payload TYPE_IDENTIFIER false
org PACKAGE_IDENTIFIER false
apache PACKAGE_IDENTIFIER false
lucene PACKAGE_IDENTIFIER false
util PACKAGE_IDENTIFIER false
AttributeImpl TYPE_IDENTIFIER false
PayloadAttributeImpl TYPE_IDENTIFIER true
AttributeImpl TYPE_IDENTIFIER false
PayloadAttribute TYPE_IDENTIFIER false
Cloneable TYPE_IDENTIFIER false
Serializable TYPE_IDENTIFIER false
Payload TYPE_IDENTIFIER false
payload VARIABLE_IDENTIFIER true
PayloadAttributeImpl METHOD_IDENTIFIER false
PayloadAttributeImpl METHOD_IDENTIFIER false
Payload TYPE_IDENTIFIER false
payload VARIABLE_IDENTIFIER true
payload VARIABLE_IDENTIFIER false
payload VARIABLE_IDENTIFIER false
Payload TYPE_IDENTIFIER false
getPayload METHOD_IDENTIFIER true
payload VARIABLE_IDENTIFIER false
setPayload METHOD_IDENTIFIER true
Payload TYPE_IDENTIFIER false
payload VARIABLE_IDENTIFIER true
payload VARIABLE_IDENTIFIER false
payload VARIABLE_IDENTIFIER false
Override TYPE_IDENTIFIER false
clear METHOD_IDENTIFIER true
payload VARIABLE_IDENTIFIER false
Override TYPE_IDENTIFIER false
Object TYPE_IDENTIFIER false
clone METHOD_IDENTIFIER true
PayloadAttributeImpl TYPE_IDENTIFIER false
clone VARIABLE_IDENTIFIER true
PayloadAttributeImpl TYPE_IDENTIFIER false
clone METHOD_IDENTIFIER false
payload VARIABLE_IDENTIFIER false
clone VARIABLE_IDENTIFIER false
payload VARIABLE_IDENTIFIER false
Payload TYPE_IDENTIFIER false
payload VARIABLE_IDENTIFIER false
clone METHOD_IDENTIFIER false
clone VARIABLE_IDENTIFIER false
Override TYPE_IDENTIFIER false
equals METHOD_IDENTIFIER true
Object TYPE_IDENTIFIER false
other VARIABLE_IDENTIFIER true
other VARIABLE_IDENTIFIER false
other VARIABLE_IDENTIFIER false
PayloadAttribute TYPE_IDENTIFIER false
PayloadAttributeImpl TYPE_IDENTIFIER false
o VARIABLE_IDENTIFIER true
PayloadAttributeImpl TYPE_IDENTIFIER false
other VARIABLE_IDENTIFIER false
o VARIABLE_IDENTIFIER false
payload VARIABLE_IDENTIFIER false
payload VARIABLE_IDENTIFIER false
o VARIABLE_IDENTIFIER false
payload VARIABLE_IDENTIFIER false
payload VARIABLE_IDENTIFIER false
o VARIABLE_IDENTIFIER false
payload VARIABLE_IDENTIFIER false
equals METHOD_IDENTIFIER false
payload VARIABLE_IDENTIFIER false
Override TYPE_IDENTIFIER false
hashCode METHOD_IDENTIFIER true
payload VARIABLE_IDENTIFIER false
payload VARIABLE_IDENTIFIER false
hashCode METHOD_IDENTIFIER false
Override TYPE_IDENTIFIER false
copyTo METHOD_IDENTIFIER true
AttributeImpl TYPE_IDENTIFIER false
target VARIABLE_IDENTIFIER true
PayloadAttribute TYPE_IDENTIFIER false
t VARIABLE_IDENTIFIER true
PayloadAttribute TYPE_IDENTIFIER false
target VARIABLE_IDENTIFIER false
t VARIABLE_IDENTIFIER false
setPayload METHOD_IDENTIFIER false
payload VARIABLE_IDENTIFIER false
Payload TYPE_IDENTIFIER false
payload VARIABLE_IDENTIFIER false
clone METHOD_IDENTIFIER false
| [
"[email protected]"
]
| |
6bcd43065d1ac182f70f2f9a755952fb76c43aaf | a284ba92b84b9a04e7c5773b27996aa6bb5fb90a | /custom-component/core/src/main/java/com/adobe/aem/guides/wknd/core/models/Byline.java | aac441101bb03db62aab641131b89493c78a38cd | [
"Apache-2.0"
]
| permissive | uithatran/aem | f571deffb5db30e2d32a74681d1e68cdf7564d21 | 332b8c4b4f5daa8b3f679c6d17a1e59579c9af25 | refs/heads/master | 2022-11-30T04:18:30.630476 | 2020-08-16T16:34:55 | 2020-08-16T16:34:55 | 287,982,803 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 547 | java | package com.adobe.aem.guides.wknd.core.models;
import java.util.List;
/**
* Represents the Byline AEM Component for the WKND Site project.
**/
public interface Byline {
/***
* @return a string to display as the name.
*/
String getName();
/***
* Occupations are to be sorted alphabetically in a descending order.
*
* @return a list of occupations.
*/
List<String> getOccupations();
/***
* @return a boolean if the component has enough content to display.
*/
boolean isEmpty();
} | [
"[email protected]"
]
| |
df22938606b957bfab6f2d961b693da58563fded | 07f16aed45c30e3542d73d46b14daa7bbb456f57 | /app/src/main/java/com/whmnrc/flymall/views/VpSwipeRefreshLayout.java | 4c5f0ce0679c07e6de67717e8540fc7c324283b2 | []
| no_license | yjyvi/flymall | 236350c129db0a51d69c43028b27526856943b96 | 40ce5477ad46e44c65f157686e2bba1c77db099d | refs/heads/master | 2020-03-19T20:25:24.170420 | 2018-07-18T00:55:29 | 2018-07-18T00:55:29 | 136,901,058 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,166 | java | package com.whmnrc.flymall.views;
import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
/**
* Created by yong hao zeng on 2018/2/9.
*/
public class VpSwipeRefreshLayout extends SwipeRefreshLayout {
private float startY;
private float startX;
// 记录viewPager是否拖拽的标记
private boolean mIsVpDragger;
private final int mTouchSlop;
public VpSwipeRefreshLayout(Context context, AttributeSet attrs) {
super(context, attrs);
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// 记录手指按下的位置
startY = ev.getY();
startX = ev.getX();
// 初始化标记
mIsVpDragger = false;
break;
case MotionEvent.ACTION_MOVE:
// 如果viewpager正在拖拽中,那么不拦截它的事件,直接return false;
if(mIsVpDragger) {
return false;
}
// 获取当前手指位置
float endY = ev.getY();
float endX = ev.getX();
float distanceX = Math.abs(endX - startX);
float distanceY = Math.abs(endY - startY);
// 如果X轴位移大于Y轴位移,那么将事件交给viewPager处理。
if(distanceX > mTouchSlop && distanceX > distanceY) {
mIsVpDragger = true;
return false;
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
// 初始化标记
mIsVpDragger = false;
break;
}
// 如果是Y轴位移大于X轴,事件交给swipeRefreshLayout处理。
return super.onInterceptTouchEvent(ev);
}
} | [
"[email protected]"
]
| |
b1a8f88b6a24ee3cee2827891a12b3c49d30a4a8 | 621e5ba535821554160463cdb0ca2b6fb3eee729 | /src/Instagram.java | 90be43bb743e4694979ce09dd30bf263e88bc90e | []
| no_license | azeersk/inheritancepolymorphism | 4c87e4abfe860106b9229fe3e088524bb6d41e38 | e44d19b357bb283e80d142a5bd1cf8d9c80df8e1 | refs/heads/master | 2023-07-21T16:57:00.880295 | 2021-09-07T06:28:54 | 2021-09-07T06:28:54 | 403,866,950 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 624 | java | public class Instagram {
public void Watch(){
System.out.println("watch reels and learning videos!");
}
public void Upload(){
System.out.println("upload photos,videos,stories and reels!");
}
}
class userA extends Instagram{
public void CreateAccount(String a,String b){
System.out.println("Enter your user name: "+ a);
System.out.println("Enter your password: "+b);
}
}
class userB extends userA{
public void CreateAccount(String a,String b){
userA obj = new userA();
super.CreateAccount(a,b);
obj.Watch();
obj.Upload();
}
}
| [
"[email protected]"
]
| |
a474f6a1fbb94d94ae2e559f7f06ff41ecfbe83c | 88be3f01a74fa7b6f0f74cce1607af7e6d9153df | /src/main/java/distributedsystems/foodService/services/IService/FoodIService.java | 824ec6d4688640297942d00f982e6a51452f78bf | []
| no_license | l6l9ldemonl6l9l/foodService | 58aa90beda7b64b66f4b3b43757e97c3c9e28dee | 11fa39f33f3ccd82ca0a7d76dece57f662e873b9 | refs/heads/master | 2023-01-05T14:53:41.846868 | 2020-10-26T19:15:13 | 2020-10-26T19:15:13 | 307,479,404 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 404 | java | package distributedsystems.foodService.services.IService;
import distributedsystems.foodService.services.models.Food;
import javassist.NotFoundException;
import java.util.List;
import java.util.UUID;
public interface FoodIService{
List<Food> findAll();
Food save(Food foodForSave);
Food getById(UUID id) throws NotFoundException;
void deleteById(UUID id) throws NotFoundException;
}
| [
"[email protected]"
]
| |
a588e00fe7d310d32abf7e8025c84b33f76217c9 | d422dab2abd0a4817e1af93a3cce7f0de30b090c | /src/Exercise/chap06/Fsort.java | f64c7a15fc6925f4cbec0c36ffe36ca0071f8c7a | []
| no_license | digilogGithub/DOitDataStructure | 2cfabc29beb165aa475bf5d4ffd9a901707f3389 | 4e1009a5c40ee1c35a99bbd9698fde81af61f8b2 | refs/heads/master | 2020-04-22T09:08:31.781221 | 2019-02-12T06:05:25 | 2019-02-12T06:05:25 | 170,262,092 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,201 | java | package Exercise.chap06;
import java.util.Scanner;
// 도수 정렬
class Fsort {
// 도수 정렬(0 이상 max 이하의 값을 입력합니다)
static void fSort(int[] a, int n, int max) {
int[] f = new int[max + 1]; // 누적 도수
int[] b = new int[n]; // 작업용 목적 배열
for (int i = 0; i < n; i++) f[a[i]]++; // 1단계
for (int i = 1; i <= max; i++) f[i] += f[i - 1]; // 2단계
for (int i = n - 1; i >= 0; i--) b[--f[a[i]]] = a[i]; // 3단계
for (int i = 0; i < n; i++) a[i] = b[i]; // 4단계
}
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
System.out.println("도수 정렬");
System.out.print("요솟수:");
int nx = stdIn.nextInt();
int[] x = new int[nx];
for (int i = 0; i < nx; i++) {
do {
System.out.print("x[" + i + "]:");
x[i] = stdIn.nextInt();
} while (x[i] < 0);
}
int max = x[0];
for (int i = 1; i < nx; i++)
if (x[i] > max) max = x[i];
fSort(x, nx, max); // 배열 x를 도수 정렬
System.out.println("오름차순으로 정렬했습니다.");
for (int i = 0; i < nx; i++)
System.out.println("x[" + i + "]=" + x[i]);
}
} | [
"[email protected]"
]
| |
b18d3dd3cc4dfde8071d5388e0098bd33d1822bc | e32266e49720e901b5fe46d94e907d6ffb0df087 | /src/com/zzuli/ssm/po/MoneyKind.java | 5c33acca68904e58b876d1181fd25b090a57a356 | []
| no_license | wangjinghui321/generator | 5a2b405764deaec1322c8622a60e805209370c47 | 67a0d6dafec8082e2ae97cd51783be8efff1c5e0 | refs/heads/master | 2020-03-28T10:24:05.961960 | 2018-09-10T05:51:03 | 2018-09-10T05:51:03 | 148,105,507 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 946 | java | package com.zzuli.ssm.po;
public class MoneyKind {
private String kindId;
private String kindCode;
private String kindName;
private String kindItem;
public String getKindId() {
return kindId;
}
public void setKindId(String kindId) {
this.kindId = kindId == null ? null : kindId.trim();
}
public String getKindCode() {
return kindCode;
}
public void setKindCode(String kindCode) {
this.kindCode = kindCode == null ? null : kindCode.trim();
}
public String getKindName() {
return kindName;
}
public void setKindName(String kindName) {
this.kindName = kindName == null ? null : kindName.trim();
}
public String getKindItem() {
return kindItem;
}
public void setKindItem(String kindItem) {
this.kindItem = kindItem == null ? null : kindItem.trim();
}
} | [
"[email protected]"
]
| |
1a774f40ad6e488a2e2d9957a4ae145569c08300 | 525a9e4323d6de43884370a8ae8a9aad16af678b | /SpringMonogoRest/src/main/java/com/bookapp/service/BookServiceImpl.java | a26574cc92475afa8236ba27cf09ce2aa84890cc | []
| no_license | 99002766/exam | c77c0534bb1b123e4ad60b6342e36faab8f6d947 | 236813903455a828317ca81024a3c5a4ec174882 | refs/heads/main | 2023-01-01T20:00:21.628194 | 2020-10-27T12:21:55 | 2020-10-27T12:21:55 | 306,895,610 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,319 | java | package com.bookapp.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bookapp.dao.BookRepos;
import com.bookapp.exception.BookNotFoundException;
import com.bookapp.model.Book;
@Service
public class BookServiceImpl implements BookService {
@Autowired
BookRepos bookRepository;
@Override
public Book addBook(Book book) {
Book newbook =bookRepository.save(book);
return newbook;
}
@Override
public boolean deleteBook(Integer bookId) {
bookRepository.deleteById(bookId);
return true;
}
@Override
public Book getBookById(Integer bookId) {
Book book=bookRepository.findById(bookId)
.orElseThrow(()->new BookNotFoundException("Id not available"));
return null;
}
@Override
public Book updateBook(Book book) {
return bookRepository.save(book);
}
@Override
public List<Book> getAllBooks() {
return bookRepository.findAll();
}
@Override
public List<Book> getBookbyAuthor(String author) {
// TODO Auto-generated method stub
return bookRepository.findByAuthor(author);
}
@Override
public List<Book> getBookByCategory(String category) {
// TODO Auto-generated method stub
return bookRepository.findByCategoryOrderByTitleAsc(category);
}
@Override
public List<Book> findByTitleAndAuthor(String title, String author) {
// TODO Auto-generated method stub
return bookRepository.findByTitleAndAuthor(title,author);
}
@Override
public List<Book> findBooksByTitleAndPrice(String title, Double price) {
// TODO Auto-generated method stub
return bookRepository.findBooksByTitleAndPrice(title, price);
}
@Override
public List<Book> getBookbycategory(String category) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Book> findBooksByTitleAndPrice(String title, String price) {
// TODO Auto-generated method stub
return null;
}
} | [
"[email protected]"
]
| |
1867bd99a3e07c92ccf2442b736e6d332715f0f4 | c364d60e42bf7b38226510a4d14b7cf6bd2fbd79 | /Array/Array.java | 7695b34dd9ba4c2837f3d609d6edc37a48050169 | []
| no_license | Aylin-Neyra-Leon/Par.impar | 75c04b022d47385e0e747d844d336f0850b887f2 | 9c779fb6d551f498b64ceba34d74538cd09b4d2d | refs/heads/master | 2022-11-11T14:05:28.640150 | 2020-07-02T01:05:56 | 2020-07-02T01:05:56 | 276,517,812 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 462 | java | package par.e.impar;
//Aleatorio
import java.util.Random;
public class PareImpar {
public static void main(String[] args) {
Random random=new Random();
int ArrayInt[]=new int[20];
for(int Hol@=0; Hol@<ArrayInt.length; Hol@++){
ArrayInt[Hol@]=random.nextInt(101);
if(ArrayInt[Hol@]%2==0){
System.out.print(" "+ArrayInt[Hol@]+" ");
}
}
for(int i=0; i<20; i++){
if(ArrayInt[i]%2==0){
}
else{
System.out.print(" "+ArrayInt[i]+" ");
}
}
System.out.println("");
}
}
| [
"[email protected]"
]
| |
4abd7b61c11eb36ea22ed36e2e249e9b6fd70b64 | 3efe12d696cff1474417558a3e857148f6d53793 | /app/src/main/java/com/asanam/udacityrecipebook/presenter/StepDetailsPresenter.java | 9d674d0818f8b8ace73c4f8233db1efb959d108f | []
| no_license | gowthamraj07/UdacityRecipeBook | c8d4c47a8e01f2770094e857b14782c97daf4a78 | b29a25066ed10723310d6a7ad81114c0839a0252 | refs/heads/master | 2020-03-22T10:25:20.831630 | 2018-07-20T11:59:49 | 2018-07-20T11:59:49 | 139,901,487 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,532 | java | package com.asanam.udacityrecipebook.presenter;
import android.database.Cursor;
import com.asanam.udacityrecipebook.db.DBContract;
import com.asanam.udacityrecipebook.repository.DBRepository;
import com.asanam.udacityrecipebook.utils.Constants;
import com.asanam.udacityrecipebook.view.StepDetailsView;
public class StepDetailsPresenter {
private StepDetailsView view;
private DBRepository repository;
public StepDetailsPresenter(StepDetailsView view, DBRepository repository) {
this.view = view;
this.repository = repository;
}
public void showStepDetailsScreen(Long recipeId, Long stepId) {
view.initializeViews();
Cursor stepDetails = repository.getStepDetails(stepId, recipeId);
if(stepDetails.getCount() == 0) {
return;
}
stepDetails.moveToFirst();
String videoUrl = stepDetails.getString(stepDetails.getColumnIndex(DBContract.StepTable.COLUMN_VIDEO_URL));
String description = stepDetails.getString(stepDetails.getColumnIndex(DBContract.StepTable.COLUMN_DESCRIPTION));
String thumbnailUrl = stepDetails.getString(stepDetails.getColumnIndex(DBContract.StepTable.COLUMN_THUMBNAIL_URL));
Cursor previous = repository.getPreviousStepDetails(recipeId, stepId);
if(previous!= null && previous.getCount() > 0) {
view.showPrevious();
} else {
view.hidePrevious();
}
Cursor next = repository.getNextStepDetails(recipeId, stepId);
if(next != null && next.getCount() > 0) {
view.showNext();
} else {
view.hideNext();
}
if(videoUrl != null && !videoUrl.isEmpty()) {
showVideo(videoUrl, description);
return;
}
if(thumbnailUrl != null && !thumbnailUrl.isEmpty()) {
if(thumbnailUrl.endsWith(Constants.MP4)) {
showVideo(thumbnailUrl, description);
} else {
showImage(description, thumbnailUrl);
}
return;
}
view.hideImageAndVideo();
if(description != null && !description.isEmpty()) {
view.showDescription(description);
}
}
private void showImage(String description, String thumbnailUrl) {
view.showImage(thumbnailUrl, description);
view.hideVideo();
}
private void showVideo(String videoUrl, String description) {
view.showVideo(videoUrl, description);
view.hideImage();
}
}
| [
"[email protected]"
]
| |
74ff25f2a80980dc4798f28a149d46bdf6306149 | c1976f50e7a654d599f4dffe7c1d37a623aecf9e | /Desktop Application (Java GUI)/Chatbot Assistant Core/src/test/java/org/chatbot/assistant/simplifiers/SimplifiersMatcher.java | 8a0da946beac47fe60d95245fb7417dd5a39a7c9 | []
| no_license | umutguneri/Question-Answering-Assistant | dd6bcf0136b8eec55c92d84f725e2390e21c772c | dedc38363612158b60ca2c28c1f60a32682e2f54 | refs/heads/master | 2020-04-01T21:07:04.431576 | 2018-10-18T15:22:05 | 2018-10-18T15:22:05 | 153,635,679 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,797 | java | /*
* #%L
* Simmetrics Core
* %%
* Copyright (C) 2014 - 2016 Simmetrics Authors
* %%
* 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.
* #L%
*/
package org.chatbot.assistant.simplifiers;
import org.chatbot.assistant.simplifiers.Simplifier;
import org.chatbot.assistant.simplifiers.Simplifiers;
import org.chatbot.assistant.simplifiers.Simplifiers.ChainSimplifier;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
import com.google.common.collect.ImmutableList;
import com.google.monitoring.runtime.instrumentation.common.com.google.common.collect.Lists;
@SuppressWarnings("javadoc")
public abstract class SimplifiersMatcher extends TypeSafeMatcher<Simplifier> {
public static SimplifiersMatcher chain(final Simplifier simplifier,
final Simplifier... simplifiers){
return new SimplifiersMatcher() {
@Override
public void describeTo(Description arg0) {
arg0.appendValue(Simplifiers.chain(simplifier, simplifiers));
}
@Override
protected boolean matchesSafely(Simplifier item) {
if(item.getClass() != ChainSimplifier.class){
return false;
}
ChainSimplifier s = (ChainSimplifier) item;
return ImmutableList.copyOf(Lists.asList(simplifier, simplifiers)).equals(s.getSimplifiers());
}
};
}
}
| [
"[email protected]"
]
| |
39fe8f12c2b69c769fc95acc51ec2e62d2b7818f | 95c49f466673952b465e19a5ee3ae6eff76bee00 | /src/main/java/com/zhihu/android/picture/editor/drawing/p1791a/BitmapBrush.java | 5c99fd6dd18a6b24dd30bfa8729ed0a84563dcc2 | []
| no_license | Phantoms007/zhihuAPK | 58889c399ae56b16a9160a5f48b807e02c87797e | dcdbd103436a187f9c8b4be8f71bdf7813b6d201 | refs/heads/main | 2023-01-24T01:34:18.716323 | 2020-11-25T17:14:55 | 2020-11-25T17:14:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 472 | java | package com.zhihu.android.picture.editor.drawing.p1791a;
import android.graphics.Bitmap;
/* renamed from: com.zhihu.android.picture.editor.drawing.a.a */
/* compiled from: BitmapBrush */
public class BitmapBrush implements AbstractC23493b {
/* renamed from: a */
private Bitmap f81623a;
public BitmapBrush(Bitmap bitmap) {
this.f81623a = bitmap;
}
/* renamed from: a */
public Bitmap mo103476a() {
return this.f81623a;
}
}
| [
"[email protected]"
]
| |
85c37f7b88b92d4baf4fb88409ef757067f8d3cb | 8a6691d290a490fbaf1bf12c82e6aa29edf2bb10 | /java-concurrency-features/src/main/java/com/java/util/concurrent/atomic/FeatureDoubleAccumulator.java | f9fcea23e27170e08bca0116155d800754c0e31f | []
| no_license | abhishek-honey/java | 35efc940afc7d82b49491ad7001fa6e0cb35813e | db3d9809e1933dd5a93f4f57ab260f5a1e08f7c7 | refs/heads/master | 2023-04-23T18:55:21.519506 | 2021-05-16T05:06:07 | 2021-05-16T05:06:07 | 287,077,188 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 85 | java | package com.java.util.concurrent.atomic;
public class FeatureDoubleAccumulator {
}
| [
"[email protected]"
]
| |
de5ffc047fc23fbc3ec6a5e449979d3b112c3ee0 | 78b6c51f04dc118977decc1eae03796738dadaa4 | /app/src/main/java/coffeespace/com/br/periciasis/Sistema/PericiaIpaf.java | 10045bcbfbe2d60fa20ed3d73fbb33631c7b9ccc | []
| no_license | dudasyn/PericiaSis | cc259551331070587f5103cbdb7492e9e8a1570e | 8a9ccfd8e40d235b2cbee1189cdde63f6843c56d | refs/heads/master | 2022-03-29T03:49:57.700394 | 2020-01-08T00:48:37 | 2020-01-08T00:48:37 | 109,199,813 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,939 | java | package coffeespace.com.br.periciasis.Sistema;
import android.util.Log;
import java.util.ArrayList;
import coffeespace.com.br.periciasis.Sistema.Objetos.Automovel;
import coffeespace.com.br.periciasis.Sistema.Objetos.Cadaver;
import coffeespace.com.br.periciasis.Sistema.Objetos.Caminhao;
import coffeespace.com.br.periciasis.Sistema.Objetos.Motocicleta;
import coffeespace.com.br.periciasis.Sistema.Objetos.Objeto;
import coffeespace.com.br.periciasis.Sistema.Objetos.Onibus;
import coffeespace.com.br.periciasis.Sistema.Objetos.Veiculo;
/**
* Created by user on 20/10/2017.
*/
public class PericiaIpaf extends Pericia {
String formato, angulacao, distsolo, eixomaior, eixomenor, orientacao, origem, trajetoria, localizacao;
String nomedoperito;
String iddoperito;
public PericiaIpaf() {
}
@Override
public ArrayList<Veiculo> getaVeiculosExaminados() {
return super.getaVeiculosExaminados();
}
@Override
public void setaVeiculosExaminados(ArrayList<Veiculo> aVeiculosExaminados) {
super.setaVeiculosExaminados(aVeiculosExaminados);
}
public String geraTitulo() {
return "<b>LAUDO DE EXAME EM LOCAL DE IMPACTO DE PROJETIL DE ARMA DE FOGO</b>";
}
public String geraTabela() {
String c = "";
int nobjetos = getaObjetos().size();
c = c + "<ol>";
for (int i = 0; i < nobjetos; i++) {
String caracteristicas = "";
int npafs = getaObjetos().get(i).getaIpafs().size();
c = c + "<table border=1>";
for (int j = 0; j < npafs; j++) {
formato = getaObjetos().get(i).getaIpafs().get(j).getFormato();
distsolo = getaObjetos().get(i).getaIpafs().get(j).distsolo;
angulacao = getaObjetos().get(i).getaIpafs().get(j).angulacao;
eixomaior = getaObjetos().get(i).getaIpafs().get(j).eixomaior;
eixomenor = getaObjetos().get(i).getaIpafs().get(j).eixomenor;
orientacao = getaObjetos().get(i).getaIpafs().get(j).getOrientacao();
localizacao = getaObjetos().get(i).getaIpafs().get(j).getLocalizacao();
origem = getaObjetos().get(i).getaIpafs().get(j).getOrigem();
trajetoria = getaObjetos().get(i).getaIpafs().get(j).getTrajetoria();
if (empty(formato)) {
formato = "[NÃO INSERIDO]";
}
if (empty(distsolo)) {
distsolo = "[NÃO INSERIDO]";
}
if (empty(angulacao)) {
angulacao = "[NÃO INSERIDO]";
}
if (empty(eixomaior)) {
eixomaior = "[NÃO INSERIDO]";
}
if (empty(eixomenor)) {
eixomenor = "[NÃO INSERIDO]";
}
String transfixou = "";
if (!getaObjetos().get(i).getaIpafs().get(j).getTransfixed()) {
transfixou = "transfixante";
} else {
transfixou = "não transfixante";
}
caracteristicas = "impacto " + transfixou + " de " +
formato + ", distando " + distsolo + "m do solo" +
", apresenta medidas para o eixo maior de " + eixomaior + " mm, e " + eixomenor + "mm para o eixo menor, apresentando angulacao de " + angulacao + ", com a seguinte trajetória: " + trajetoria;
c = c + "<tr><td rowspan=3><b>IPAF " + (j + 1) + "</b></td><td><b>Objeto Examinado</b></td><td><b>LOCALIZAÇÃO</b></td><td><b>DIREÇÃO E SENTIDO</b></td><td><b>ORIGEM</b></td></tr>" +
"<td>" + retTipo(getaObjetos().get(i)) + "</td>" +
"<td>" + localizacao + "</td>" +
"<td>" + orientacao + "</td>" +
"<td>" + origem + "</td>" +
"</tr><tr><td colspan=4>Informações adicionais: " + caracteristicas + "</td></tr></tr>";
}
c = c + "</table>";
}
c = c + "</ol>";
/*
for (String item : getaItemConstatacao()) {
c = c + "<li> " + item + ";</li>";
}
*/
return c;
}
public String geraConstatacaoObjeto() {
String c = "";
int nobjetos = getaVeiculosExaminados().size();
c = c + "<ol>";
for (int i = 0; i < getaObjetos().size(); i++) {
if (!(getaObjetos().get(i) instanceof Veiculo)) {
c = c + "<li> No local foi examinado um(a) " + getaObjetos().get(i).getNome() + " com as seguintes características: " + getaObjetos().get(i).getDescricao() + ";</li>";
} else {
c = c + "<li> Das constatações no " + retTipo(getaObjetos().get(i))+ " (" + ((Veiculo) getaObjetos().get(i)).getPlaca() + "): </li>";
}
int npafs = getaObjetos().get(i).getaIpafs().size();
c = c + "<ol>";
for (int j = 0; j < npafs; j++) {
formato = getaObjetos().get(i).getaIpafs().get(j).getFormato();
distsolo = getaObjetos().get(i).getaIpafs().get(j).distsolo;
angulacao = getaObjetos().get(i).getaIpafs().get(j).angulacao;
eixomaior = getaObjetos().get(i).getaIpafs().get(j).eixomaior;
eixomenor = getaObjetos().get(i).getaIpafs().get(j).eixomenor;
orientacao = getaObjetos().get(i).getaIpafs().get(j).getOrientacao();
localizacao = getaObjetos().get(i).getaIpafs().get(j).getLocalizacao();
origem = getaObjetos().get(i).getaIpafs().get(j).getOrigem();
trajetoria = getaObjetos().get(i).getaIpafs().get(j).getTrajetoria();
String transfixou = "";
if (!getaObjetos().get(i).getaIpafs().get(j).getTransfixed()) {
transfixou = "transfixante";
} else {
transfixou = "não transfixante";
}
if (empty(formato)) {
formato = "[NÃO INSERIDO]";
}
if (empty(distsolo)) {
distsolo = "[NÃO INSERIDO]";
}
if (empty(angulacao)) {
angulacao = "[NÃO INSERIDO]";
}
if (empty(eixomaior)) {
eixomaior = "[NÃO INSERIDO]";
}
if (empty(eixomenor)) {
eixomenor = "[NÃO INSERIDO]";
}
if (getaObjetos().get(i).getaIpafs().size() == 1) {
c = c + "<li class=\"lialf\">Impacto de projétil de arma de fogo de " + formato + ", localizado no(a) " + localizacao + ", de direção " + orientacao + ", com origem " + origem + " trajetoria, sendo identificada a seguinte trajetória: " + trajetoria + "</li>";
} else {
c = c + "<li>IPAF(" + (j + 1) + "): Impacto de " + formato + ", localizado no(a) " + localizacao + ", de direção " + orientacao + ", com origem " + origem + " trajetoria, sendo identificada a seguinte trajetória: " + trajetoria + "</li>";
}
}
c = c + "</ol>";
}
c = c + "</ol>";
/*
for (String item : getaItemConstatacao()) {
c = c + "<li> " + item + ";</li>";
}*/
return c;
}
public String geraConstatacao() {
String c = "";
if (!empty(geraConstatacaoObjeto())) {
c = c + geraConstatacaoObjeto();
}
if (!empty(geraTabela())) {
c = c + geraTabela();
}
return c;
}
public boolean outrosCamposVazios() {
if (empty(eixomaior) && empty(eixomenor) && empty(angulacao) && empty(distsolo)) {
return true;
} else {
return false;
}
}
public static boolean empty(final String s) {
// Null-safe, short-circuit evaluation.
return s == null || s.trim().isEmpty();
}
public String retTipo(Objeto o) {
String tipo = "";
if (o instanceof Veiculo) {
if (o instanceof Motocicleta) {
tipo = "motocicleta(" +((Motocicleta) o).getPlaca() ;
}
if (o instanceof Automovel) {
tipo = "automóvel(" +((Automovel) o).getPlaca() ;
}
if (o instanceof Caminhao) {
tipo = "caminhão(" +((Caminhao) o).getPlaca() ;
}
if (o instanceof Onibus) {
tipo = "onibus(" +((Onibus) o).getPlaca() ;
}
}else {
if (o instanceof Cadaver) {
tipo = "cadáver";
}else{
tipo = o.getNome();
}
}
return tipo;
}
} | [
"[email protected]"
]
| |
c4a179c0c5610347638755acb36f4c8773f6f0f0 | 26b7f30c6640b8017a06786e4a2414ad8a4d71dd | /src/number_of_direct_superinterfaces/i52959.java | 309171be24f251adaa35ff65340070633ef398f2 | []
| no_license | vincentclee/jvm-limits | b72a2f2dcc18caa458f1e77924221d585f23316b | 2fd1c26d1f7984ea8163bc103ad14b6d72282281 | refs/heads/master | 2020-05-18T11:18:41.711400 | 2014-09-14T04:25:18 | 2014-09-14T04:25:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 69 | java | package number_of_direct_superinterfaces;
public interface i52959 {} | [
"[email protected]"
]
| |
b791382d070d825af87ba97f337fe1eabdb679b2 | bcdad602e34f9b49c742acfe62328390eae2fce8 | /app/src/main/java/com/test/xutils3demo/db/Parent.java | 95c04e81f6d2139fd5f121e3312335a77a5234d8 | []
| no_license | KainKxng/xUtils3Demo | 160b479ee14854ddd890a974f0bc72ee43888824 | f5cb787008704e0b1bb81e5b017c36292b88d785 | refs/heads/master | 2020-03-24T00:07:57.438721 | 2018-07-23T13:35:37 | 2018-07-23T13:35:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,059 | java | package com.test.xutils3demo.db;
import org.xutils.DbManager;
import org.xutils.db.annotation.Column;
import org.xutils.db.annotation.Table;
import org.xutils.ex.DbException;
import java.util.Date;
import java.util.List;
/**
* Author: wyouflf
* Date: 13-7-25
* Time: 下午7:06
*/
@Table(name = "parent", onCreated = "CREATE UNIQUE INDEX index_name ON parent(name,email)")
public class Parent {
@Column(name = "id", isId = true)
private int id;
@Column(name = "name")
public String name;
@Column(name = "email")
private String email;
@Column(name = "isAdmin")
private boolean isAdmin;
@Column(name = "time")
private Date time;
@Column(name = "date")
private java.sql.Date date;
public List<Child> getChildren(DbManager db) throws DbException {
return db.selector(Child.class).where("parentId", "=", this.id).findAll();
}
// 一对一
//public Child getChild(DbManager db) throws DbException {
// return db.selector(Child.class).where("parentId", "=", this.id).findFirst();
//}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public boolean isAdmin() {
return isAdmin;
}
public void setAdmin(boolean admin) {
isAdmin = admin;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public java.sql.Date getDate() {
return date;
}
public void setDate(java.sql.Date date) {
this.date = date;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "Parent{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", isAdmin=" + isAdmin +
", time=" + time +
", date=" + date +
'}';
}
}
| [
"[email protected]"
]
| |
09db873344423f98b59e9227d3e0211977a3a3df | b5f9482b5377c71567836e4605b23299aafbfdec | /src/main/java/com/jeecg/userhelpsell/entity/TUserHelpSellEntity.java | 933d5977d08c8ec411f61cbdcf2b9740338af0f5 | []
| no_license | changjiangzhixuedev/jeecg | 7e165b5aba89b41fe5c3651f423ada86ebb12d93 | 2b2adab713f1890b5dbad8c86b6902cf5e2cfde1 | refs/heads/master | 2020-04-30T13:11:32.530392 | 2019-03-21T05:39:48 | 2019-03-21T05:39:48 | 176,849,095 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 7,297 | java | package com.jeecg.userhelpsell.entity;
import java.math.BigDecimal;
import java.util.Date;
import java.lang.String;
import java.lang.Double;
import java.lang.Integer;
import java.math.BigDecimal;
import javax.xml.soap.Text;
import java.sql.Blob;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.SequenceGenerator;
import org.jeecgframework.poi.excel.annotation.Excel;
/**
* @Title: Entity
* @Description: 帮我卖车
* @author onlineGenerator
* @date 2019-03-13 22:18:30
* @version V1.0
*
*/
@Entity
@Table(name = "t_user_help_sell", schema = "")
@SuppressWarnings("serial")
public class TUserHelpSellEntity implements java.io.Serializable {
/**主键*/
private String id;
/**创建人名称*/
private String createName;
/**创建人登录名称*/
private String createBy;
/**创建日期*/
private Date createDate;
/**更新人名称*/
private String updateName;
/**更新人登录名称*/
private String updateBy;
/**更新日期*/
private Date updateDate;
/**所属部门*/
private String sysOrgCode;
/**所属公司*/
private String sysCompanyCode;
/**流程状态*/
private String bpmStatus;
/**用户*/
@Excel(name="用户",width=15,dictTable ="t_user",dicCode ="id",dicText ="nick_name")
private String userId;
/**姓名*/
@Excel(name="姓名",width=15)
private String name;
/**手机号*/
@Excel(name="手机号",width=15)
private String phoneNumber;
/**品牌*/
@Excel(name="品牌",width=15)
private String cartBrand;
/**车系*/
@Excel(name="车系",width=15)
private String cartSys;
/**
*方法: 取得java.lang.String
*@return: java.lang.String 主键
*/
@Id
@GeneratedValue(generator = "paymentableGenerator")
@GenericGenerator(name = "paymentableGenerator", strategy = "uuid")
@Column(name ="ID",nullable=false,length=36)
public String getId(){
return this.id;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 主键
*/
public void setId(String id){
this.id = id;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 创建人名称
*/
@Column(name ="CREATE_NAME",nullable=true,length=50)
public String getCreateName(){
return this.createName;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 创建人名称
*/
public void setCreateName(String createName){
this.createName = createName;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 创建人登录名称
*/
@Column(name ="CREATE_BY",nullable=true,length=50)
public String getCreateBy(){
return this.createBy;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 创建人登录名称
*/
public void setCreateBy(String createBy){
this.createBy = createBy;
}
/**
*方法: 取得java.util.Date
*@return: java.util.Date 创建日期
*/
@Column(name ="CREATE_DATE",nullable=true,length=20)
public Date getCreateDate(){
return this.createDate;
}
/**
*方法: 设置java.util.Date
*@param: java.util.Date 创建日期
*/
public void setCreateDate(Date createDate){
this.createDate = createDate;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 更新人名称
*/
@Column(name ="UPDATE_NAME",nullable=true,length=50)
public String getUpdateName(){
return this.updateName;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 更新人名称
*/
public void setUpdateName(String updateName){
this.updateName = updateName;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 更新人登录名称
*/
@Column(name ="UPDATE_BY",nullable=true,length=50)
public String getUpdateBy(){
return this.updateBy;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 更新人登录名称
*/
public void setUpdateBy(String updateBy){
this.updateBy = updateBy;
}
/**
*方法: 取得java.util.Date
*@return: java.util.Date 更新日期
*/
@Column(name ="UPDATE_DATE",nullable=true,length=20)
public Date getUpdateDate(){
return this.updateDate;
}
/**
*方法: 设置java.util.Date
*@param: java.util.Date 更新日期
*/
public void setUpdateDate(Date updateDate){
this.updateDate = updateDate;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 所属部门
*/
@Column(name ="SYS_ORG_CODE",nullable=true,length=50)
public String getSysOrgCode(){
return this.sysOrgCode;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 所属部门
*/
public void setSysOrgCode(String sysOrgCode){
this.sysOrgCode = sysOrgCode;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 所属公司
*/
@Column(name ="SYS_COMPANY_CODE",nullable=true,length=50)
public String getSysCompanyCode(){
return this.sysCompanyCode;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 所属公司
*/
public void setSysCompanyCode(String sysCompanyCode){
this.sysCompanyCode = sysCompanyCode;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 流程状态
*/
@Column(name ="BPM_STATUS",nullable=true,length=32)
public String getBpmStatus(){
return this.bpmStatus;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 流程状态
*/
public void setBpmStatus(String bpmStatus){
this.bpmStatus = bpmStatus;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 用户
*/
@Column(name ="USER_ID",nullable=true,length=32)
public String getUserId(){
return this.userId;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 用户
*/
public void setUserId(String userId){
this.userId = userId;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 姓名
*/
@Column(name ="NAME",nullable=true,length=32)
public String getName(){
return this.name;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 姓名
*/
public void setName(String name){
this.name = name;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 手机号
*/
@Column(name ="PHONE_NUMBER",nullable=true,length=32)
public String getPhoneNumber(){
return this.phoneNumber;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 手机号
*/
public void setPhoneNumber(String phoneNumber){
this.phoneNumber = phoneNumber;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 品牌
*/
@Column(name ="CART_BRAND",nullable=true,length=32)
public String getCartBrand(){
return this.cartBrand;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 品牌
*/
public void setCartBrand(String cartBrand){
this.cartBrand = cartBrand;
}
/**
*方法: 取得java.lang.String
*@return: java.lang.String 车系
*/
@Column(name ="CART_SYS",nullable=true,length=32)
public String getCartSys(){
return this.cartSys;
}
/**
*方法: 设置java.lang.String
*@param: java.lang.String 车系
*/
public void setCartSys(String cartSys){
this.cartSys = cartSys;
}
} | [
"[email protected]"
]
| |
3c0a4e67daab2ff1e1c8400a3abd540081b12a68 | 7a77174db8d6b64327c4f235844bfb9a1b3068e4 | /src/br/com/protocoloeletronico/domain/NotaEmpenho.java | 26597bba12c532359e99c3d1e226587e37d9a250 | []
| no_license | DiasGustavo/eprotocolo | ff14d8b2b35577c315f468565a93dec9158054ce | eb704821d4fe86c14bdb71fca1fc4c4b23a462cf | refs/heads/master | 2023-05-07T03:07:42.881873 | 2021-05-14T15:46:24 | 2021-05-14T15:46:24 | 287,762,437 | 1 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 4,276 | java | package br.com.protocoloeletronico.domain;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Digits;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
@Entity
@Table(name = "tbl_nota_empenho")
@NamedQueries({
@NamedQuery(name = "NotaEmpenho.listar", query = "SELECT nota FROM NotaEmpenho nota"),
@NamedQuery(name = "NotaEmpenho.buscarPorCodigo", query = "SELECT nota FROM NotaEmpenho nota WHERE nota.id = :codigo"),
@NamedQuery(name = "NotaEmpenho.buscarPorDocumento", query = "SELECT nota FROM NotaEmpenho nota WHERE nota.documento = :documento"),
@NamedQuery(name = "NotaEmpenho.buscarPorFuncionario", query = "SELECT nota FROM NotaEmpenho nota WHERE nota.funcionario = :funcionario")
})
public class NotaEmpenho {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "cod_nota")
private Long Id;
@NotEmpty(message = "o campo processo é obrigatório")
@Size(min = 1, max = 10, message= "Nome deve ter entre 1 e 10 caracteres")
@Column(name="numero", length=10, nullable=false)
private String numero;
@NotNull(message="o campo valor é obrigatório.")
@DecimalMin(value="0.00", message="o campo valor deve ser maior do que 0.00")
@Digits(integer = 7, fraction = 2, message = "coloque um valor válido para o valor")
@Column(name = "valor", precision = 9, scale = 2, nullable = false)
private BigDecimal valor;
@NotEmpty(message = "o campo descrição é obrigatório")
@Size(min = 1, max = 50, message= "Descrição deve ter entre 1 e 50 caracteres")
@Column(name="descricao", length=50, nullable=false)
private String descricao;
@Column(name="observacao", length=250)
private String observacao;
@NotNull(message = "O campo Documento é obrigatório")
@ManyToOne (fetch = FetchType.EAGER)
@JoinColumn(name = "fk_documento", referencedColumnName = "cod_doc", nullable = false)
private Documento documento;
@NotNull(message = "O campo Digitador é obrigatório")
@ManyToOne (fetch = FetchType.EAGER)
@JoinColumn(name = "fk_funcionario", referencedColumnName = "cod_fun", nullable = false)
private Funcionario funcionario;
public Long getId() {
return Id;
}
public void setId(Long id) {
Id = id;
}
public String getNumero() {
return numero;
}
public void setNumero(String numero) {
this.numero = numero;
}
public BigDecimal getValor() {
return valor;
}
public void setValor(BigDecimal valor) {
this.valor = valor;
}
public String getObservacao() {
return observacao;
}
public void setObservacao(String observacao) {
this.observacao = observacao;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public Documento getDocumento() {
return documento;
}
public void setDocumento(Documento documento) {
this.documento = documento;
}
public Funcionario getFuncionario() {
return funcionario;
}
public void setFuncionario(Funcionario funcionario) {
this.funcionario = funcionario;
}
@Override
public String toString() {
return "NotaEmpenho [Id=" + Id + ", numero=" + numero + ", valor=" + valor + ", descricao=" + descricao
+ ", observacao=" + observacao + ", documento=" + documento + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((Id == null) ? 0 : Id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
NotaEmpenho other = (NotaEmpenho) obj;
if (Id == null) {
if (other.Id != null)
return false;
} else if (!Id.equals(other.Id))
return false;
return true;
}
}
| [
"[email protected]"
]
| |
d736944964c31df7ef461685182b4c66892869ba | ae71ad15b2ff5a4e764dbd7a7c9392af7b4757bb | /app/src/main/java/com/example/ruthvikreddy/ble/Model/SampleGattAttributes.java | 8aa7761781b40d50a0842578f60c0606834ede90 | []
| no_license | Ruthvik47/BLE | 6e08c70e14d92b5a6495137cba1075556d3257f7 | e4db99b904b6b22f9705a2da54cbf1be80b685a0 | refs/heads/master | 2020-04-15T21:48:46.509402 | 2019-01-08T05:48:27 | 2019-01-08T05:48:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,718 | java | /*
* Copyright (C) 2013 The Android Open Source Project
*
* 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.example.ruthvikreddy.ble.Model;
import java.util.HashMap;
/**
* This class includes a small subset of standard GATT attributes for demonstration purposes.
*/
public class SampleGattAttributes {
private static HashMap<String, String> attributes = new HashMap();
public static String CLIENT_CHARACTERISTIC_CONFIG = "00002902-0000-1000-8000-00805f9b34fb";
public static String HM_10_CONF = "0000ffe0-0000-1000-8000-00805f9b34fb";
public static String HM_RX_TX = "0000ffe1-0000-1000-8000-00805f9b34fb";
static {
// Sample Services.
attributes.put("0000ffe0-0000-1000-8000-00805f9b34fb", "HM 10 Serial");
attributes.put("00001800-0000-1000-8000-00805f9b34fb", "Device Information Service");
// Sample Characteristics.
attributes.put(HM_RX_TX,"RX/TX data");
attributes.put("00002a29-0000-1000-8000-00805f9b34fb", "Manufacturer Name String");
}
public static String lookup(String uuid, String defaultName) {
String name = attributes.get(uuid);
return name == null ? defaultName : name;
}
}
| [
"[email protected]"
]
| |
dc359a79e0a807bfe4b0c2aba6f96e70068f042f | bf3b335a0dce343ad646176ea02c2bd79f95cfd8 | /src/main/java/hust/mso/ga/GA.java | 75f98a3befb281010c67bb293edf3e953e2dead1 | []
| no_license | DaoTranbk/GA-DAT | 80f58d046ea77ddef28a6ad9911a40a33a95b138 | 05856dcfb5048456e1babf4a965ad513e92d087c | refs/heads/master | 2022-11-11T18:13:25.511920 | 2020-07-07T02:17:53 | 2020-07-07T02:17:53 | 280,579,190 | 3 | 0 | null | 2020-07-18T04:11:40 | 2020-07-18T04:11:39 | null | UTF-8 | Java | false | false | 3,243 | java | package hust.mso.ga;
import java.util.ArrayList;
import hust.mso.ga.Operator.Selection;
public class GA {
private Population pop = new Population();
int nic = 0, gen = 0;
public Individual run() {
pop.init(Parameter.POPULATION_SIZE);
Parameter.FES += pop.size();
Parameter.save_generation(gen);
gen++;
int child_pop_size;
while (Parameter.FES < Parameter.Max_FES && nic < Parameter.PATIENCE_GENERATION) {
ArrayList<Individual> child = new ArrayList<>();
child_pop_size = (Parameter.Max_FES - Parameter.FES) > Parameter.POPULATION_SIZE ? Parameter.POPULATION_SIZE
: (Parameter.Max_FES - Parameter.FES);
while (child.size() < child_pop_size) {
child.addAll(crossover_mutation_v2());
}
Parameter.FES += child.size();
pop.members.addAll(child);
pop.selection();
Parameter.save_generation(gen);
check_local();
gen++;
}
return Parameter.best_ind;
}
public void check_local() {
double prev_best_fitness = Parameter.gen_best.get(gen - 1);
double curr_best_fitness = Parameter.gen_best.get(gen);
if (curr_best_fitness < prev_best_fitness) {
nic = 0;
} else {
nic++;
}
}
public ArrayList<Individual> crossover_mutation() {
ArrayList<Individual> offsprings = new ArrayList<>();
ArrayList<Individual> parents;
if (Parameter.rand.nextDouble() < 0.1) {
parents = Selection.tourament(pop.members);
} else {
parents = Selection.random(pop.members);
}
Individual parent1 = parents.get(0);
Individual parent2 = parents.get(1);
double rnd = Parameter.rand.nextDouble();
if (rnd < Parameter.pc) {
offsprings = pop.crossover(parent1, parent2);
} else if (rnd < Parameter.pm) {
offsprings.add(pop.mutation(parent1));
offsprings.add(pop.mutation(parent2));
}
for (Individual ind : offsprings) {
ind.calculate_fitness();
}
return offsprings;
}
public ArrayList<Individual> crossover_mutation_v2() {
ArrayList<Individual> offsprings = new ArrayList<>();
ArrayList<Individual> parents;
// if (Parameter.rand.nextDouble() < 0.3) {
parents = Selection.tourament(pop.members);
// } else {
// parents = Selection.random(pop.members);
// }
Individual parent1 = parents.get(0);
Individual parent2 = parents.get(1);
double rnd = Parameter.rand.nextDouble();
if (rnd < Parameter.pc) {
offsprings = pop.crossover(parent1, parent2);
int i = 0;
for (Individual ind: offsprings) {
rnd = Parameter.rand.nextDouble();
if (rnd < Parameter.pm) {
offsprings.set(i, pop.mutation(ind));
i++;
}
}
}
for (Individual ind : offsprings) {
ind.calculate_fitness();
}
return offsprings;
}
}
| [
"[email protected]"
]
| |
2197e0fdab60e89fdd93c5554aa7a49c526b8f58 | b0137dd82ae73140c615b06edb0b8fda2343016f | /app/src/main/java/com/bx/research/net/UtilDateSerializer.java | fc2c470c23f7f48a0c036c4d6f46412a3c64cbea | []
| no_license | Suosuo123/Research | 0e3a57f03dcc1c31a486aa2eaad8554404bf1337 | 5f50ac845f39d8e8ac3100c85097b48fc671f3a3 | refs/heads/master | 2021-01-15T15:26:03.204768 | 2016-09-01T06:37:58 | 2016-09-01T06:37:58 | 64,999,779 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 494 | java | package com.bx.research.net;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
/** 串行Data */
public class UtilDateSerializer implements JsonSerializer<java.util.Date> {
@Override
public JsonElement serialize(java.util.Date src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(src.getTime());
}
} | [
"[email protected]"
]
| |
ad986fc6ca90fe7ba31e353cb8fe99ea944244da | 4db500bc8ac2db766764e3ff3834f763a030be00 | /app/src/main/java/com/example/admin/thehealthapp/EmargencyResponseActivity.java | a6f6b91d0a59504ecf9e08d23ab6e42be992d86e | []
| no_license | AyushKshitij45/TheHealthApp2 | ee662e61c24149707cc125aa819c9a361761acf2 | 32ea555f7106b9a5a021f350a6c80f1a29dd49af | refs/heads/master | 2021-08-17T05:21:58.465479 | 2017-11-20T20:08:47 | 2017-11-20T20:08:47 | 107,147,756 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,910 | java | package com.example.admin.thehealthapp;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class EmargencyResponseActivity extends AppCompatActivity {
CountDownTimer timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_emergency_response);
timer= new CountDownTimer(5000, 1000) {
public void onFinish() {
String phone = "108";
Intent intent = new Intent(Intent.ACTION_CALL, Uri.fromParts("tel", phone, null));
if (ActivityCompat.checkSelfPermission(EmargencyResponseActivity.this,
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(EmargencyResponseActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 1);
return;
}
startActivity(intent);
finish();
}
public void onTick ( long millisUntilFinished){
}
}.start();
TextView ambulance = (TextView) (findViewById(R.id.call_ambulance));
ambulance.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String phone = "102";
Intent intent = new Intent(Intent.ACTION_CALL, Uri.fromParts("tel", phone, null));
if (ActivityCompat.checkSelfPermission(EmargencyResponseActivity.this,
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(EmargencyResponseActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 1);
return;
}
startActivity(intent);
}
});
TextView hospital = (TextView) (findViewById(R.id.call_hospital));
hospital.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String phone = "108";
Intent intent = new Intent(Intent.ACTION_CALL, Uri.fromParts("tel", phone, null));
if (ActivityCompat.checkSelfPermission(EmargencyResponseActivity.this,
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(EmargencyResponseActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 1);
return;
}
startActivity(intent);
}
});
TextView police = (TextView) (findViewById(R.id.call_police));
police.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String phone = "100";
Intent intent = new Intent(Intent.ACTION_CALL, Uri.fromParts("tel", phone, null));
if (ActivityCompat.checkSelfPermission(EmargencyResponseActivity.this,
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(EmargencyResponseActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 1);
return;
}
startActivity(intent);
}
});
}
@Override
public void onPause(){
super.onPause();
if (timer!=null) {
timer.cancel();
}
}
}
| [
"[email protected]"
]
| |
361dd71a5a832cb9ef31c46183b9910f9bf5cc41 | d808f0da0bda026cc4ad2753fd5ffd1556a3ac88 | /minecomponent/src/test/java/com/chinafocus/minecomponent/ExampleUnitTest.java | d6134d38987b7f5dd180ff9421df0617aef2d986 | []
| no_license | yk14123/RouterComponent | 9b09a5f54f6b097c3bd5394094d3889a6f96cd8a | c2837e30c56fcc6699d4b813045bf69a347c9f8d | refs/heads/master | 2020-05-20T04:13:41.071860 | 2019-05-07T10:16:32 | 2019-05-07T10:16:32 | 185,377,610 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 389 | java | package com.chinafocus.minecomponent;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
]
| |
5f99858e05e6866bd55824fe64a79687bf324e33 | 3f03ed9d8d030a5ffc869ebd68ac2edde578abc8 | /Spring/spring-testna/src/test/java/com/example/springtestna/SpringTestnaApplicationTests.java | 4bb824318fa9916656c375a8e47185070b4af405 | []
| no_license | leokacic/Idea | 637ee7e9c11507c231c6cb9e5b853791f61467e3 | 3008e3bf805199192067fdea09545e4066eae92b | refs/heads/master | 2023-01-05T16:34:36.581566 | 2020-11-03T08:18:58 | 2020-11-03T08:18:58 | 309,618,943 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 222 | java | package com.example.springtestna;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringTestnaApplicationTests {
@Test
void contextLoads() {
}
}
| [
"[email protected]"
]
| |
6d8ff6c216a8ebd6e40bf3a7e5fc9d803d76baf3 | 0d1caf10516a53cf2de82cabe329cb565911554d | /src/main/java/ru/johnspade/web/controller/PostController.java | 8ff3e25db7e29119762b718230ad19ce5370552c | []
| no_license | johnspade/blog | 4b069c8ded01113f8a325f924d69842771eb9016 | a34b00b69afe88c316d6323f9c818c2a323e10ab | refs/heads/master | 2021-01-18T23:50:35.130549 | 2016-12-25T11:06:30 | 2016-12-25T16:24:53 | 51,226,662 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,222 | java | package ru.johnspade.web.controller;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.rometools.utils.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import ru.johnspade.dao.Post;
import ru.johnspade.dao.Tag;
import ru.johnspade.service.PostService;
import ru.johnspade.service.TagService;
import ru.johnspade.web.PostModel;
import ru.johnspade.web.ResourceNotFoundException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;
@Controller
public class PostController {
private static final int RELATED_COUNT = 4;
private final PostService postService;
private final TagService tagService;
@Autowired
public PostController(PostService postService, TagService tagService) {
this.postService = postService;
this.tagService = tagService;
}
@RequestMapping(value = "/new", method = RequestMethod.GET)
public String create(Model model) {
model.addAttribute("post", new PostModel());
return "edit";
}
@RequestMapping(value = "/posts/{id}", method = RequestMethod.GET)
public String read(@PathVariable int id, Model model) {
if (postService.exists(id)) {
final Post post = postService.get(id);
List<Post> posts = new ArrayList<>(postService.findAll());
Iterables.removeIf(posts, new Predicate<Post>() {
@Override
public boolean apply(Post postObject) {
return post.getId() == postObject.getId();
}
});
List<Post> related = new ArrayList<>(RELATED_COUNT);
Random random = new Random();
int count = RELATED_COUNT < posts.size() ? RELATED_COUNT : posts.size();
for (int i = 0; i < count; i++) {
int n = random.nextInt(posts.size());
related.add(posts.get(n));
posts.remove(n);
}
model.addAttribute("post", new PostModel(post));
model.addAttribute("related", related);
final Calendar cal = Calendar.getInstance();
cal.setTime(post.getDate());
model.addAttribute("tree", postService.getTree(cal));
}
else
throw new ResourceNotFoundException("Пост не найден");
return "post";
}
@RequestMapping(value = "/posts/{id}/edit", method = RequestMethod.GET)
public String update(@PathVariable int id, Model model) {
if (postService.exists(id))
model.addAttribute("post", new PostModel(postService.get(id)));
else
throw new ResourceNotFoundException("Пост не найден");
return "edit";
}
@RequestMapping(value = "/posts/{id}/delete", method = RequestMethod.DELETE)
public String delete(@PathVariable int id) {
postService.delete(postService.get(id));
return "redirect:/";
}
@RequestMapping(value = "/save", method = RequestMethod.POST, params = "action=save")
public String save(@ModelAttribute("post") PostModel resource) {
int id = resource.getId();
Post post = postService.exists(id) ? postService.get(id) : new Post();
update(post, resource);
post = postService.save(post);
return "redirect:/posts/" + Integer.toString(post.getId());
}
@RequestMapping(value = "/save", method = RequestMethod.POST, params = "action=preview")
public String preview(@ModelAttribute("post") PostModel resource, Model model) {
model.addAttribute("post", resource);
return "post";
}
private Post update(Post post, PostModel resource) {
post.setTitle(resource.getTitle());
post.setBody(resource.getBody());
String[] tagsArray = resource.getTags().split(",");
List<Tag> postTags = post.getTags();
postTags.clear();
for (String tag : tagsArray) {
String tagName = tag.trim();
if (Strings.isNotEmpty(tagName) && !tagService.exists(tagName))
tagService.save(new Tag(tagName));
if (tagService.exists(tagName)) {
Tag foundTag = tagService.getOne(tagName);
if (!postTags.contains(foundTag))
postTags.add(foundTag);
}
}
post.setDescription(resource.getDescription());
return post;
}
}
| [
"[email protected]"
]
| |
ed0d96910e0e3878ff2831a7f6a2b7a719c5022d | a7059321f71b57dbee7ebb2b28359ce7fd924e87 | /src/main/java/com/example/demo/processor/MySQLProcessor.java | 43cc8b173e43521ef7af673d5c5ca04d65b92e00 | []
| no_license | YerrapothuPavan/SpringCamelMQExample | d4617b4d2ccf295c148ab4c2905259ab3da0dd46 | 2205b69d70211f436cad2daf297a345cde674d19 | refs/heads/master | 2023-07-05T09:39:39.152160 | 2021-08-12T11:27:40 | 2021-08-12T11:27:40 | 328,660,714 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 970 | java | package com.example.demo.processor;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import com.example.demo.exception.DataException;
import com.example.demo.pojo.MyProduct;
@Component
public class MySQLProcessor implements Processor {
public void process(Exchange exchange) throws Exception {
MyProduct product = (MyProduct) exchange.getIn().getBody();
StringBuilder query = new StringBuilder();
if(ObjectUtils.isEmpty(product.getProductId())){
throw new DataException("product id is null for "+product.getDescription());
}
query.append("INSERT INTO PRODUCTS1 (PRODUCTID,DESCRIPTION,BRAND,PRICE) VALUES ('");
query.append(product.getProductId()+"','"+product.getDescription()+"','"+product.getBrand()+"',"+product.getPrice()+")");
System.out.println("Query is : "+query);
exchange.getIn().setBody(query.toString());
}
}
| [
"[email protected]"
]
| |
ec96239a3ba08117a81a639e76cdd42e932a4ae8 | df61a8fdb3fd585c4b241eec32102572aea87c37 | /source-utils/src/main/java/com/source/utils/train/HostUtils.java | 830b885eb649f7927e5cdd722ee2c6124218cb51 | []
| no_license | BigerTeam/source | 81120866f094f41d8af1a028b135cf98441418ec | 9c1b06a7e78b8c9a57acbc7dc4576d2d393c7fc0 | refs/heads/master | 2021-01-06T20:39:50.290484 | 2017-08-14T04:20:13 | 2017-08-14T04:20:13 | 99,539,114 | 7 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,884 | java | package com.source.utils.train;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class HostUtils {
public static final String hostFilePath = "C:\\Windows\\System32\\drivers\\etc\\hosts";
// public static final String hostFilePath="/etc/hosts";
public static void addHostBinding(String ip, String host) {
Map<String, String> hostToIpMap = readFromIpHostFile();
hostToIpMap.put(host, ip);
writeIpHostToReader(hostToIpMap);
}
public static void deleteHostBinding(String ip, String host) {
Map<String, String> hostToIpMap = readFromIpHostFile();
if (hostToIpMap != null && hostToIpMap.containsKey(host)) {
hostToIpMap.remove(host);
}
writeIpHostToReader(hostToIpMap);
}
public static Map<String, String> readFromIpHostFile() {
Map<String, String> hostToIpMap = new HashMap<String, String>();
BufferedReader bufferReader = null;
try {
bufferReader = new BufferedReader(new FileReader(hostFilePath));
String str = null;
while ((str = bufferReader.readLine()) != null) {
if (str != null) {
String[] ipAndHost = str.split(" ");
if (ipAndHost != null && ipAndHost.length == 2 && ipAndHost[0] != null
&& ipAndHost[0].charAt(0) != '#') {
hostToIpMap.put(ipAndHost[1], ipAndHost[0]);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferReader.close();
} catch (Exception e) {
}
}
return hostToIpMap;
}
public static void writeIpHostToReader(Map<String, String> hostToIpMap) {
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter(new FileWriter(hostFilePath));
Iterator<Entry<String, String>> iter = hostToIpMap.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, String> entry = iter.next();
bufferedWriter.write(entry.getValue() + " " + entry.getKey() + "\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferedWriter.close();
} catch (Exception e) {
}
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void jdkDnsNoCache()
throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Class clazz = java.net.InetAddress.class;
final Field cacheField = clazz.getDeclaredField("addressCache");
cacheField.setAccessible(true);
final Object o = cacheField.get(clazz);
Class clazz2 = o.getClass();
final Field cacheMapField = clazz2.getDeclaredField("cache");
cacheMapField.setAccessible(true);
final Map cacheMap = (Map) cacheMapField.get(o);
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
synchronized (o) {// 同步是必须的,因为o可能会有多个线程同时访问修改。
// cacheMap.clear();//这步比较关键,用于清除原来的缓存
cacheMap.remove("kyfw.12306.cn");
}
} catch (Throwable te) {
throw new RuntimeException(te);
}
return null;
}
});
}
public static void test() throws IOException, InterruptedException {
addHostBinding("127.0.0.1", "www.baidu.com");
deleteHostBinding("127.0.0.1", "www.baidu.com");
try {
jdkDnsNoCache();
} catch (Exception e) {
e.printStackTrace();
}
InetAddress address = InetAddress.getByName("www.baidu.com");
System.out.println(System.currentTimeMillis() + ":::" + address.getHostAddress());
}
}
| [
"zhuyangxu@[email protected]"
]
| zhuyangxu@[email protected] |
38a104828e1cc93ff7e8d8f1f4bee447e5d61126 | 99a65a15d223a571bb09a81033b7f8a58a3bc55e | /filescatalog/app/src/androidTest/java/ro/alexpopa/filescatalog/ExampleInstrumentedTest.java | 601d0d5ddd71e14a281d032478b69dfa4bbab415 | []
| no_license | alexovidiupopa/mobile | a58373c4fd3c2d43f67f88448dafce47668f2516 | 984f53c4f8d8ec7408a9a02d31e1e5befa307af1 | refs/heads/master | 2023-02-17T06:58:33.364663 | 2021-01-19T07:58:23 | 2021-01-19T07:58:23 | 326,652,838 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 762 | java | package ro.alexpopa.filescatalog;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("ro.alexpopa.filescatalog", appContext.getPackageName());
}
} | [
"[email protected]"
]
| |
e756f04247358b44f719582437ae132629f85570 | 0af8b92686a58eb0b64e319b22411432aca7a8f3 | /large-multiproject/project15/src/main/java/org/gradle/test/performance15_5/Production15_467.java | 03c0a467fe31db4d96296b8350a7a2e3551fac3e | []
| no_license | gradle/performance-comparisons | b0d38db37c326e0ce271abebdb3c91769b860799 | e53dc7182fafcf9fedf07920cbbea8b40ee4eef4 | refs/heads/master | 2023-08-14T19:24:39.164276 | 2022-11-24T05:18:33 | 2022-11-24T05:18:33 | 80,121,268 | 17 | 15 | null | 2022-09-30T08:04:35 | 2017-01-26T14:25:33 | null | UTF-8 | Java | false | false | 303 | java | package org.gradle.test.performance15_5;
public class Production15_467 extends org.gradle.test.performance9_5.Production9_467 {
private final String property;
public Production15_467() {
this.property = "foo";
}
public String getProperty() {
return property;
}
}
| [
"[email protected]"
]
| |
57c1763e5145dd45952ebe028c0da82fef0c7625 | f251908eb932c00a3a99f8909d2873f3f88db575 | /src/main/java/org/chuckame/dofus2/protocol/types/game/look/SubEntity.java | 0cc73420e875bee5fa0eb1c2ffbc5074dd661c16 | []
| no_license | Chuckame/dofus-protocol | 613c6e27f67ef24b4ec0eb3acf74e3adae859e7c | 5d96fb83929e0fd4f58492d8445cbb7b7181af8f | refs/heads/master | 2021-07-05T16:21:00.824668 | 2017-07-27T13:12:22 | 2017-07-27T13:37:12 | 96,158,319 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,764 | java | package org.chuckame.dofus2.protocol.types.game.look;
import org.chuckame.dofus2.common.io.IDataReader;
import org.chuckame.dofus2.common.io.IDataWriter;
import org.chuckame.dofus2.common.io.INetworkType;
import org.chuckame.dofus2.protocol.types.game.look.EntityLook;
import lombok.Data;
import lombok.ToString;
import lombok.EqualsAndHashCode;
@Data
@ToString
@EqualsAndHashCode
public class SubEntity implements INetworkType {
public static final short TYPE_ID = 54;
private byte bindingPointCategory;
private byte bindingPointIndex;
private EntityLook subEntityLook;
public SubEntity() {
}
public SubEntity(byte bindingPointCategory, byte bindingPointIndex, EntityLook subEntityLook) {
this.bindingPointCategory = bindingPointCategory;
this.bindingPointIndex = bindingPointIndex;
this.subEntityLook = subEntityLook;
}
public short getProtocolTypeId() {
return TYPE_ID;
}
public void deserialize(IDataReader reader) {
this.bindingPointCategory = reader.readSByte();
if (bindingPointCategory < 0)
throw new IllegalArgumentException(String.format("Forbidden value on bindingPointCategory = %s, it doesn't respect the following condition : bindingPointCategory < 0", bindingPointCategory));
this.bindingPointIndex = reader.readSByte();
if (bindingPointIndex < 0)
throw new IllegalArgumentException(String.format("Forbidden value on bindingPointIndex = %s, it doesn't respect the following condition : bindingPointIndex < 0", bindingPointIndex));
this.subEntityLook = new EntityLook();
this.subEntityLook.deserialize(reader);
}
public void serialize(IDataWriter writer) {
writer.writeSByte(this.bindingPointCategory);
writer.writeSByte(this.bindingPointIndex);
this.subEntityLook.serialize(writer);
}
} | [
"[email protected]"
]
| |
0d6e88369d5c44294a6d98920611f79a98ef5b60 | 166f53bbb9a13ff2d67ff67c0d358ef601604828 | /app/src/main/java/com/auxomate/mynewself/mynewself/activities/HomeActivity.java | 2c5bfa81941cf60dcd65d4ab04019851349185a2 | []
| no_license | auxoadmin/auxomate-master | 7fa59494d3ef1231c365aeef73639ff4ce8e05f6 | c619c13b34477397f60c8b8c6fe548cc01fc1972 | refs/heads/master | 2020-04-06T15:42:15.825442 | 2018-11-14T18:00:06 | 2018-11-14T18:00:06 | 157,589,465 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,404 | java | package com.auxomate.mynewself.mynewself.activities;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.app.ActionBar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
import com.auxomate.mynewself.mynewself.dashboard.Dashboard;
import com.auxomate.mynewself.mynewself.utilities.ClearPrefReceiver;
import com.auxomate.mynewself.mynewself.utilities.PrefManager;
import com.auxomate.mynewself.mynewself.R;
import com.auxomate.mynewself.mynewself.fragments.UserprofileFragment;
import com.auxomate.mynewself.mynewself.fragments.ActFragment;
import com.auxomate.mynewself.mynewself.fragments.AspireFragment;
import com.auxomate.mynewself.mynewself.fragments.AwareFragment;
import com.auxomate.mynewself.mynewself.utilities.auxomate;
import com.theartofdev.edmodo.cropper.CropImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
public class HomeActivity extends FragmentActivity {
AspireFragment aspireFragment = new AspireFragment();
ActFragment actFragment = new ActFragment();
AwareFragment awareFragment = new AwareFragment();
Button aware,aspire,act;
ArrayList<String> menuList = new ArrayList<>(); //menu titles
ArrayList<Integer> imagesList = new ArrayList<>(); //menu backgrounds
ArrayList<Fragment> fragmentsList = new ArrayList<>();
public static Context contextOfApplication;
public static Context getContextOfApplication()
{
return contextOfApplication;
}
FragmentManager fragmentManager= getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
public String fromWhere="";
ActionBar toolbar ;
// private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
// = new BottomNavigationView.OnNavigationItemSelectedListener() {
//
// @Override
// public boolean onNavigationItemSelected(@NonNull MenuItem item) {
// FragmentManager fragmentManager= getSupportFragmentManager();
// FragmentTransaction transaction = fragmentManager.beginTransaction();
// switch (item.getItemId()) {
// case R.id.navigation_aware:
// transaction.replace(R.id.container,new AwareFragment()).commit();
//
// // toolbar.setTitle("Aware");
// return true;
// case R.id.navigation_aspire:
//
// transaction.replace(R.id.container,new AspireFragment()).commit();
//
// // toolbar.setTitle("Aspire");
// return true;
// case R.id.navigation_act:
// transaction.replace(R.id.container,actFragment).commit();
//
// // toolbar.setTitle("Act");
// return true;
// case R.id.navigation_userprofile:
// transaction.replace(R.id.container,new UserprofileFragment()).commit();
// item.setTitle(PrefManager.getString(HomeActivity.this,PrefManager.PRF_USERNAME_WELCOME));
//
//
// // toolbar.setTitle("User Profile");
// return true;
// }
// return false;
// }
// };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
schedAlarm(this);
menuList.add("Aware"); //add titles
menuList.add("Aspire");
menuList.add("Act");
menuList.add(PrefManager.getString(this,PrefManager.PRF_USERNAME_WELCOME));
// aware = findViewById(R.id.home_AwareFrag);
// aware.setOnClickListener(this);
// aspire=findViewById(R.id.home_AspireFrag);
// aspire.setOnClickListener(this);
// act=findViewById(R.id.home_ActFrag);
// act.setOnClickListener(this);
imagesList.add(R.drawable.aware11); //add background images
imagesList.add(R.drawable.aspire11);
imagesList.add(R.drawable.act11);
imagesList.add(R.drawable.user_profile11);
fragmentsList.add(AwareFragment.newInstance("aware")); //add fragment instances
fragmentsList.add(aspireFragment);
fragmentsList.add(actFragment);
fragmentsList.add(UserprofileFragment.newInstance("User Profile"));
//toolbar = findViewById(R.id.toolbar);
//
Dashboard auxomate = Dashboard.initialize(HomeActivity.this, menuList, imagesList, fragmentsList);
auxomate.start();
contextOfApplication = getApplicationContext();
// toolbar = getSupportActionBar();
// BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
//
//
// aspireFragment = new AspireFragment();
// actFragment = new ActFragment();
//
//
//
// //navigation.setOnNavigationItemSelectedListener();
// navigation.setSelectedItemId(R.id.navigation_act);
//
// navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
//
// transaction.replace(R.id.container,actFragment).commit();
// toolbar.setTitle("Act");
}
// @Override
// public void onClick(View v) {
//// FragmentManager fragmentManager= getSupportFragmentManager();
//// FragmentTransaction transaction = fragmentManager.beginTransaction();
// switch (v.getId()){
// case R.id.home_AwareFrag:
// transaction.replace(R.id.container,new AwareFragment()).commit();
//
// //toolbar.setTitle("Aware");
//
// break;
// case R.id.home_AspireFrag:
// transaction.replace(R.id.container,new AspireFragment()).commit();
//
// // toolbar.setTitle("Aspire");
// break;
// case R.id.home_ActFrag:
// transaction.replace(R.id.container,new ActFragment()).commit();
//
// // toolbar.setTitle("Act");
// break;
// }
//
// }
private void schedAlarm(Context context) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.DAY_OF_MONTH, 1);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, new Intent(context, ClearPrefReceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000*60*60*24, pi);
}
}
| [
"[email protected]"
]
| |
72de5ba747493611875f1cc0020d1518ef3e6769 | 999886fcec4744ca27379f77132e31f60435ffaf | /excel-upload-download/src/main/java/com/springmvc/util/Constant.java | 6c47745283d67e808dea9d639ccade7179bbad10 | []
| no_license | liulnngit/test | 3d2ab0f7f3b1c0f9daa620fbd6f8ebcee62b9015 | 898b981382a830a842588b1cdc4ef5844a29a58e | refs/heads/master | 2021-06-24T08:43:55.071236 | 2019-03-14T03:19:32 | 2019-03-14T03:19:32 | 129,596,988 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 184 | java | package com.springmvc.util;
/**
* 常量字符串
* @author jesse
*
*/
public class Constant {
public static final String DOWNLOAD_PATH="H:\\mytest\\dir\\";
}
| [
"[email protected]"
]
| |
85ee48e053f562c9c7466f88f434e17ce9be67dd | 78581b0bd67948903c728058203fb99c96342f0c | /Chitunion/Web(java)/src/main/java/com/xyauto/util/CookiesUtil.java | af88280b26ac93787bd72832629754d748c2c7fc | []
| no_license | godamos/Repository-Privious | 4a5f7ef47d995b467f9eb52b96fb35062b295661 | f9632fcca7d0784db6d7a8368041310cdec7dec1 | refs/heads/master | 2023-03-19T10:24:25.523350 | 2020-08-29T21:58:41 | 2020-08-29T21:58:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,280 | java | package com.xyauto.util;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CookiesUtil {
private final static String DOMAIN = "chitunion.com";
private final static String PATH = "/";
public static boolean setCookieValue(HttpServletResponse response, String key, String value) {
return setCookieValue(response, key, value, PATH, DOMAIN);
}
public static boolean setCookieValue(HttpServletResponse response, String key, String value, String path,
String domain) {
try {
Cookie cookie = new Cookie(key, value);
cookie.setPath(path);// very important
cookie.setDomain(domain);
cookie.setMaxAge(-1);
response.addCookie(cookie);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static String getCookieValue(HttpServletRequest request, String key) {
try {
Cookie[] cookies = request.getCookies();
if (cookies == null)
return "";
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (key.equals(cookie.getName()))
return (cookie.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
| [
"[email protected]"
]
| |
a0b448a186b44dcc09455039cac9311a87def793 | 884ffe90c0c65c8dd5c5211264c878760f5613c8 | /處理CSV/java導入CSV.java | b17fd12df694011d7d7b5c3cc197c602ed0ba5e2 | []
| no_license | LIOU2021/other | 467bfb849ab49f492b35ad42e2975bbc5f2f82f1 | 921354945b03cdffd618fb2a985b2d61d3b2b4d9 | refs/heads/main | 2023-06-24T15:14:19.964334 | 2021-07-20T16:53:51 | 2021-07-20T16:53:51 | 338,016,998 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,261 | java | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class java導入CSV {
public static void main(String[] args) {
try {
URL url = new URL("https://data.kcg.gov.tw/dataset/5936f124-dc59-44b4-a731-997d8ba85279/resource/7053bfe4-5ef6-417f-900e-55a83fefb0db/download/110131.csv");
InputStream openStream = url.openStream();//開啟連結
InputStreamReader isr = new InputStreamReader(openStream,"UTF-8");//因為政府資料平台是BIG5
BufferedReader br = new BufferedReader(isr);
String str="";
while((str=br.readLine())!=null) {
String[] split = str.split(",");
for(String string : split) {
System.out.print(string+" ");
}
System.out.println();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
單位別
109年新竹縣政府核定公教人員退休人數
"本府暨所屬(不含警察局及各公所)"
"19"
"警察局"
"16"
"國中小"
"68"
"合計"
"103"
*/ | [
"[email protected]"
]
| |
6d118ee23e0dcfa878041849b851cf29d6dbbd26 | 7d5920809b5628e775d34c4b09315c135fdbcf1f | /transportable-udfs-examples/transportable-udfs-example-udfs/src/test/java/com/linkedin/transport/examples/TestMapValuesFunction.java | 70f0105810c8b1ee6b11a4dcb60328c2c0c49f3c | [
"Apache-2.0",
"BSD-2-Clause"
]
| permissive | linkedin/transport | 124d54f2232709ae755edb99c47b0a7f0c736c8e | 1adf4f4a7d38a5a46d9f57f38e1d68f348b9ad44 | refs/heads/master | 2023-09-06T09:09:45.627966 | 2023-06-08T12:26:38 | 2023-06-08T12:26:38 | 157,273,136 | 285 | 79 | BSD-2-Clause | 2023-06-08T20:41:00 | 2018-11-12T20:34:12 | Java | UTF-8 | Java | false | false | 1,314 | java | /**
* Copyright 2018 LinkedIn Corporation. All rights reserved.
* Licensed under the BSD-2 Clause license.
* See LICENSE in the project root for license information.
*/
package com.linkedin.transport.examples;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.linkedin.transport.api.udf.StdUDF;
import com.linkedin.transport.api.udf.TopLevelStdUDF;
import com.linkedin.transport.test.AbstractStdUDFTest;
import com.linkedin.transport.test.spi.StdTester;
import java.util.List;
import java.util.Map;
import org.testng.annotations.Test;
public class TestMapValuesFunction extends AbstractStdUDFTest {
@Override
protected Map<Class<? extends TopLevelStdUDF>, List<Class<? extends StdUDF>>> getTopLevelStdUDFClassesAndImplementations() {
return ImmutableMap.of(MapValuesFunction.class, ImmutableList.of(MapValuesFunction.class));
}
@Test
public void testMapValues() {
StdTester tester = getTester();
tester.check(functionCall("std_map_values", map(1, 4, 2, 5, 3, 6)), array(4, 5, 6), "array(integer)");
tester.check(functionCall("std_map_values", map("1", "4", "2", "5", "3", "6")), array("4", "5", "6"),
"array(varchar)");
tester.check(functionCall("std_map_values", (Object) null), null, "array(unknown)");
}
}
| [
"[email protected]"
]
| |
e389d0d6879a2ddaa6646a7ed5f51599700d4b8d | abc4dbcc76e3e595ba337c94c24585f7e40b6310 | /SmartHome/src/nguyenquytu/slidingmenu/PullToRefreshListView.java | 9fff6c2dc85028e05a88b5520466fa24c53579e1 | []
| no_license | quytutlu/SmartHome_Android | 6e6bd045b4d6354efcf7cd02dba6479eb10b7b86 | 2ba2ee5ab7b9feab468185381e35d7bc3cb6053f | refs/heads/master | 2016-09-05T12:14:15.384962 | 2015-09-22T18:15:55 | 2015-09-22T18:15:55 | 42,950,239 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 14,229 | java | package nguyenquytu.slidingmenu;
import nguyenquytu.smarthome.R;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class PullToRefreshListView extends ListView implements OnScrollListener {
private static final int TAP_TO_REFRESH = 1;
private static final int PULL_TO_REFRESH = 2;
private static final int RELEASE_TO_REFRESH = 3;
private static final int REFRESHING = 4;
private static final String TAG = "PullToRefreshListView";
private OnRefreshListener mOnRefreshListener;
/**
* Listener that will receive notifications every time the list scrolls.
*/
private OnScrollListener mOnScrollListener;
private LayoutInflater mInflater;
private RelativeLayout mRefreshView;
private TextView mRefreshViewText;
private ImageView mRefreshViewImage;
private ProgressBar mRefreshViewProgress;
private TextView mRefreshViewLastUpdated;
private int mCurrentScrollState;
private int mRefreshState;
private RotateAnimation mFlipAnimation;
private RotateAnimation mReverseFlipAnimation;
private int mRefreshViewHeight;
private int mRefreshOriginalTopPadding;
private int mLastMotionY;
private boolean mBounceHack;
public PullToRefreshListView(Context context) {
super(context);
init(context);
}
public PullToRefreshListView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public PullToRefreshListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
// Load all of the animations we need in code rather than through XML
mFlipAnimation = new RotateAnimation(0, -180,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
mFlipAnimation.setInterpolator(new LinearInterpolator());
mFlipAnimation.setDuration(250);
mFlipAnimation.setFillAfter(true);
mReverseFlipAnimation = new RotateAnimation(-180, 0,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
mReverseFlipAnimation.setInterpolator(new LinearInterpolator());
mReverseFlipAnimation.setDuration(250);
mReverseFlipAnimation.setFillAfter(true);
mInflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
mRefreshView = (RelativeLayout) mInflater.inflate(
R.layout.pull_to_refresh_header, this, false);
mRefreshViewText =
(TextView) mRefreshView.findViewById(R.id.pull_to_refresh_text);
mRefreshViewImage =
(ImageView) mRefreshView.findViewById(R.id.pull_to_refresh_image);
mRefreshViewProgress =
(ProgressBar) mRefreshView.findViewById(R.id.pull_to_refresh_progress);
mRefreshViewLastUpdated =
(TextView) mRefreshView.findViewById(R.id.pull_to_refresh_updated_at);
mRefreshViewImage.setMinimumHeight(50);
mRefreshView.setOnClickListener(new OnClickRefreshListener());
mRefreshOriginalTopPadding = mRefreshView.getPaddingTop();
mRefreshState = TAP_TO_REFRESH;
addHeaderView(mRefreshView);
super.setOnScrollListener(this);
measureView(mRefreshView);
mRefreshViewHeight = mRefreshView.getMeasuredHeight();
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
setSelection(1);
}
@Override
public void setAdapter(ListAdapter adapter) {
super.setAdapter(adapter);
setSelection(1);
}
/**
* Set the listener that will receive notifications every time the list
* scrolls.
*
* @param l The scroll listener.
*/
@Override
public void setOnScrollListener(AbsListView.OnScrollListener l) {
mOnScrollListener = l;
}
/**
* Register a callback to be invoked when this list should be refreshed.
*
* @param onRefreshListener The callback to run.
*/
public void setOnRefreshListener(OnRefreshListener onRefreshListener) {
mOnRefreshListener = onRefreshListener;
}
/**
* Set a text to represent when the list was last updated.
* @param lastUpdated Last updated at.
*/
public void setLastUpdated(CharSequence lastUpdated) {
if (lastUpdated != null) {
mRefreshViewLastUpdated.setVisibility(View.VISIBLE);
mRefreshViewLastUpdated.setText(lastUpdated);
} else {
mRefreshViewLastUpdated.setVisibility(View.GONE);
}
}
@SuppressLint("ClickableViewAccessibility") @Override
public boolean onTouchEvent(MotionEvent event) {
final int y = (int) event.getY();
mBounceHack = false;
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
if (!isVerticalScrollBarEnabled()) {
setVerticalScrollBarEnabled(true);
}
if (getFirstVisiblePosition() == 0 && mRefreshState != REFRESHING) {
if ((mRefreshView.getBottom() >= mRefreshViewHeight
|| mRefreshView.getTop() >= 0)
&& mRefreshState == RELEASE_TO_REFRESH) {
// Initiate the refresh
mRefreshState = REFRESHING;
prepareForRefresh();
onRefresh();
} else if (mRefreshView.getBottom() < mRefreshViewHeight
|| mRefreshView.getTop() <= 0) {
// Abort refresh and scroll down below the refresh view
resetHeader();
setSelection(1);
}
}
break;
case MotionEvent.ACTION_DOWN:
mLastMotionY = y;
break;
case MotionEvent.ACTION_MOVE:
applyHeaderPadding(event);
break;
}
return super.onTouchEvent(event);
}
private void applyHeaderPadding(MotionEvent ev) {
// getHistorySize has been available since API 1
int pointerCount = ev.getHistorySize();
for (int p = 0; p < pointerCount; p++) {
if (mRefreshState == RELEASE_TO_REFRESH) {
if (isVerticalFadingEdgeEnabled()) {
setVerticalScrollBarEnabled(false);
}
int historicalY = (int) ev.getHistoricalY(p);
// Calculate the padding to apply, we divide by 1.7 to
// simulate a more resistant effect during pull.
int topPadding = (int) (((historicalY - mLastMotionY)
- mRefreshViewHeight) / 1.7);
mRefreshView.setPadding(
mRefreshView.getPaddingLeft(),
topPadding,
mRefreshView.getPaddingRight(),
mRefreshView.getPaddingBottom());
}
}
}
/**
* Sets the header padding back to original size.
*/
private void resetHeaderPadding() {
mRefreshView.setPadding(
mRefreshView.getPaddingLeft(),
mRefreshOriginalTopPadding,
mRefreshView.getPaddingRight(),
mRefreshView.getPaddingBottom());
}
/**
* Resets the header to the original state.
*/
private void resetHeader() {
if (mRefreshState != TAP_TO_REFRESH) {
mRefreshState = TAP_TO_REFRESH;
resetHeaderPadding();
// Set refresh view text to the pull label
mRefreshViewText.setText("Tap to refresh...");
// Replace refresh drawable with arrow drawable
mRefreshViewImage.setImageResource(R.drawable.ic_pulltorefresh_arrow);
// Clear the full rotation animation
mRefreshViewImage.clearAnimation();
// Hide progress bar and arrow.
mRefreshViewImage.setVisibility(View.GONE);
mRefreshViewProgress.setVisibility(View.GONE);
}
}
@SuppressWarnings("deprecation")
private void measureView(View child) {
ViewGroup.LayoutParams p = child.getLayoutParams();
if (p == null) {
p = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
int childWidthSpec = ViewGroup.getChildMeasureSpec(0,
0 + 0, p.width);
int lpHeight = p.height;
int childHeightSpec;
if (lpHeight > 0) {
childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
}
child.measure(childWidthSpec, childHeightSpec);
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// When the refresh view is completely visible, change the text to say
// "Release to refresh..." and flip the arrow drawable.
if (mCurrentScrollState == SCROLL_STATE_TOUCH_SCROLL
&& mRefreshState != REFRESHING) {
if (firstVisibleItem == 0) {
mRefreshViewImage.setVisibility(View.VISIBLE);
if ((mRefreshView.getBottom() >= mRefreshViewHeight + 20
|| mRefreshView.getTop() >= 0)
&& mRefreshState != RELEASE_TO_REFRESH) {
mRefreshViewText.setText("Release to refresh...");
mRefreshViewImage.clearAnimation();
mRefreshViewImage.startAnimation(mFlipAnimation);
mRefreshState = RELEASE_TO_REFRESH;
} else if (mRefreshView.getBottom() < mRefreshViewHeight + 20
&& mRefreshState != PULL_TO_REFRESH) {
mRefreshViewText.setText("Pull to refresh...");
if (mRefreshState != TAP_TO_REFRESH) {
mRefreshViewImage.clearAnimation();
mRefreshViewImage.startAnimation(mReverseFlipAnimation);
}
mRefreshState = PULL_TO_REFRESH;
}
} else {
mRefreshViewImage.setVisibility(View.GONE);
resetHeader();
}
} else if (mCurrentScrollState == SCROLL_STATE_FLING
&& firstVisibleItem == 0
&& mRefreshState != REFRESHING) {
setSelection(1);
mBounceHack = true;
} else if (mBounceHack && mCurrentScrollState == SCROLL_STATE_FLING) {
setSelection(1);
}
if (mOnScrollListener != null) {
mOnScrollListener.onScroll(view, firstVisibleItem,
visibleItemCount, totalItemCount);
}
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
mCurrentScrollState = scrollState;
if (mCurrentScrollState == SCROLL_STATE_IDLE) {
mBounceHack = false;
}
if (mOnScrollListener != null) {
mOnScrollListener.onScrollStateChanged(view, scrollState);
}
}
public void prepareForRefresh() {
resetHeaderPadding();
mRefreshViewImage.setVisibility(View.GONE);
// We need this hack, otherwise it will keep the previous drawable.
mRefreshViewImage.setImageDrawable(null);
mRefreshViewProgress.setVisibility(View.VISIBLE);
// Set refresh view text to the refreshing label
mRefreshViewText.setText("Loading...");
mRefreshState = REFRESHING;
}
public void onRefresh() {
Log.d(TAG, "onRefresh");
if (mOnRefreshListener != null) {
mOnRefreshListener.onRefresh();
}
}
/**
* Resets the list to a normal state after a refresh.
* @param lastUpdated Last updated at.
*/
public void onRefreshComplete(CharSequence lastUpdated) {
setLastUpdated(lastUpdated);
onRefreshComplete();
}
/**
* Resets the list to a normal state after a refresh.
*/
public void onRefreshComplete() {
Log.d(TAG, "onRefreshComplete");
resetHeader();
// If refresh view is visible when loading completes, scroll down to
// the next item.
if (mRefreshView.getBottom() > 0) {
invalidateViews();
setSelection(1);
}
}
/**
* Invoked when the refresh view is clicked on. This is mainly used when
* there's only a few items in the list and it's not possible to drag the
* list.
*/
private class OnClickRefreshListener implements OnClickListener {
public void onClick(View v) {
if (mRefreshState != REFRESHING) {
prepareForRefresh();
onRefresh();
}
}
}
/**
* Interface definition for a callback to be invoked when list should be
* refreshed.
*/
public interface OnRefreshListener {
/**
* Called when the list should be refreshed.
* <p>
* A call to {@link PullToRefreshListView #onRefreshComplete()} is
* expected to indicate that the refresh has completed.
*/
public void onRefresh();
}
}
| [
"[email protected]"
]
| |
19136ada7807265f6204a96c1c110e750d073516 | 540089061a1bc4c31056f44fe486da4100e261a4 | /src/main/java/com/chenyl/module/base/abstractAndinterface/StreamTest.java | df86f8c885780b24289205f6b75b4cc28727c72f | []
| no_license | chenyongliangbj/wise-base-module | fbdb5b8aada50e052d7e5f206da0ae9959a4e7f9 | e53469bbbed9489fc03bd61ae9b0dcaa2802eea3 | refs/heads/master | 2022-12-21T04:51:37.769150 | 2021-01-29T02:21:12 | 2021-01-29T02:21:12 | 178,314,923 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,551 | java | package com.chenyl.module.base.abstractAndinterface;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* Stream
**/
public class StreamTest {
public static void main(String[] args){
List<Integer> list = Arrays.asList(8,3,4,6,7,9,1);
/**测试终止操作*/
//1.判断所有值为偶数
boolean a = list.stream().allMatch(num -> num % 2 == 0);
System.out.println(a);//false
//2.判断存在数值为偶数
boolean b = list.stream().anyMatch(num -> num % 2 == 0);
System.out.println(b);//true
//3.判断不存在大于10的数
boolean c = list.stream().noneMatch(num -> num > 10);
System.out.println(c);//true
//3.返回第一个元素
Optional<Integer> d = list.stream().findFirst();
System.out.println(d.get());//8
//4.返回任意元素
Optional<Integer> e = list.stream().findAny();
System.out.println(e.get());//找不到就抛出异常,最好设置默认值
Integer e1 = list.stream().findAny().orElse(0);
System.out.println(e1);
//5.count 统计数量
long f = list.stream().count();
System.out.println(f);//7
//6.返回最大值
Optional<Integer> max = list.stream().max(Integer::compareTo);
System.out.println(max.get());//9
//7.返回最小值
Optional<Integer> min = list.stream().min(Integer::compareTo);
System.out.println(min.get());//1
//8.归约:求最大值
Optional<Integer> reduce = list.stream().reduce((r1, r2) -> r1 >= r2 ? r1 : r2);
System.out.println(reduce.get());//9
//9.收集:偶数列表
List<Integer> evenNum = list.stream().filter(num -> num % 2 == 0).collect(Collectors.toList());
System.out.println(evenNum);//[8, 4, 6]
//10.遍历
list.stream().forEach(System.out::print);//8346791
//11.迭代器
Iterator<Integer> iterator = list.stream().iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next());//8346791
}
//12.toArray
Integer[] array1 = list.stream().toArray(in -> new Integer[list.size()]);
Integer[] array2 = list.stream().toArray(Integer[]::new);
Object[] array3 = list.stream().toArray();
/**测试中间操作*/
//1.filter:过滤
List<Integer> evenNums = list.stream().filter(num -> num % 2 == 0).collect(Collectors.toList());
System.out.println(evenNums);//[8, 4, 6]
//2.map:映射 举例:映射成+2的数据
List<Integer> map1 = list.stream().map(m1 -> m1+2).collect(Collectors.toList());
System.out.println(map1);//[10, 5, 6, 8, 9, 11, 3]
//3.limit:保留前几条
List<Integer> test1 = list.stream().limit(3).collect(Collectors.toList());
System.out.println(test1);//[8, 3, 4]
//4.skip:跳过前几条
List<Integer> test2 = list.stream().skip(3).collect(Collectors.toList());
System.out.println(test2);//[6, 7, 9, 1]
//4.skip:跳过前几条
List<Integer> test3 = list.stream().distinct().collect(Collectors.toList());
System.out.println(test3);//[8, 3, 4, 6, 7, 9, 1] 尴尬,没有重复的数字
//5.sort:排序
List<Integer> test4 = list.stream().sorted().collect(Collectors.toList());
System.out.println(test4);//[1, 3, 4, 6, 7, 8, 9]
}
}
| [
"[email protected]"
]
| |
3dfe533db0a49448c6d48bed69992802eaba0ef4 | 366aec26c921e77c211905b93e1f04743199684e | /src/com/igomall/controller/admin/ReviewController.java | 94272c7b8532e91103d9c64642a77940eb410b1a | []
| no_license | cloudgoon/mall-1 | 492dbdb6b8b71f40cad66e325c5e55218e11db54 | 3340c8cc16418ee8f986c8f181f634e3abcf90ab | refs/heads/master | 2021-05-16T19:59:24.613232 | 2019-10-12T07:52:27 | 2019-10-12T07:52:27 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,001 | java |
package com.igomall.controller.admin;
import javax.inject.Inject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.igomall.Message;
import com.igomall.Pageable;
import com.igomall.entity.Review;
import com.igomall.service.ReviewService;
/**
* Controller - 评论
*
* @author IGOMALL Team
* @version 1.0
*/
@Controller("adminReviewController")
@RequestMapping("/admin/review")
public class ReviewController extends BaseController {
@Inject
private ReviewService reviewService;
/**
* 编辑
*/
@GetMapping("/edit")
public String edit(Long id, ModelMap model) {
model.addAttribute("review", reviewService.find(id));
return "admin/review/edit";
}
/**
* 更新
*/
@PostMapping("/update")
public String update(Long id, @RequestParam(defaultValue = "false") Boolean isShow, RedirectAttributes redirectAttributes) {
Review review = reviewService.find(id);
if (review == null) {
return ERROR_VIEW;
}
review.setIsShow(isShow);
reviewService.update(review);
addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
return "redirect:list";
}
/**
* 列表
*/
@GetMapping("/list")
public String list(Review.Type type, Pageable pageable, ModelMap model) {
model.addAttribute("type", type);
model.addAttribute("types", Review.Type.values());
model.addAttribute("page", reviewService.findPage(null, null, null, type, null, pageable));
return "admin/review/list";
}
/**
* 删除
*/
@PostMapping("/delete")
public @ResponseBody Message delete(Long[] ids) {
reviewService.delete(ids);
return SUCCESS_MESSAGE;
}
} | [
"[email protected]"
]
| |
95fcd794f0b46c073695b8a811fcd0138ea8c21f | c1601e3ba1d74d881efb6bc88732fafe9c4c3caa | /app/src/main/java/com/example/dh/hichat/ui/fragment/ContactFragment.java | 9713854d5eb601b27e66821c98d08bdd4e57346f | []
| no_license | KingOfHui/HiChat | 5696dcaaf4c32cf5c4f6a41ed4c2d5aeeb0236b9 | 038befef2607d13e8d0637a44241f8304716e563 | refs/heads/master | 2021-01-19T13:38:52.119221 | 2017-08-20T17:40:29 | 2017-08-20T17:40:29 | 100,850,533 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 607 | java | package com.example.dh.hichat.ui.fragment;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.dh.hichat.R;
import com.example.dh.hichat.base.BaseFragment;
/**
* Created by DH on 2017/8/10.
*/
public class ContactFragment extends BaseFragment {
@Override
public void setDefaultTitle(TextView tvTitle) {
tvTitle.setText("通讯录");
}
@Override
public void setEmptyView(ImageView ivEmpty, TextView tvInfo) {
ivEmpty.setImageResource(R.drawable.ic_guest_contact_empty);
tvInfo.setText("可以让附近的人互动");
}
}
| [
"[email protected]"
]
| |
399c5aded4b5ad8e2cb161d4f5fc6cba1e40b567 | 103c360c021488a81d3362b84a016ee96187977c | /src/main/java/com/liushijie/annotations/FilterMethods.java | 383c96d725f78c7be3f3f2064d97083709ae16b5 | []
| no_license | ofdata/junit4_ext | a6603727457c7e4c414c775f452583d12def440a | 04784ddc279ab69b2ce96b7bc40a3f69ecfa27cf | refs/heads/master | 2021-01-12T16:26:35.703880 | 2016-09-26T17:24:20 | 2016-09-26T17:24:20 | 69,273,859 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 319 | java | package com.liushijie.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface FilterMethods {
String[] methods();
}
| [
"[email protected]"
]
| |
b109b4398f7ca45c782beb84263754f3c0c1abd6 | 7ded6f38db744877872a63b645ce043dbe21b05d | /whp-container-mapping/src/test/java/org/motechproject/whp/containermapping/service/AdminContainerMappingServiceTest.java | 6efe2875a770730f3f550e1426b615e0449ed480 | []
| no_license | maduhu/motech-whp | 420fa914001abb88f2ec08ff6ddbbcb5b7cf5b36 | 75336e9710cfcc84c5156958b40da3f717866f8a | refs/heads/master | 2021-01-18T05:36:26.653159 | 2014-11-21T10:41:00 | 2014-11-21T10:41:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,392 | java | package org.motechproject.whp.containermapping.service;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.motechproject.whp.containermapping.domain.AdminContainerMapping;
import org.motechproject.whp.containermapping.domain.ContainerRange;
import org.motechproject.whp.containermapping.repository.AllAdminContainerMappings;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
public class AdminContainerMappingServiceTest {
@Mock
AllAdminContainerMappings allAdminContainerMappings;
AdminContainerMappingService adminContainerMappingService;
@Before
public void setUp() {
initMocks(this);
adminContainerMappingService = new AdminContainerMappingService(allAdminContainerMappings);
}
@Test
public void shouldReturnTrueIfContainerIdFallsWithinTheCorrectRangeOfProvider() {
AdminContainerMapping adminContainerMapping = new AdminContainerMapping();
adminContainerMapping.add(new ContainerRange(1000, 2000));
when(allAdminContainerMappings.get()).thenReturn(adminContainerMapping);
assertTrue(adminContainerMappingService.isValidContainer(1234));
assertFalse(adminContainerMappingService.isValidContainer(2234));
}
}
| [
"[email protected]"
]
| |
93057680c54647c07d5c0d63edd41ebd039adf31 | ca9f8c4669cfdbe0a2c52199664382daba32fc85 | /nowBitcamp/javaWork/day09/src/com/bit/day09/Ex07My.java | 9f237242882f0b3900a15b0b46eae1efdf23da60 | []
| no_license | stxz00/bitcamp | 42ed37285bafa5c4434f8cfc5eba230f5108cf1d | 8c26e650599cba8a6c6275e29cdd605c39fe2591 | refs/heads/master | 2023-03-29T23:55:41.355695 | 2021-04-04T20:07:11 | 2021-04-04T20:07:11 | 332,386,386 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 1,487 | java | package com.bit.day09;
//
/*
* 주민번호 체크
* 123456-1234567
*
*
*
*
*
*
*/
public class Ex07My {
public static void main(String[] args) {
int age = 0;
char gender = '-';
String input = null;
java.util.Scanner sc;
sc = new java.util.Scanner(System.in);
boolean boo = false;
do{
System.out.print("주민번호를 입력해주세요\n>");
input = sc.nextLine();
String[] s1 = input.split("-");
String[] s2 = input.split("");
if(s2[6].equals("-") == false) {
System.out.println("7번째 자리에 - 표시하시기 바랍니다");
continue;
}
try {
Integer.parseInt(s1[0]);
Integer.parseInt(s1[1]);
String[] s3 = new String[14];
s3[13] = s2[13]; // 14자리 이내면 인덱스오류
for(int i = 0; i < s2.length; i++) {
s3[i] = s2[i]; // 14자리 초과 시 인덱스 오류
}
}catch(NumberFormatException e){
System.out.println("숫자 이외는 입력할 수 없습니다");
continue;
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("14자리 까지만 입력하세요");
continue;
}
break;
}while(true);
age = 2020-(1900+Integer.parseInt(input.substring(0,2))-1);
if(input.charAt(7) >= '3') {
age -= 100;
}
if(input.charAt(7) == '1' || input.charAt(7) == '3'){
gender = '남';
}else {
gender = '여';
}
System.out.println("당신은 " + age + "세 " + gender + "성 입니다");
sc.close();
}
}
| [
"[email protected]"
]
| |
02af25582af8f88ebaf44e0c4fa075eb9c82e37d | b780b760a17420c9cbbcfdc9cfe58d1c60696113 | /washmall/src/main/java/com/xmkj/washmall/base/utils/Constants.java | aed47fb09b63defb65977aa3b8b5699f46ce34c0 | []
| no_license | hupulin/MyApplication | 70d804b373d65723effffa48b7446b159307f507 | 2db5f5f4c51af47b30370140f749343d4bb5954b | refs/heads/master | 2020-04-13T01:52:21.725658 | 2019-09-11T13:52:57 | 2019-09-11T13:52:57 | 162,886,234 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,925 | java | package com.xmkj.washmall.base.utils;
public final class Constants {
public static final int BASE_ID = 0;
public static final int RQF_PAY = BASE_ID + 1;
public static final int RQF_INSTALL_CHECK = RQF_PAY + 1;
public static final String SERVER_URL = "http://yintong.com.cn/secure_server/x.htm";
public static final String PAY_PACKAGE = "com.yintong.secure";
// 银通支付安全支付服务apk的名称,必须与assets目录下的apk名称一致
public static final String YT_PLUGIN_NAME = "SecurePay.apk";
public static final String RET_CODE_SUCCESS = "0000";// 0000 交易成功
public static final String RET_CODE_PROCESS = "2008";// 2008 支付处理中
public static final String RESULT_PAY_SUCCESS = "SUCCESS";
public static final String RESULT_PAY_PROCESSING = "PROCESSING";
public static final String RESULT_PAY_FAILURE = "FAILURE";
public static final String RESULT_PAY_REFUND = "REFUND";
//异步通知回调地址
public static final String NOTIFY_URL = "http://test.yintong.com.cn:80/apidemo/API_DEMO/notifyUrl.htm";
}
class YTPayDefine {
public static final String IMEI = "imei";
public static final String IMSI = "imsi";
public static final String KEY = "key";
public static final String USER_AGENT = "user_agent";
public static final String VERSION = "version";
public static final String DEVICE = "device";
public static final String SID = "sid";
public static final String PARTNER = "partner";
public static final String TRANSCODE = "transcode";
public static final String CHARSET = "charset";
public static final String SIGN_TYPE = "sign_type";
public static final String SIGN = "sign";
public static final String URL = "URL";
public static final String SPLIT = "&";
public static final String ACTION = "action";
public static final String ACTION_UPDATE = "update";
public static final String DATA = "data";
public static final String PLATFORM = "platform";
}
| [
"[email protected]"
]
| |
df779f7bda533cd0c1f206d1266f6c9c6eb763b4 | b6ea417b48402d85b6fe90299c51411b778c07cc | /spring-core/src/test/java/org/springframework/util/ReflectionUtilsTests.java | 29106a4ca83c5918ac825a7953b6445470136921 | [
"Apache-2.0"
]
| permissive | DevHui/spring-framework | 065f24e96eaaed38495b9d87bc322db82b6a046c | 4a2f291e26c6f78c3875dea13432be21bb1c0ed6 | refs/heads/master | 2020-12-04T21:08:18.445815 | 2020-01-15T03:54:42 | 2020-01-15T03:54:42 | 231,526,595 | 1 | 0 | Apache-2.0 | 2020-01-03T06:28:30 | 2020-01-03T06:28:29 | null | UTF-8 | Java | false | false | 14,972 | java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.util;
import org.hamcrest.Matchers;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.tests.Assume;
import org.springframework.tests.TestGroup;
import org.springframework.tests.sample.objects.TestObject;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.rmi.ConnectException;
import java.rmi.RemoteException;
import java.util.LinkedList;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* @author Rob Harrop
* @author Juergen Hoeller
* @author Sam Brannen
* @author Arjen Poutsma
*/
public class ReflectionUtilsTests {
@Test
public void findField() {
Field field = ReflectionUtils.findField(TestObjectSubclassWithPublicField.class, "publicField", String.class);
assertNotNull(field);
assertEquals("publicField", field.getName());
assertEquals(String.class, field.getType());
assertTrue("Field should be public.", Modifier.isPublic(field.getModifiers()));
field = ReflectionUtils.findField(TestObjectSubclassWithNewField.class, "prot", String.class);
assertNotNull(field);
assertEquals("prot", field.getName());
assertEquals(String.class, field.getType());
assertTrue("Field should be protected.", Modifier.isProtected(field.getModifiers()));
field = ReflectionUtils.findField(TestObjectSubclassWithNewField.class, "name", String.class);
assertNotNull(field);
assertEquals("name", field.getName());
assertEquals(String.class, field.getType());
assertTrue("Field should be private.", Modifier.isPrivate(field.getModifiers()));
}
@Test
public void setField() {
TestObjectSubclassWithNewField testBean = new TestObjectSubclassWithNewField();
Field field = ReflectionUtils.findField(TestObjectSubclassWithNewField.class, "name", String.class);
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, testBean, "FooBar");
assertNotNull(testBean.getName());
assertEquals("FooBar", testBean.getName());
ReflectionUtils.setField(field, testBean, null);
assertNull(testBean.getName());
}
@Test
public void invokeMethod() throws Exception {
String rob = "Rob Harrop";
TestObject bean = new TestObject();
bean.setName(rob);
Method getName = TestObject.class.getMethod("getName");
Method setName = TestObject.class.getMethod("setName", String.class);
Object name = ReflectionUtils.invokeMethod(getName, bean);
assertEquals("Incorrect name returned", rob, name);
String juergen = "Juergen Hoeller";
ReflectionUtils.invokeMethod(setName, bean, juergen);
assertEquals("Incorrect name set", juergen, bean.getName());
}
@Test
public void declaresException() throws Exception {
Method remoteExMethod = A.class.getDeclaredMethod("foo", Integer.class);
assertTrue(ReflectionUtils.declaresException(remoteExMethod, RemoteException.class));
assertTrue(ReflectionUtils.declaresException(remoteExMethod, ConnectException.class));
assertFalse(ReflectionUtils.declaresException(remoteExMethod, NoSuchMethodException.class));
assertFalse(ReflectionUtils.declaresException(remoteExMethod, Exception.class));
Method illegalExMethod = B.class.getDeclaredMethod("bar", String.class);
assertTrue(ReflectionUtils.declaresException(illegalExMethod, IllegalArgumentException.class));
assertTrue(ReflectionUtils.declaresException(illegalExMethod, NumberFormatException.class));
assertFalse(ReflectionUtils.declaresException(illegalExMethod, IllegalStateException.class));
assertFalse(ReflectionUtils.declaresException(illegalExMethod, Exception.class));
}
@Test(expected = IllegalArgumentException.class)
public void copySrcToDestinationOfIncorrectClass() {
TestObject src = new TestObject();
String dest = new String();
ReflectionUtils.shallowCopyFieldState(src, dest);
}
@Test(expected = IllegalArgumentException.class)
public void rejectsNullSrc() {
TestObject src = null;
String dest = new String();
ReflectionUtils.shallowCopyFieldState(src, dest);
}
@Test(expected = IllegalArgumentException.class)
public void rejectsNullDest() {
TestObject src = new TestObject();
String dest = null;
ReflectionUtils.shallowCopyFieldState(src, dest);
}
@Test
public void validCopy() {
TestObject src = new TestObject();
TestObject dest = new TestObject();
testValidCopy(src, dest);
}
@Test
public void validCopyOnSubTypeWithNewField() {
TestObjectSubclassWithNewField src = new TestObjectSubclassWithNewField();
TestObjectSubclassWithNewField dest = new TestObjectSubclassWithNewField();
src.magic = 11;
// Will check inherited fields are copied
testValidCopy(src, dest);
// Check subclass fields were copied
assertEquals(src.magic, dest.magic);
assertEquals(src.prot, dest.prot);
}
@Test
public void validCopyToSubType() {
TestObject src = new TestObject();
TestObjectSubclassWithNewField dest = new TestObjectSubclassWithNewField();
dest.magic = 11;
testValidCopy(src, dest);
// Should have left this one alone
assertEquals(11, dest.magic);
}
@Test
public void validCopyToSubTypeWithFinalField() {
TestObjectSubclassWithFinalField src = new TestObjectSubclassWithFinalField();
TestObjectSubclassWithFinalField dest = new TestObjectSubclassWithFinalField();
// Check that this doesn't fail due to attempt to assign final
testValidCopy(src, dest);
}
private void testValidCopy(TestObject src, TestObject dest) {
src.setName("freddie");
src.setAge(15);
src.setSpouse(new TestObject());
assertFalse(src.getAge() == dest.getAge());
ReflectionUtils.shallowCopyFieldState(src, dest);
assertEquals(src.getAge(), dest.getAge());
assertEquals(src.getSpouse(), dest.getSpouse());
}
@Test
public void doWithProtectedMethods() {
ListSavingMethodCallback mc = new ListSavingMethodCallback();
ReflectionUtils.doWithMethods(TestObject.class, mc, new ReflectionUtils.MethodFilter() {
@Override
public boolean matches(Method m) {
return Modifier.isProtected(m.getModifiers());
}
});
assertFalse(mc.getMethodNames().isEmpty());
assertTrue("Must find protected method on Object", mc.getMethodNames().contains("clone"));
assertTrue("Must find protected method on Object", mc.getMethodNames().contains("finalize"));
assertFalse("Public, not protected", mc.getMethodNames().contains("hashCode"));
assertFalse("Public, not protected", mc.getMethodNames().contains("absquatulate"));
}
@Test
public void duplicatesFound() {
ListSavingMethodCallback mc = new ListSavingMethodCallback();
ReflectionUtils.doWithMethods(TestObjectSubclass.class, mc);
int absquatulateCount = 0;
for (String name : mc.getMethodNames()) {
if (name.equals("absquatulate")) {
++absquatulateCount;
}
}
assertEquals("Found 2 absquatulates", 2, absquatulateCount);
}
@Test
public void findMethod() throws Exception {
assertNotNull(ReflectionUtils.findMethod(B.class, "bar", String.class));
assertNotNull(ReflectionUtils.findMethod(B.class, "foo", Integer.class));
assertNotNull(ReflectionUtils.findMethod(B.class, "getClass"));
}
@Ignore("[SPR-8644] findMethod() does not currently support var-args")
@Test
public void findMethodWithVarArgs() throws Exception {
assertNotNull(ReflectionUtils.findMethod(B.class, "add", int.class, int.class, int.class));
}
@Test
public void isCglibRenamedMethod() throws SecurityException, NoSuchMethodException {
@SuppressWarnings("unused")
class C {
public void CGLIB$m1$123() {
}
public void CGLIB$m1$0() {
}
public void CGLIB$$0() {
}
public void CGLIB$m1$() {
}
public void CGLIB$m1() {
}
public void m1() {
}
public void m1$() {
}
public void m1$1() {
}
}
assertTrue(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1$123")));
assertTrue(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1$0")));
assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$$0")));
assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1$")));
assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("CGLIB$m1")));
assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("m1")));
assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("m1$")));
assertFalse(ReflectionUtils.isCglibRenamedMethod(C.class.getMethod("m1$1")));
}
@Test
public void getAllDeclaredMethods() throws Exception {
class Foo {
@Override
public String toString() {
return super.toString();
}
}
int toStringMethodCount = 0;
for (Method method : ReflectionUtils.getAllDeclaredMethods(Foo.class)) {
if (method.getName().equals("toString")) {
toStringMethodCount++;
}
}
assertThat(toStringMethodCount, is(2));
}
@Test
public void getUniqueDeclaredMethods() throws Exception {
class Foo {
@Override
public String toString() {
return super.toString();
}
}
int toStringMethodCount = 0;
for (Method method : ReflectionUtils.getUniqueDeclaredMethods(Foo.class)) {
if (method.getName().equals("toString")) {
toStringMethodCount++;
}
}
assertThat(toStringMethodCount, is(1));
}
@Test
public void getUniqueDeclaredMethods_withCovariantReturnType() throws Exception {
class Parent {
@SuppressWarnings("unused")
public Number m1() {
return Integer.valueOf(42);
}
}
class Leaf extends Parent {
@Override
public Integer m1() {
return Integer.valueOf(42);
}
}
int m1MethodCount = 0;
Method[] methods = ReflectionUtils.getUniqueDeclaredMethods(Leaf.class);
for (Method method : methods) {
if (method.getName().equals("m1")) {
m1MethodCount++;
}
}
assertThat(m1MethodCount, is(1));
assertTrue(ObjectUtils.containsElement(methods, Leaf.class.getMethod("m1")));
assertFalse(ObjectUtils.containsElement(methods, Parent.class.getMethod("m1")));
}
@Test
public void getUniqueDeclaredMethods_isFastEnough() {
Assume.group(TestGroup.PERFORMANCE);
@SuppressWarnings("unused")
class C {
void m00() {
}
void m01() {
}
void m02() {
}
void m03() {
}
void m04() {
}
void m05() {
}
void m06() {
}
void m07() {
}
void m08() {
}
void m09() {
}
void m10() {
}
void m11() {
}
void m12() {
}
void m13() {
}
void m14() {
}
void m15() {
}
void m16() {
}
void m17() {
}
void m18() {
}
void m19() {
}
void m20() {
}
void m21() {
}
void m22() {
}
void m23() {
}
void m24() {
}
void m25() {
}
void m26() {
}
void m27() {
}
void m28() {
}
void m29() {
}
void m30() {
}
void m31() {
}
void m32() {
}
void m33() {
}
void m34() {
}
void m35() {
}
void m36() {
}
void m37() {
}
void m38() {
}
void m39() {
}
void m40() {
}
void m41() {
}
void m42() {
}
void m43() {
}
void m44() {
}
void m45() {
}
void m46() {
}
void m47() {
}
void m48() {
}
void m49() {
}
void m50() {
}
void m51() {
}
void m52() {
}
void m53() {
}
void m54() {
}
void m55() {
}
void m56() {
}
void m57() {
}
void m58() {
}
void m59() {
}
void m60() {
}
void m61() {
}
void m62() {
}
void m63() {
}
void m64() {
}
void m65() {
}
void m66() {
}
void m67() {
}
void m68() {
}
void m69() {
}
void m70() {
}
void m71() {
}
void m72() {
}
void m73() {
}
void m74() {
}
void m75() {
}
void m76() {
}
void m77() {
}
void m78() {
}
void m79() {
}
void m80() {
}
void m81() {
}
void m82() {
}
void m83() {
}
void m84() {
}
void m85() {
}
void m86() {
}
void m87() {
}
void m88() {
}
void m89() {
}
void m90() {
}
void m91() {
}
void m92() {
}
void m93() {
}
void m94() {
}
void m95() {
}
void m96() {
}
void m97() {
}
void m98() {
}
void m99() {
}
}
StopWatch sw = new StopWatch();
sw.start();
Method[] methods = ReflectionUtils.getUniqueDeclaredMethods(C.class);
sw.stop();
long totalMs = sw.getTotalTimeMillis();
assertThat(methods.length, Matchers.greaterThan(100));
assertThat(totalMs, Matchers.lessThan(10L));
}
private static class ListSavingMethodCallback implements ReflectionUtils.MethodCallback {
private List<String> methodNames = new LinkedList<>();
private List<Method> methods = new LinkedList<>();
@Override
public void doWith(Method m) throws IllegalArgumentException, IllegalAccessException {
this.methodNames.add(m.getName());
this.methods.add(m);
}
public List<String> getMethodNames() {
return this.methodNames;
}
@SuppressWarnings("unused")
public List<Method> getMethods() {
return this.methods;
}
}
private static class TestObjectSubclass extends TestObject {
@Override
public void absquatulate() {
throw new UnsupportedOperationException();
}
}
private static class TestObjectSubclassWithPublicField extends TestObject {
@SuppressWarnings("unused")
public String publicField = "foo";
}
private static class TestObjectSubclassWithNewField extends TestObject {
protected String prot = "foo";
private int magic;
}
private static class TestObjectSubclassWithFinalField extends TestObject {
@SuppressWarnings("unused")
private final String foo = "will break naive copy that doesn't exclude statics";
}
private static class A {
@SuppressWarnings("unused")
private void foo(Integer i) throws RemoteException {
}
}
@SuppressWarnings("unused")
private static class B extends A {
void bar(String s) throws IllegalArgumentException {
}
int add(int... args) {
int sum = 0;
for (int i = 0; i < args.length; i++) {
sum += args[i];
}
return sum;
}
}
}
| [
"[email protected]"
]
| |
539530034736b4f705961474ca0c1b8b5ed7418c | 28304035d13b212d6998d0ba73a6826d1b4f7bf1 | /app/src/test/java/com/example/edgelight/CreateNotificationTextTest.java | ff9cd733ea42a24230819351363179861ff8d6b7 | []
| no_license | galbertsson/EdgeLight | e19482ef9afd3509d3f4a946ec52cdadb5cfc80b | f7f83196e4e8ee7ba9ed18c2e78035c531ac3921 | refs/heads/develop | 2021-06-22T03:41:34.941555 | 2021-04-23T20:48:44 | 2021-04-23T20:48:44 | 215,828,574 | 4 | 1 | null | 2021-04-23T20:48:45 | 2019-10-17T15:41:08 | Java | UTF-8 | Java | false | false | 4,522 | java | package com.example.edgelight;
import com.example.edgelight.model.AppSetting;
import com.example.edgelight.util.NotificationUtils;
import org.junit.Test;
import static org.junit.Assert.*;
public class CreateNotificationTextTest {
@Test
public void simple() {
CharSequence title = "title";
CharSequence text = "text";
AppSetting appSetting = new AppSetting();
appSetting.setTitlePos(0);
appSetting.setTextPos(1);
appSetting.setPackageName("com.example");
String expected = title + " " + text;
String notification = NotificationUtils.createNotificationText(title, text, appSetting);
assertEquals(expected, notification);
}
@Test
public void disableTitle() {
CharSequence title = "title";
CharSequence text = "text";
AppSetting appSetting = new AppSetting();
appSetting.setTitlePos(2);
appSetting.setTextPos(0);
appSetting.setPackageName("com.example");
String expected = text.toString();
String notification = NotificationUtils.createNotificationText(title, text, appSetting);
assertEquals(expected, notification);
}
@Test
public void disableText() {
CharSequence title = "title";
CharSequence text = "text";
AppSetting appSetting = new AppSetting();
appSetting.setTitlePos(0);
appSetting.setTextPos(2);
appSetting.setPackageName("com.example");
String expected = title.toString();
String notification = NotificationUtils.createNotificationText(title, text, appSetting);
assertEquals(expected, notification);
}
@Test
public void bothDisabled() {
CharSequence title = "title";
CharSequence text = "text";
AppSetting appSetting = new AppSetting();
appSetting.setTitlePos(2);
appSetting.setTextPos(2);
appSetting.setPackageName("com.example");
String expected = "";
String notification = NotificationUtils.createNotificationText(title, text, appSetting);
assertEquals(expected, notification);
}
@Test
public void titleNull() {
CharSequence title = null;
CharSequence text = "text";
AppSetting appSetting = new AppSetting();
appSetting.setTitlePos(0);
appSetting.setTextPos(1);
appSetting.setPackageName("com.example");
String expected = text.toString();
String notification = NotificationUtils.createNotificationText(title, text, appSetting);
assertEquals(expected, notification);
}
@Test
public void textNull() {
CharSequence title = "title";
CharSequence text = null;
AppSetting appSetting = new AppSetting();
appSetting.setTitlePos(0);
appSetting.setTextPos(1);
appSetting.setPackageName("com.example");
String expected = title.toString();
String notification = NotificationUtils.createNotificationText(title, text, appSetting);
assertEquals(expected, notification);
}
@Test
public void bothNull() {
CharSequence title = null;
CharSequence text = null;
AppSetting appSetting = new AppSetting();
appSetting.setTitlePos(0);
appSetting.setTextPos(1);
appSetting.setPackageName("com.example");
String expected = "";
String notification = NotificationUtils.createNotificationText(title, text, appSetting);
assertEquals(expected, notification);
}
@Test
public void bothfirst() {
CharSequence title = "title";
CharSequence text = "text";
AppSetting appSetting = new AppSetting();
appSetting.setTitlePos(0);
appSetting.setTextPos(0);
appSetting.setPackageName("com.example");
String expected = title + " " + text;
String notification = NotificationUtils.createNotificationText(title, text, appSetting);
assertEquals(expected, notification);
}
@Test
public void bothLast() {
CharSequence title = "title";
CharSequence text = "text";
AppSetting appSetting = new AppSetting();
appSetting.setTitlePos(1);
appSetting.setTextPos(1);
appSetting.setPackageName("com.example");
String expected = title + " " + text;
String notification = NotificationUtils.createNotificationText(title, text, appSetting);
assertEquals(expected, notification);
}
}
| [
"[email protected]"
]
| |
0523c7dd4721003207b3c8d22396bcc9c21d9d00 | da1d3bfef78ef735246ec8d9440d112415d07206 | /spring_cloud_sell/order/server/src/main/java/com/cunjunwang/order/controller/TrnController.java | c69b30571c8c25cf3f8e8f3fc3bd68a021b65bd1 | []
| no_license | CunjunWang/microservice | 16744e7a2fd875c9d6f1bd49d94e9eb0db7dc5b7 | ce0ae362abbad4b1f50461edfcbca38dc1196b97 | refs/heads/master | 2020-03-25T21:16:39.648058 | 2018-08-28T15:47:08 | 2018-08-28T15:47:08 | 144,168,701 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 562 | java | package com.cunjunwang.order.controller;
import com.cunjunwang.order.config.TrnConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Created by CunjunWang on 2018/8/14.
*/
@RestController
public class TrnController {
@Autowired
private TrnConfig trnConfig;
@GetMapping("/trn/print")
public String print() {
return "name: " + trnConfig.getName() + " age: " + trnConfig.getAge();
}
}
| [
"[email protected]"
]
| |
773457185d08fecfbf11c4280ace9740418f59c9 | 9581f585e58241aeaa8b3896a2cd34a69bf62d67 | /src/Server/ClientDemo.java | 3121fccebc0553c65f15856859c814f8f2c0e59a | []
| no_license | ZhengXinYu666/Day26 | 9505c149c74e0a1a0357ae42011c75b5a6dc9644 | 618bfaec3bb58de1dcd53c4d428319870559160e | refs/heads/master | 2020-07-07T01:34:58.392578 | 2019-08-19T15:47:33 | 2019-08-19T15:47:33 | 203,202,873 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 746 | java | package Server;
import jdk.internal.util.xml.impl.Input;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class ClientDemo {
public static void main(String[] args)throws IOException {
//创建客户端对象
Socket s = new Socket("192.168.43.31",9999);
//获取输出流
OutputStream os = s.getOutputStream();
os.write("今天天气不错,适合睡觉".getBytes());
//获取输入流
InputStream is = s.getInputStream();
byte[] bys = new byte[1024];
int len = is.read(bys);
String client = new String(bys,0,len);
System.out.println("client:"+client);
s.close();
}
}
| [
"[email protected]"
]
| |
6ff6ab5e2221a0296999f512f1bd73e07ad35727 | 974977661e55ff1d9c2d597ab49fab4f9a82717f | /spring-learning-ioc/src/main/java/com/longge/service/UserService.java | f64fddba7f7b2cc491afe81ff76522b105f4d11d | []
| no_license | longyonghua/SSM-Learning | dd6f56c6ecc536431b801a74184a9721836ec7ee | dd50b51b5f78f23fc65903b1cdd301f5aafb814c | refs/heads/master | 2022-12-24T12:55:15.318731 | 2019-10-14T12:47:10 | 2019-10-14T12:47:10 | 213,795,939 | 0 | 0 | null | 2022-12-16T00:39:39 | 2019-10-09T01:52:07 | Java | UTF-8 | Java | false | false | 343 | java | package com.longge.service;
import com.longge.domain.User;
import java.util.List;
/**
* @author longge
* @create 2019-10-07 下午2:18
*/
public interface UserService {
List<User> findAllUser();
User findUserById(Integer id);
void saveUser(User user);
void updateUser(User user);
void deleteUser(Integer id);
}
| [
"[email protected]"
]
| |
62c90a4f515f7226c3d6ea95f7913183465e5bbf | 14ae33a65306d1bba038707bdbe41ea7d3d5b72d | /src/uk/ac/gre/comp1549/dashboard/controls/IIndicatorPanel.java | 39ddaa85f7a26c0a17845575d5fdc408a8e48b85 | []
| no_license | shalali/Aeroplane-Dashboard | e1a50c5153b56b2212c63407b94e372696120b83 | bca35f042d49a9dec81c40a83ec8b9a2037abc0a | refs/heads/master | 2021-06-17T10:45:42.001332 | 2017-05-30T17:31:48 | 2017-05-30T17:31:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 439 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package uk.ac.gre.comp1549.dashboard.controls;
import javax.swing.JLabel;
/**
*
* @author st8511x
*/
//ALL PANELS MUST HAVE...
public interface IIndicatorPanel {
void setLabel(String label);
void setValue(int value);
}
| [
"[email protected]"
]
| |
1de484b7f1ef70405b11e3225265a2b62f828ee4 | 180fdf4c346d36f8276375043458b62a3ad74994 | /src/test/java/com/github/galimru/boostrsdk/AuthServiceTest.java | f4e3238dd5437b38504664028edb810c1d9377ef | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
]
| permissive | galimru/boostr-java-sdk | ebc3eb5f1e9a815b51423caaedc373d80fc8b69a | 123282c7e047fa5bdd81334446655d95587f934a | refs/heads/main | 2023-04-02T19:43:48.834909 | 2021-04-06T22:08:22 | 2021-04-06T22:08:22 | 353,419,471 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,026 | java | package com.github.galimru.boostrsdk;
import com.github.galimru.boostrsdk.exceptions.ApiException;
import com.github.galimru.boostrsdk.http.Credentials;
import com.github.galimru.boostrsdk.model.UserTokenResponse;
import com.github.galimru.boostrsdk.logging.Level;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
public class AuthServiceTest {
private static BoostrClient client;
@BeforeClass
public static void setup() {
client = BoostrClient.builder()
.withBaseUrl(BoostrClient.SANDBOX_BASE_URL)
.withCredentials(Credentials.of(TestConstants.USERNAME, TestConstants.PASSWORD))
.withHttpLoggingLevel(Level.BODY)
.build();
}
@Test
public void getTokenShouldWork() throws IOException, ApiException {
UserTokenResponse response = client.auth().getToken(TestConstants.USERNAME, TestConstants.PASSWORD);
Assert.assertNotNull(response.getJwt());
}
}
| [
"[email protected]"
]
| |
cacf4e5f0e8c97a0e4784ccf541c84b7dbc4b67f | 2ee2ef80e2b9e602ebfe962e41d19f22704cdd31 | /2021.04.25 'For' Loop (Extra Exercises)/src/for_loop_extra_exercises/h_equivalent_pairs.java | 52972505f86998f4096bf552be4282865afaf150 | []
| no_license | svetthesaiyan/softuni-projects-pb-with-java | 1bffe909c3c5f221f94238747540445332daf440 | 14753a9322af6edb4b906b0ecfbc34523f62a7f8 | refs/heads/main | 2023-05-26T13:39:12.777924 | 2021-06-02T23:00:40 | 2021-06-02T23:00:40 | 357,715,872 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,080 | java | package for_loop_extra_exercises;
import java.util.Scanner;
public class h_equivalent_pairs
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter how many loops you'd like to go through: ");
int numberOfLoops=Integer.parseInt(scanner.nextLine());
System.out.println();
int initialSum=0;
int subsequentSum=0;
int maxDifference=0;
for(int i=1; i<=numberOfLoops; i++)
{
if(i==1)
{
System.out.print("Enter the first number for the initial sum: ");
int initialSumFirstNumber=Integer.parseInt(scanner.nextLine());
System.out.print("Enter the second number for the inital sum: ");
int initialSumSecondNumber=Integer.parseInt(scanner.nextLine());
initialSum=initialSumFirstNumber+initialSumSecondNumber;
}
else
{
System.out.println();
System.out.print("Enter the first number for the subsequent sum: ");
int subsequentSumFirstNumber=Integer.parseInt(scanner.nextLine());
System.out.print("Enter the second number for the subsequent sum: ");
int subsequentSumSecondNumber=Integer.parseInt(scanner.nextLine());
subsequentSum=subsequentSumFirstNumber+subsequentSumSecondNumber;
if((subsequentSum-initialSum!=0))
{
maxDifference=Math.abs(subsequentSum-initialSum);
initialSum=subsequentSum; // шом веднъж изначалната двойка и последвалата я двойка от числа се различават, то нацяло отпада вариантът да са равни всички двойки и затова се присвоява стойността на предишната двойка, за да продължи цикъла
}
}
}
System.out.println();
if(maxDifference!=0)
System.out.print("The groups of numbers you input have differing sums."+"\n"+"The maximal difference in sums when looking at each duo of numbers consecutively is: "+maxDifference);
else
System.out.print("All groups of numbers have an identical sum, which is: "+initialSum);
}
}
| [
"[email protected]"
]
| |
bead3bca1ac7cde30cf80765542e474408f5bdb4 | 94b0e84976231fcff673daf18c8e8f76951ace1a | /src/main/java/com/yisui/dao/ClassDao.java | eb2d25467066e886954f2b82aa2b84049d9edc6a | []
| no_license | constling/choumi | 216b40fe7cfd046656ae7d845776b9f25461156e | 613aeb32865a1b50960ab51ec80b384f6b3c1007 | refs/heads/master | 2022-12-22T11:00:26.346094 | 2020-04-07T07:57:14 | 2020-04-07T07:57:14 | 211,438,036 | 0 | 0 | null | 2022-12-16T12:13:30 | 2019-09-28T03:25:39 | Java | UTF-8 | Java | false | false | 50 | java | package com.yisui.dao;
public class ClassDao {
}
| [
"[email protected]"
]
| |
b35d4c0afac0c924f6fc16a626bdcb97cd4d910b | 01087a4d4f9945b1b7c54126cbc69d4aad648140 | /StriverSDE/Arrays/D3_P4_MajorityElement2.java | 4eadb320f06dee2149e5e8caeaa6768e197f1d28 | []
| no_license | prafull-vrsh/Data-Structures-Algorithms | 1f30b81b78cf1c3d8181f70ba3785c5b32f28980 | f88930893b5d1958cedfdf5f552c1e9eb52124e4 | refs/heads/master | 2023-09-01T01:13:06.451129 | 2021-10-06T06:41:48 | 2021-10-06T06:41:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 970 | java | // https://leetcode.com/problems/majority-element-ii/
// BOYER MOORE VOTING ALGORITHM
class Solution {
public List<Integer> majorityElement(int[] nums) {
List<Integer> res = new ArrayList<>();
int count1=0, count2=0, num1=-1, num2=-1;
int l = nums.length;
for(int i=0; i<l; i++){
if(nums[i] == num1)count1++;
else if(nums[i] == num2)count2++;
else if(count1 == 0){
num1 = nums[i];
count1 = 1;
}else if(count2 == 0){
num2 = nums[i];
count2++;
}else{
count1--;
count2--;
}
}
count1=0;
count2=0;
for(int i=0; i<l; i++){
if(nums[i]==num1)count1++;
else if(nums[i]==num2)count2++;
}
if(count1>l/3)res.add(num1);
if(count2>l/3)res.add(num2);
return res;
}
}
| [
"[email protected]"
]
| |
f42eef72b909954a51d53626a9653a9d44d364a6 | 2555445de5b918c70532a07b2b787bcd19b526ab | /asset/src/com/dao/impl/AssetTypeDao.java | 2daeb42ad207b75f45e052eec7e1ccd15678ad79 | []
| no_license | chenqinhuang/asset | d2c46fb27531cd81875b2bfa83d5a53d54890a9d | b10b14319e60d8a8452f2441f62432653fa0ca61 | refs/heads/master | 2021-01-01T05:18:27.339105 | 2016-05-19T03:33:51 | 2016-05-19T03:34:03 | 59,168,494 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 154 | java | package com.dao.impl;
import com.dao.IAssetTypeDao;
/**
*
* @author hpp
*
*/
public class AssetTypeDao extends BaseDao implements IAssetTypeDao{
}
| [
"[email protected]"
]
| |
cacba6266286a41bd31be709e945a4c45a23e871 | 7865222866e1369789edeefb7e9d4180583d9a08 | /src/main/java/br/com/edersonandrey/pinbowling/model/Turn.java | 2ebcb9f4e91dd2a6df079d37417932fca600157e | []
| no_license | edersonandrey/10PinBowling | 049ea7c5f972e32ca5eab8d46cb177e795bbb248 | 89b250a6ac949de856a0abec2ae0562e24deddf5 | refs/heads/main | 2023-03-06T21:42:39.237119 | 2021-02-23T15:47:15 | 2021-02-23T15:47:15 | 341,539,602 | 0 | 0 | null | 2021-02-23T15:46:01 | 2021-02-23T11:58:09 | null | UTF-8 | Java | false | false | 484 | java | package br.com.edersonandrey.pinbowling.model;
public class Turn {
private String playerName;
private String pinsDown;
public Turn(String playerName, String pinsDown) {
super();
this.playerName = playerName;
this.pinsDown = pinsDown;
}
public String getPlayerName() {
return playerName;
}
public String getPinsDown() {
return pinsDown;
}
@Override
public String toString() {
return "Turn [playerName=" + playerName + ", pinsDown=" + pinsDown + "]";
}
}
| [
"[email protected]"
]
| |
cbf2bdf31588f799dbf31f80b55ac1d74874fb7f | 2ceb874289627a8c83f15a379f1e5750b0305200 | /root/src/main/java/com/me2me/web/request/GetLotteryListRequest.java | 94e356a4063cce70ef80c835fd324fa909319a34 | []
| no_license | hushunjian/me2me-app | 73a691576d29565f5a51eed9025e256df6b5c9ce | 5da0a720b72193a041150fae1266fceb33ba8518 | refs/heads/master | 2023-01-07T15:59:26.013478 | 2021-04-03T09:50:07 | 2021-04-03T09:50:07 | 120,296,809 | 0 | 2 | null | 2022-12-16T07:54:57 | 2018-02-05T11:37:31 | Java | UTF-8 | Java | false | false | 261 | java | package com.me2me.web.request;
import lombok.Getter;
import lombok.Setter;
import com.me2me.common.web.Request;
public class GetLotteryListRequest extends Request {
@Getter
@Setter
private long topicId;
@Getter
@Setter
private long sinceId;
}
| [
"[email protected]"
]
| |
473aa75784d9c9b4bb416304ab543bad87d79033 | d04bf43f6ef7189dbe16949b797e3d0a9c418779 | /src/main/java/com/dlanca/cursomc/resources/utils/URL.java | bf48ce7c478aea79537916f10f15e0a89df01f5b | []
| no_license | DouglasLanca/cursomc | 4949d38914053c4c3d5342dcaf35b1461db40118 | 88c758be09eafa503f25662b783542b050f786ed | refs/heads/master | 2022-12-05T13:56:11.182620 | 2020-08-20T21:31:36 | 2020-08-20T21:31:36 | 257,754,317 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 799 | java | package com.dlanca.cursomc.resources.utils;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
public class URL {
public static List<Integer> decodeIntList(String s){
String[] vet = s.split(",");
List<Integer> integerNumber = new ArrayList<>();
for (String numbers: vet){
integerNumber.add(Integer.parseInt(numbers));
}
return integerNumber;
//return Arrays.asList(s.split(",")).stream().map(x -> Integer.parseInt(x)).collect(Collectors.toList());
}
public static String decodeParam(String s){
try{
return URLDecoder.decode(s, "UTF-8");
}catch (UnsupportedEncodingException e){
return "";
}
}
}
| [
"[email protected]"
]
| |
6ac2547455f99f265cda5ed263051c3aa301864c | 814496582b4729e4862f5f1101ba3880e90f535b | /plugin/bukkit/abstraction/v1_16_R2/src/main/java/com/mrivanplays/skins/bukkit/abstraction/SkinSetter1_16_R2.java | a87874217be4ac2b8b4922505533f25b991aa37e | [
"MIT"
]
| permissive | MrIvanPlays/Skins | 07f4affd35719c4f48e907c93ac03d7a8db496d7 | 4b1984b27c8364cbe54c5e5b95b052a6995b5af4 | refs/heads/master | 2022-12-17T12:22:14.186427 | 2022-12-07T18:22:09 | 2022-12-07T18:22:09 | 204,759,535 | 5 | 5 | MIT | 2020-07-04T10:06:21 | 2019-08-27T17:55:54 | Java | UTF-8 | Java | false | false | 2,947 | java | package com.mrivanplays.skins.bukkit.abstraction;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.properties.Property;
import com.mrivanplays.skins.api.Skin;
import java.lang.reflect.Field;
import java.util.List;
import java.util.UUID;
import org.bukkit.Material;
import org.bukkit.craftbukkit.v1_16_R2.entity.CraftPlayer;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.persistence.PersistentDataType;
public class SkinSetter1_16_R2 implements SkinSetter {
@Override
public void setSkin(Player player, Skin skin) {
((CraftPlayer) player)
.getHandle()
.getProfile()
.getProperties()
.put("textures", new Property("textures", skin.getTexture(), skin.getSignature()));
}
@Override
public ItemStack getMenuItem(
Skin skin, String ownerName, String headNameFormat, List<String> lore) {
ItemStack item = new ItemStack(Material.PLAYER_HEAD);
SkullMeta meta = (SkullMeta) item.getItemMeta();
if (skin != null) {
GameProfile profile = new GameProfile(skin.getOwner(), ownerName);
profile
.getProperties()
.put("textures", new Property("textures", skin.getTexture(), skin.getSignature()));
try {
Field profileField = meta.getClass().getDeclaredField("profile");
profileField.setAccessible(true);
profileField.set(meta, profile);
} catch (IllegalAccessException | NoSuchFieldException e) {
e.printStackTrace();
}
meta.getPersistentDataContainer()
.set(SkinSetter.SKULL_OWNER_NAME_KEY, PersistentDataType.STRING, ownerName);
meta.getPersistentDataContainer()
.set(
SkinSetter.SKULL_OWNER_UUID_KEY,
PersistentDataType.STRING,
skin.getOwner().toString());
}
if (headNameFormat != null) {
meta.setDisplayName(headNameFormat.replace("%name%", ownerName));
}
meta.setLore(lore);
item.setItemMeta(meta);
return item;
}
@Override
public SkullItemOwnerResponse getSkullOwner(ItemStack item) {
if (item.getType() != Material.PLAYER_HEAD) {
return null;
}
if (!item.hasItemMeta()) {
return null;
}
if (!(item.getItemMeta() instanceof SkullMeta)) {
return null;
}
SkullMeta meta = (SkullMeta) item.getItemMeta();
String ownerName =
meta.getPersistentDataContainer()
.get(SkinSetter.SKULL_OWNER_NAME_KEY, PersistentDataType.STRING);
String ownerUUIDString =
meta.getPersistentDataContainer()
.get(SkinSetter.SKULL_OWNER_UUID_KEY, PersistentDataType.STRING);
if (ownerName == null || ownerUUIDString == null) {
return null;
}
return new SkullItemOwnerResponse(ownerName, UUID.fromString(ownerUUIDString));
}
}
| [
"[email protected]"
]
| |
b1f3a1df33e84ac4b7db555232c5c0530129a48b | e038c9b9761e978e3935e268e7ddfa1b15533341 | /基础语法/DataTypeDemo4.java | 6cc0547780e531a802c55192a30ad4f7216c1977 | []
| no_license | Scyzin/11.6restart | 600df7635ae599bfebe459bd110f7dc5ee72ec76 | fcbaaf6b5bd460569e837410557d025ce1f30123 | refs/heads/master | 2021-08-29T01:26:35.555266 | 2017-12-13T08:52:19 | 2017-12-13T08:52:19 | 109,783,364 | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 525 | java | /*
强制转换:
从大的数据类型到小的数据类型。
格式:
目标数据类型 变量 = (目标数据类型) (被转换的数据);
注意:
不要随意的去使用强制转换,因为它隐含了精度损失问题。
*/
class DataTypeDemo4 {
public static void main(String[] args) {
byte a = 3;
int b = 4;
//int c = a + b;
//byte c = 7;
//这个是有问题的
//byte c = a + b;
//用强制类型转换改进
byte c = (byte) (a + b);
System.out.println(c);
}
} | [
"[email protected]"
]
| |
d7015a10489b067ee5f5c6ca3a5c7db4e8dd93fa | d745ffaddb2e4b5a32e71cfd1067815a26de18ad | /app/src/main/java/com/example/fragmenttest/AnotherRightFragment.java | 433d42bac9c71e28cf97cc5b661c254ecf5419ea | []
| no_license | lbge/Fragement | 5bbc42c14ba8e81b5b4ee20666962f82c3fb0c74 | 9aff201478d7bf4155bc3e71c9ae174f944190dd | refs/heads/master | 2021-07-14T13:52:22.629335 | 2020-09-02T15:12:54 | 2020-09-02T15:12:54 | 194,587,115 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 516 | java | package com.example.fragmenttest;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class AnotherRightFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.another_right_fragment, container, false);
return view;
}
}
| [
"[email protected]"
]
| |
b79af37ecfdf0ff21066756afdfb76490829ab9c | 01f272af704234b2ebec7fe3d3342263246f5373 | /codes/05/5.5/Apple.java | 0a41d5a5b7dfffa684ad22ebf89d11b24032174f | []
| no_license | liyingfei142118/crazy_learn_java | 9d75be0b4c426ff228227fc6a8ba4a94c250b15d | cdd582053db24970a718c0a8861eb9ec2e6c115c | refs/heads/master | 2022-02-22T18:18:15.209063 | 2019-08-28T02:32:30 | 2019-08-28T02:32:30 | 204,604,842 | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 806 | java |
/**
* Description:
* 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a><br>
* Copyright (C), 2001-2020, Yeeku.H.Lee<br>
* This program is protected by copyright laws.<br>
* Program Name:<br>
* Date:<br>
* @author Yeeku.H.Lee [email protected]
* @version 5.0
*/
public class Apple
{
public String name;
public String color;
public double weight;
public Apple(){}
// 两个参数的构造器
public Apple(String name, String color)
{
this.name = name;
this.color = color;
}
// 三个参数的构造器
public Apple(String name, String color, double weight)
{
// 通过this调用另一个重载的构造器的初始化代码
this(name, color);
// 下面this引用该构造器正在初始化的Java对象
this.weight = weight;
}
}
| [
"[email protected]"
]
| |
b6ce5519dd9a66d1566ef39f0576effcbad212d7 | 94462015f8cfd0f9d7d32e7f0756ab05e1476071 | /UITestCase/app/src/main/java/com/example/sahil/uitestcase/MainActivity.java | 783891ec792d63fa8c471a428f6cf3c8cf606fee | []
| no_license | sahilgarg30/Falgee-Apps | f5d26aaa138daa57b684184fd40c9bf3ab5a6f16 | 46d2512ed35681a1135e4829dd92f43c68865307 | refs/heads/master | 2020-03-24T10:50:15.530275 | 2018-07-28T10:40:24 | 2018-07-28T10:40:24 | 142,669,118 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 786 | java | package com.example.sahil.uitestcase;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private EditText mNameEt;
private TextView mHelloTv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNameEt = (EditText)findViewById(R.id.name_et);
mHelloTv = (TextView)findViewById(R.id.result_tv);
}
public void sayHello(View view) {
String name = mNameEt.getText().toString();
String result = "Hello, " + name + " !";
mHelloTv.setText(result);
}
}
| [
"[email protected]"
]
| |
d465b64dbfe5b8ec307e3c63e8f5879fd6640023 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/20/20_bfffe28f5772b831a9d94cdc7436cc265dbad9cb/ContextMenuLayer/20_bfffe28f5772b831a9d94cdc7436cc265dbad9cb_ContextMenuLayer_t.java | 6d586170ffdaf9fe3eb219e4e9eb9b284a4f6870 | []
| no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 7,475 | java | package net.osmand.plus.views;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import net.osmand.osm.LatLon;
import net.osmand.plus.R;
import net.osmand.plus.activities.MapActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.FrameLayout.LayoutParams;
public class ContextMenuLayer extends OsmandMapLayer {
public interface IContextMenuProvider {
public Object getPointObject(PointF point);
public LatLon getObjectLocation(Object o);
public String getObjectDescription(Object o);
public String getObjectName(Object o);
public DialogInterface.OnClickListener getActionListener(List<String> actionsList, Object o);
}
private LatLon latLon;
private IContextMenuProvider selectedContextProvider;
private Object selectedObject;
private TextView textView;
private DisplayMetrics dm;
private OsmandMapTileView view;
private int BASE_TEXT_SIZE = 170;
private int SHADOW_OF_LEG = 5;
private final MapActivity activity;
private Drawable boxLeg;
private float scaleCoefficient = 1;
private Rect textPadding;
public ContextMenuLayer(MapActivity activity){
this.activity = activity;
}
@Override
public void destroyLayer() {
}
@Override
public void initLayer(OsmandMapTileView view) {
this.view = view;
dm = new DisplayMetrics();
WindowManager wmgr = (WindowManager) view.getContext().getSystemService(Context.WINDOW_SERVICE);
wmgr.getDefaultDisplay().getMetrics(dm);
scaleCoefficient = dm.density;
if (Math.min(dm.widthPixels / (dm.density * 160), dm.heightPixels / (dm.density * 160)) > 2.5f) {
// large screen
scaleCoefficient *= 1.5f;
}
BASE_TEXT_SIZE = (int) (BASE_TEXT_SIZE * scaleCoefficient);
SHADOW_OF_LEG = (int) (SHADOW_OF_LEG * scaleCoefficient);
boxLeg = view.getResources().getDrawable(R.drawable.box_leg);
boxLeg.setBounds(0, 0, boxLeg.getMinimumWidth(), boxLeg.getMinimumHeight());
textView = new TextView(view.getContext());
LayoutParams lp = new LayoutParams(BASE_TEXT_SIZE, LayoutParams.WRAP_CONTENT);
textView.setLayoutParams(lp);
textView.setTextSize(15);
textView.setTextColor(Color.argb(255, 0, 0, 0));
textView.setMinLines(1);
// textView.setMaxLines(15);
textView.setGravity(Gravity.CENTER_HORIZONTAL);
textView.setClickable(true);
textView.setBackgroundDrawable(view.getResources().getDrawable(R.drawable.box_free));
textPadding = new Rect();
textView.getBackground().getPadding(textPadding);
}
@Override
public void onDraw(Canvas canvas, RectF latLonBounds, RectF tilesRect, boolean nightMode) {
if(latLon != null){
int x = view.getRotatedMapXForPoint(latLon.getLatitude(), latLon.getLongitude());
int y = view.getRotatedMapYForPoint(latLon.getLatitude(), latLon.getLongitude());
int tx = x - boxLeg.getMinimumWidth() / 2;
int ty = y - boxLeg.getMinimumHeight() + SHADOW_OF_LEG;
canvas.translate(tx, ty);
boxLeg.draw(canvas);
canvas.translate(-tx, -ty);
if (textView.getText().length() > 0) {
canvas.translate(x - textView.getWidth() / 2, ty - textView.getBottom() + textPadding.bottom - textPadding.top);
int c = textView.getLineCount();
textView.draw(canvas);
if (c == 0) {
// special case relayout after on draw method
layoutText();
view.refreshMap();
}
}
}
}
private void layoutText() {
Rect padding = new Rect();
if (textView.getLineCount() > 0) {
textView.getBackground().getPadding(padding);
}
int w = BASE_TEXT_SIZE;
int h = (int) ((textView.getPaint().getTextSize() + 4) * textView.getLineCount());
textView.layout(0, -padding.bottom, w, h + padding.top);
}
public void setLocation(LatLon loc, String description){
latLon = loc;
if(latLon != null){
if(description == null || description.length() == 0){
description = MessageFormat.format(view.getContext().getString(R.string.point_on_map),
latLon.getLatitude(), latLon.getLongitude());
}
textView.setText(description);
} else {
textView.setText(""); //$NON-NLS-1$
}
layoutText();
}
@Override
public boolean onLongPressEvent(PointF point) {
if(pressedInTextView(point.x, point.y)){
setLocation(null, ""); //$NON-NLS-1$
view.refreshMap();
return true;
}
selectedContextProvider = null;
selectedObject = null;
for(OsmandMapLayer l : view.getLayers()){
if(l instanceof ContextMenuLayer.IContextMenuProvider){
selectedObject = ((ContextMenuLayer.IContextMenuProvider) l).getPointObject(point);
if(selectedObject != null){
selectedContextProvider = (IContextMenuProvider) l;
break;
}
}
}
LatLon latLon = view.getLatLonFromScreenPoint(point.x, point.y);
String description = "";
if(selectedObject != null){
description = selectedContextProvider.getObjectDescription(selectedObject);
LatLon l = selectedContextProvider.getObjectLocation(selectedObject);
if(l != null){
latLon = l;
}
}
setLocation(latLon, description);
view.refreshMap();
return true;
}
@Override
public boolean drawInScreenPixels() {
return true;
}
public boolean pressedInTextView(float px, float py) {
if (latLon != null) {
Rect bs = textView.getBackground().getBounds();
int x = (int) (px - view.getRotatedMapXForPoint(latLon.getLatitude(), latLon.getLongitude()));
int y = (int) (py - view.getRotatedMapYForPoint(latLon.getLatitude(), latLon.getLongitude()));
x += bs.width() / 2;
y += bs.height() + boxLeg.getMinimumHeight() - SHADOW_OF_LEG;
if (bs.contains(x, y)) {
return true;
}
}
return false;
}
public String getSelectedObjectName(){
if(selectedObject != null && selectedContextProvider != null){
return selectedContextProvider.getObjectName(selectedObject);
}
return null;
}
@Override
public boolean onSingleTap(PointF point) {
if (pressedInTextView(point.x, point.y)) {
if (selectedObject != null) {
ArrayList<String> l = new ArrayList<String>();
OnClickListener listener = selectedContextProvider.getActionListener(l, selectedObject);
activity.contextMenuPoint(latLon.getLatitude(), latLon.getLongitude(), l, listener);
} else {
activity.contextMenuPoint(latLon.getLatitude(), latLon.getLongitude());
}
return true;
}
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (latLon != null) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if(pressedInTextView(event.getX(), event.getY())){
textView.setPressed(true);
view.refreshMap();
}
}
}
if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
if(textView.isPressed()) {
textView.setPressed(false);
view.refreshMap();
}
}
return false;
}
}
| [
"[email protected]"
]
| |
d1eac716c2a26712807baed28126e070dd348da4 | 7219f75733d906ff930e1b6ba1be249d6007b582 | /src/com/vikings/sanguo/protos/FriendInfos.java | f8acc779b69f900272f159e7649bc1eb504bf05d | []
| no_license | wongainia/sanguo | 9c9b528a3b4cfaf58f94badf71add1b8bb77e038 | 55e38be665f1b9e3a4dc7a1caaa09728563cf4b2 | refs/heads/master | 2020-05-23T09:51:26.455001 | 2019-05-14T22:44:06 | 2019-05-14T22:44:06 | 186,711,060 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 4,754 | java | // Generated by http://code.google.com/p/protostuff/ ... DO NOT EDIT!
// Generated from common.proto
package com.vikings.sanguo.protos;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.List;
import com.dyuproject.protostuff.GraphIOUtil;
import com.dyuproject.protostuff.Input;
import com.dyuproject.protostuff.Message;
import com.dyuproject.protostuff.Output;
import com.dyuproject.protostuff.Schema;
public final class FriendInfos implements Externalizable, Message<FriendInfos>, Schema<FriendInfos>
{
public static Schema<FriendInfos> getSchema()
{
return DEFAULT_INSTANCE;
}
public static FriendInfos getDefaultInstance()
{
return DEFAULT_INSTANCE;
}
static final FriendInfos DEFAULT_INSTANCE = new FriendInfos();
private DataCtrl ctrl;
private List<ExFriendInfo> infos;
private Integer totalCount;
public FriendInfos()
{
}
// getters and setters
// ctrl
public boolean hasCtrl(){
return ctrl != null;
}
public DataCtrl getCtrl()
{
return ctrl == null ? new DataCtrl() : ctrl;
}
public FriendInfos setCtrl(DataCtrl ctrl)
{
this.ctrl = ctrl;
return this;
}
// infos
public boolean hasInfos(){
return infos != null;
}
public List<ExFriendInfo> getInfosList()
{
return infos == null? new ArrayList<ExFriendInfo>():infos;
}
public int getInfosCount()
{
return infos == null?0:infos.size();
}
public ExFriendInfo getInfos(int i)
{
return infos == null?null:infos.get(i);
}
public FriendInfos setInfosList(List<ExFriendInfo> infos)
{
this.infos = infos;
return this;
}
// totalCount
public boolean hasTotalCount(){
return totalCount != null;
}
public Integer getTotalCount()
{
return totalCount == null ? 0 : totalCount;
}
public FriendInfos setTotalCount(Integer totalCount)
{
this.totalCount = totalCount;
return this;
}
// java serialization
public void readExternal(ObjectInput in) throws IOException
{
GraphIOUtil.mergeDelimitedFrom(in, this, this);
}
public void writeExternal(ObjectOutput out) throws IOException
{
GraphIOUtil.writeDelimitedTo(out, this, this);
}
// message method
public Schema<FriendInfos> cachedSchema()
{
return DEFAULT_INSTANCE;
}
// schema methods
public FriendInfos newMessage()
{
return new FriendInfos();
}
public Class<FriendInfos> typeClass()
{
return FriendInfos.class;
}
public String messageName()
{
return FriendInfos.class.getSimpleName();
}
public String messageFullName()
{
return FriendInfos.class.getName();
}
public boolean isInitialized(FriendInfos message)
{
return true;
}
public void mergeFrom(Input input, FriendInfos message) throws IOException
{
for(int number = input.readFieldNumber(this);; number = input.readFieldNumber(this))
{
switch(number)
{
case 0:
return;
case 10:
message.ctrl = input.mergeObject(message.ctrl, DataCtrl.getSchema());
break;
case 20:
if(message.infos == null)
message.infos = new ArrayList<ExFriendInfo>();
message.infos.add(input.mergeObject(null, ExFriendInfo.getSchema()));
break;
case 30:
message.totalCount = input.readUInt32();
break;
default:
input.handleUnknownField(number, this);
}
}
}
public void writeTo(Output output, FriendInfos message) throws IOException
{
if(message.ctrl != null)
output.writeObject(10, message.ctrl, DataCtrl.getSchema(), false);
if(message.infos != null)
{
for(ExFriendInfo infos : message.infos)
{
if(infos != null)
output.writeObject(20, infos, ExFriendInfo.getSchema(), true);
}
}
if(message.totalCount != null)
output.writeUInt32(30, message.totalCount, false);
}
public String getFieldName(int number)
{
return Integer.toString(number);
}
public int getFieldNumber(String name)
{
return Integer.parseInt(name);
}
}
| [
"dengyuanming@dengyuanming"
]
| dengyuanming@dengyuanming |
05d7dc84324372f05a42b7e5585c18d34bfc9afb | b0752af8b8fbb0c869fb80ed3b12ada5a6676677 | /app/src/main/java/com/huatec/hiot_cloud/test/networktest/LoginResultDTO.java | 09092dcdbc885a192f2402b753f4ae03837f0b16 | []
| no_license | guoxiling/hiot_cloud_app | f680b6bc7e6570cd34917537ab8688b51cc43ecb | 7dbeaeb9a693e7895cc2955ad7c2946602abd5d4 | refs/heads/master | 2022-06-30T21:27:57.547905 | 2020-05-12T06:16:10 | 2020-05-12T06:16:10 | 254,803,216 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 517 | java | package com.huatec.hiot_cloud.test.networktest;
import java.io.Serializable;
/**
* 登录返回DTO类
*/
public class LoginResultDTO implements Serializable {
private String tokenValue;
private String uuid;
public String getTokenValue() {
return tokenValue;
}
public void setTokenValue(String tokenValue) {
this.tokenValue = tokenValue;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
}
| [
"[email protected]"
]
| |
316792b8a24faaaed873ea9ab66af7275306291c | 61bb8eba742d6f99cf322688a2218b4b8715bc25 | /src/main/java/app/dao/hibernate/UsuarioDAOH.java | d39441de0043248f7636edb21cc512cf267a5c31 | []
| no_license | carmena/masSpring | 709ca9852f637fe57d8ba2fba2a9baef7dcc10b4 | d55e28f93fd5b2545b803881f7f468faff558272 | refs/heads/master | 2021-01-17T05:33:39.098615 | 2013-12-02T18:38:39 | 2013-12-02T18:38:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,706 | java |
package app.dao.hibernate;
import app.dao.BaseHibernateDAO;
import app.dao.UsuarioDAO;
import app.model.Persona;
import app.model.Usuario;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository("usuarioDAO")
public class UsuarioDAOH extends BaseHibernateDAO implements UsuarioDAO{
public List<Usuario> list() {
Criteria criteria = this.getSession().createCriteria(Usuario.class);
return criteria.list();
}
public Usuario get(Usuario t) {
Criteria criteria = this.getSession().createCriteria(Usuario.class);
criteria.add(Restrictions.eq("id", t.getId()));
return (Usuario) criteria.uniqueResult();
}
@Transactional
public void save(Usuario t) {
this.getSession().save(t);
}
@Transactional
public void update(Usuario t) {
this.getSession().update(t);
}
@Transactional
public void delete(Usuario t) {
this.getSession().delete(t);
}
@Override
public Usuario getByPersona(Persona persona) {
Criteria criteria = this.getSession().createCriteria(Usuario.class);
criteria.add(Restrictions.eq("persona", persona));
return (Usuario) criteria.uniqueResult();
}
public Usuario getByUserName (String username){
Criteria criteria = this.getSession().createCriteria(Usuario.class);
criteria.add(Restrictions.eq("usuario", username));
return (Usuario) criteria.uniqueResult();
}
}
| [
"Administrador@LAB702-15"
]
| Administrador@LAB702-15 |
f3f8607164b91f05635a20afd561f93d9e1d60ff | f35347395771a918700b8a817dfa1f6f7a6a0ae0 | /08_getTreeInNext/src/Solution.java | cfef1023f398758a3842c288d11121518876002d | []
| no_license | Songlynn/CodingInterview-Java | 9c80a45782f1cb1366e484574feadc88e3fba511 | 450914c5948618fde38c719b3dab91ae52dcf1ea | refs/heads/master | 2021-01-23T16:25:22.876054 | 2017-06-11T09:33:45 | 2017-06-11T09:33:45 | 93,297,352 | 0 | 1 | null | 2017-06-11T09:33:45 | 2017-06-04T07:29:19 | JavaScript | GB18030 | Java | false | false | 645 | java | /*
* 在二叉树中序遍历中找出节点的下一节点
*/
public class Solution {
public class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode father;
TreeNode(int x){
this.val=x;
}
}
public TreeNode getNext(TreeNode node){
TreeNode next=null;
if(node.right!=null){
next=node.right;
while(next.left!=null){
next=next.left;
}
}
else if(node.father!=null&&node==node.father.left){
next=node.father;
}
else if(node.father!=null&&node==node.father.right){
next=node.father;
while(next.father!=null&&next==next.father.right){
next=next.father;
}
}
return next;
}
}
| [
"[email protected]"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.