blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
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
684M
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
132 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
28 values
content
stringlengths
3
9.45M
authors
listlengths
1
1
author_id
stringlengths
0
352
23835781fe01eb4bb26b15c7493cb0f2290e6b22
a7067537133bbd788286b6b64fe0e29e07121e28
/src/com/radiant/cisms/hdfs/seq/HInfoWritable.java
06b36045f2c7fd693231ae66a1c09632a0ff25e2
[]
no_license
thomachan/Hadoop
a9c0eedda65897813ede32d5e8dca2257959442b
2ffc5504ad851d5644daccf1a1e7789d781afc7a
refs/heads/master
2020-12-25T19:15:43.903298
2013-12-05T05:50:18
2013-12-05T05:50:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,839
java
package com.radiant.cisms.hdfs.seq; import java.io.ByteArrayInputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.IOException; import java.nio.ByteBuffer; import org.apache.commons.lang.builder.CompareToBuilder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.io.WritableUtils; public class HInfoWritable implements WritableComparable<HInfoWritable>, Cloneable { String oid; long objId; long time; double value; ByteBuffer buff; private static final Log LOG = LogFactory.getLog(" org.apache.hadoop.io"); public HInfoWritable() { buff = ByteBuffer.allocate(1024 * 64); } public HInfoWritable(String oid, long objId, long time, double value) { this.oid = oid; this.objId = objId; this.time = time; this.value = value; } public HInfoWritable(int defaultBufferSize) { buff = ByteBuffer.allocate(defaultBufferSize); } @Override public void write(DataOutput out) throws IOException { WritableUtils.writeString(out, oid); out.writeLong(objId); out.writeLong(time); out.writeDouble(value); } @Override public void readFields(DataInput in) throws IOException { oid = WritableUtils.readString(in); objId = in.readLong(); time = in.readLong(); value = in.readDouble(); } @Override public int compareTo(HInfoWritable passwd) { return CompareToBuilder.reflectionCompare(this, passwd); } public String getOid() { return oid; } public void setOid(String oid) { this.oid = oid; } public long getObjId() { return objId; } public void setObjId(long objId) { this.objId = objId; } public ByteBuffer getBuff() { return buff; } public void setBuff(ByteBuffer buff) { this.buff = buff; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } public double getValue() { return value; } public void setValue(double value) { this.value = value; } public void put(byte buffer[], int startPosn, int appendLength){ System.out.println(new String(buffer)); buff.put(buffer, startPosn, appendLength); } public void read(int start,int end) throws IOException{ DataInputStream in = new DataInputStream(new ByteArrayInputStream(this.buff.array(),start,end)); readFields(in); in.close(); } public void read() throws IOException { DataInputStream in = new DataInputStream(new ByteArrayInputStream(this.buff.array(),0,this.buff.position())); readFields(in); in.close(); } @Override public String toString() { return objId+"_"+ oid +"_"+time; } public void clear() { if(this.buff != null){ this.buff.clear(); } } /*public static void main(String []a){ ByteBuffer buff = null; buff.put(new byte[]{},0,10); }*/ }
[ "tom@RIMS005.mjsindia.com" ]
tom@RIMS005.mjsindia.com
fd6ddf06df660335ed02b186f7ae399f66eefc4d
4d7a45066c85c2f1288ad2d7e41cb5cef9aa6c85
/src/main/java/com/example/demo/config/SecurityConfig.java
988e07d578e950987793fa307bb96435a6087ccb
[]
no_license
MinhHoangCao/SpringGoogle
7417e6c0dcb8ccf28ef09f688cffb5f0fa5ff5b2
e3c8d1dcd57838d2eb954b75f5e0b33b91700d96
refs/heads/master
2020-05-29T22:31:05.956130
2019-06-06T12:24:19
2019-06-06T12:24:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,378
java
package com.example.demo.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean public BCryptPasswordEncoder passwordEncoder() { BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(); return bCryptPasswordEncoder; } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().passwordEncoder(passwordEncoder()). withUser("hoang").password("$2a$04$Q2Cq0k57zf2Vs/n3JXwzmerql9RzElr.J7aQd3/Sq0fw/BdDFPAj.").roles("ADMIN"); auth.inMemoryAuthentication().passwordEncoder(passwordEncoder()). withUser("cao").password("$2a$04$Q2Cq0k57zf2Vs/n3JXwzmerql9RzElr.J7aQd3/Sq0fw/BdDFPAj.").roles("USER"); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable().authorizeRequests().anyRequest().permitAll(); // http.authorizeRequests().antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')"); // http.authorizeRequests().antMatchers("/user/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')"); // http.authorizeRequests().and().exceptionHandling().accessDeniedPage("/403"); http.authorizeRequests().and().formLogin() .loginProcessingUrl("/j_spring_security_login") .loginPage("/login") .defaultSuccessUrl("/user") .failureUrl("/login?message=error") .usernameParameter("username") .passwordParameter("password") .and().logout().logoutUrl("/j_spring_security_logout").logoutSuccessUrl("/login?message=logout"); } }
[ "cmhoang123@gmil.com" ]
cmhoang123@gmil.com
84cb53efb229979ebf3322d87548f83c8e2514a7
95cbc094b2a5ed9c124aa41d1a21dd0cd62029dc
/src/main/java/com/google/identitytoolkit/GitkitClient.java
df527961800c55374a357c9d35332f5625724b22
[]
no_license
AIMMOTH/gitapp
95b35edd5baf9221ee47333ca1bfb0d10a93c66a
2d26f3f453011400912a0766208cbf2ee836867d
refs/heads/master
2020-12-24T13:35:59.757111
2015-02-05T14:26:34
2015-02-05T14:26:34
30,232,797
2
1
null
null
null
null
UTF-8
Java
false
false
19,523
java
/* * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.identitytoolkit; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.gson.JsonObject; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.security.SignatureException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.logging.Logger; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; /** * Google Identity Toolkit client library. This class is the only interface that third party * developers needs to know to integrate Gitkit with their backend server. Main features are * Gitkit token verification and Gitkit remote API wrapper. */ public class GitkitClient { @VisibleForTesting static final String GITKIT_API_BASE = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/"; private static final Logger logger = Logger.getLogger(GitkitClient.class.getName()); private final JsonTokenHelper tokenHelper; private final RpcHelper rpcHelper; private final String widgetUrl; private final String cookieName; /** * Constructs a Gitkit client. * * @param clientId Google oauth2 web application client id. Audience in Gitkit token must match * this client id. * @param serviceAccountEmail Google service account email. * @param keyStream Google service account private p12 key stream. * @param widgetUrl Url of the Gitkit widget, must starting with /. * @param cookieName Gitkit cookie name. Used to extract Gitkit token from incoming http request. * @param httpSender Concrete http sender when Gitkit client needs to call Gitkit remote API. * @param serverApiKey Server side API key in Google Developer Console. */ public GitkitClient( String clientId, String serviceAccountEmail, InputStream keyStream, String widgetUrl, String cookieName, HttpSender httpSender, String serverApiKey) { rpcHelper = new RpcHelper(httpSender, GITKIT_API_BASE, serviceAccountEmail, keyStream); tokenHelper = new JsonTokenHelper(clientId, rpcHelper, serverApiKey); this.widgetUrl = widgetUrl; this.cookieName = cookieName; } /** * Constructs a Gitkit client from a JSON config file * * @param configPath Path to JSON configuration file * @return Gitkit client */ // public static GitkitClient createFromJson(String configPath) throws JSONException, IOException { // JSONObject configData = // new JSONObject( // StandardCharsets.UTF_8.decode( // ByteBuffer.wrap(Files.readAllBytes(Paths.get(configPath)))) // .toString()); // // return new GitkitClient.Builder() // .setGoogleClientId(configData.getString("clientId")) // .setServiceAccountEmail(configData.getString("serviceAccountEmail")) // .setKeyStream(new FileInputStream(configData.getString("serviceAccountPrivateKeyFile"))) // .setWidgetUrl(configData.getString("widgetUrl")) // .setCookieName(configData.getString("cookieName")) // .setServerApiKey(configData.optString("serverApiKey", null)) // .build(); // } /** * Verifies a Gitkit token. * * @param token token string to be verified. * @return Gitkit user if token is valid. * @throws GitkitClientException if token has invalid signature */ public GitkitUser validateToken(String token) throws GitkitClientException { if (token == null) { return null; } try { JsonObject jsonToken = tokenHelper.verifyAndDeserialize(token).getPayloadAsJsonObject(); return new GitkitUser() .setLocalId(jsonToken.get(JsonTokenHelper.ID_TOKEN_USER_ID).getAsString()) .setEmail(jsonToken.get(JsonTokenHelper.ID_TOKEN_EMAIL).getAsString()) .setCurrentProvider(jsonToken.has(JsonTokenHelper.ID_TOKEN_PROVIDER) ? jsonToken.get(JsonTokenHelper.ID_TOKEN_PROVIDER).getAsString() : null); } catch (SignatureException e) { throw new GitkitClientException(e); } } /** * Verifies Gitkit token in http request. * * @param request http request * @return Gitkit user if valid token is found in the request. * @throws GitkitClientException if there is token but signature is invalid */ public GitkitUser validateTokenInRequest(HttpServletRequest request) throws GitkitClientException { Cookie[] cookies = request.getCookies(); if (cookieName == null || cookies == null) { return null; } for (Cookie cookie : cookies) { if (cookieName.equals(cookie.getName())) { return validateToken(cookie.getValue()); } } return null; } /** * Gets user info from GITkit service using Gitkit token. Can be used to verify a Gitkit token * remotely. * * @param token the gitkit token. * @return Gitkit user info if token is valid. * @throws GitkitClientException if request is invalid * @throws GitkitServerException for Gitkit server error */ public GitkitUser getUserByToken(String token) throws GitkitClientException, GitkitServerException { GitkitUser gitkitUser = validateToken(token); if (gitkitUser == null) { throw new GitkitClientException("invalid gitkit token"); } try { JSONObject result = rpcHelper.getAccountInfo(token); JSONObject jsonUser = result.getJSONArray("users").getJSONObject(0); return jsonToUser(jsonUser) // gitkit server does not return current provider .setCurrentProvider(gitkitUser.getCurrentProvider()); } catch (JSONException e) { throw new GitkitServerException(e); } } /** * Gets user info given an email. * * @param email user email. * @return Gitkit user info. * @throws GitkitClientException if request is invalid * @throws GitkitServerException for Gitkit server error */ public GitkitUser getUserByEmail(String email) throws GitkitClientException, GitkitServerException { Preconditions.checkNotNull(email); try { JSONObject result = rpcHelper.getAccountInfoByEmail(email); return jsonToUser(result.getJSONArray("users").getJSONObject(0)); } catch (JSONException e) { throw new GitkitServerException(e); } } /** * Gets user info given a user id. * * @param localId user identifier at Gitkit. * @return Gitkit user info. * @throws GitkitClientException if request is invalid * @throws GitkitServerException for Gitkit server error */ public GitkitUser getUserByLocalId(String localId) throws GitkitClientException, GitkitServerException { Preconditions.checkNotNull(localId); try { JSONObject result = rpcHelper.getAccountInfoById(localId); return jsonToUser(result.getJSONArray("users").getJSONObject(0)); } catch (JSONException e) { throw new GitkitServerException(e); } } /** * Gets all user info of this web site. Underlying requests are send with default pagination size. * * @return lazy iterator over all user accounts. */ public Iterator<GitkitUser> getAllUsers() { return getAllUsers(null); } /** * Gets all user info of this web site. Underlying requests are paginated and send on demand with * given size. * * @param resultsPerRequest pagination size * @return lazy iterator over all user accounts. */ public Iterator<GitkitUser> getAllUsers(final Integer resultsPerRequest) { return new DownloadIterator<GitkitUser>() { private String nextPageToken = null; @Override protected Iterator<GitkitUser> getNextResults() { try { JSONObject response = rpcHelper.downloadAccount(nextPageToken, resultsPerRequest); nextPageToken = response.has("nextPageToken") ? response.getString("nextPageToken") : null; if (response.has("users")) { return jsonToList(response.getJSONArray("users")).iterator(); } } catch (JSONException e) { logger.warning(e.getMessage()); } catch (GitkitServerException e) { logger.warning(e.getMessage()); } catch (GitkitClientException e) { logger.warning(e.getMessage()); } return ImmutableSet.<GitkitUser>of().iterator(); } }; } /** * Updates a user info at Gitkit server. * * @param user user info to be updated. * @return the updated user info * @throws GitkitClientException for invalid request * @throws GitkitServerException for server error */ public GitkitUser updateUser(GitkitUser user) throws GitkitClientException, GitkitServerException { try { return jsonToUser(rpcHelper.updateAccount(user)); } catch (JSONException e) { throw new GitkitServerException(e); } } /** * Uploads multiple user accounts to Gitkit server. * * @param hashAlgorithm hash algorithm. Supported values are HMAC_SHA256, HMAC_SHA1, HMAC_MD5, * PBKDF_SHA1, MD5 and SCRYPT. * @param hashKey key of hash algorithm * @param users list of user accounts to be uploaded * @throws GitkitClientException for invalid request * @throws GitkitServerException for server error */ public void uploadUsers(String hashAlgorithm, byte[] hashKey, List<GitkitUser> users) throws GitkitServerException, GitkitClientException { rpcHelper.uploadAccount(hashAlgorithm, hashKey, users); } /** * Deletes a user account at Gitkit server. * * @param user user to be deleted. * @throws GitkitClientException for invalid request * @throws GitkitServerException for server error */ public void deleteUser(GitkitUser user) throws GitkitServerException, GitkitClientException { deleteUser(user.getLocalId()); } /** * Deletes a user account at Gitkit server. * * @param localId user id to be deleted. * @throws GitkitClientException for invalid request * @throws GitkitServerException for server error */ public void deleteUser(String localId) throws GitkitServerException, GitkitClientException { rpcHelper.deleteAccount(localId); } /** * Gets out-of-band response. Used by oob endpoint for ResetPassword and ChangeEmail operation. * The web site needs to send user an email containing the oobUrl in the response. The user needs * to click the oobUrl to finish the operation. * * @param req http request for the oob endpoint * @return the oob response. * @throws GitkitServerException */ public OobResponse getOobResponse(HttpServletRequest req) throws GitkitServerException { String gitkitToken = lookupCookie(req, cookieName); return getOobResponse(req, gitkitToken); } /** * Gets out-of-band response. Used by oob endpoint for ResetPassword and ChangeEmail operation. * The web site needs to send user an email containing the oobUrl in the response. The user needs * to click the oobUrl to finish the operation. * * @param req http request for the oob endpoint * @param gitkitToken Gitkit token of authenticated user, required for ChangeEmail operation * @return the oob response. * @throws GitkitServerException */ public OobResponse getOobResponse(HttpServletRequest req, String gitkitToken) throws GitkitServerException { try { String action = req.getParameter("action"); if ("resetPassword".equals(action)) { String oobLink = buildOobLink(req, buildPasswordResetRequest(req), action); return new OobResponse( req.getParameter("email"), null, oobLink, OobAction.RESET_PASSWORD); } else if ("changeEmail".equals(action)) { if (gitkitToken == null) { return new OobResponse("login is required"); } else { String oobLink = buildOobLink(req, buildChangeEmailRequest(req, gitkitToken), action); return new OobResponse( req.getParameter("oldEmail"), req.getParameter("newEmail"), oobLink, OobAction.CHANGE_EMAIL); } } else { return new OobResponse("unknown request"); } } catch (JSONException e) { throw new GitkitServerException(e); } catch (GitkitClientException e) { return new OobResponse(e.getMessage()); } } public static Builder newBuilder() { return new Builder(); } private String lookupCookie(HttpServletRequest request, String cookieName) { Cookie[] cookies = request.getCookies(); if (cookies == null) { return null; } for (Cookie cookie : cookies) { if (cookieName.equals(cookie.getName())) { return cookie.getValue(); } } return null; } private String buildOobLink(HttpServletRequest req, JSONObject resetReq, String modeParam) throws GitkitClientException, GitkitServerException, JSONException { try { JSONObject result = rpcHelper.getOobCode(resetReq); String code = result.getString("oobCode"); return widgetUrl + "?mode=" + modeParam + "&oobCode=" + URLEncoder.encode(code, "UTF-8"); } catch (UnsupportedEncodingException e) { // should never happen throw new GitkitServerException(e); } } private JSONObject buildPasswordResetRequest(HttpServletRequest req) throws JSONException { return new JSONObject() .put("email", req.getParameter("email")) .put("userIp", req.getRemoteAddr()) .put("challenge", req.getParameter("challenge")) .put("captchaResp", req.getParameter("response")) .put("requestType", "PASSWORD_RESET"); } private JSONObject buildChangeEmailRequest(HttpServletRequest req, String gitkitToken) throws JSONException { return new JSONObject() .put("email", req.getParameter("oldEmail")) .put("userIp", req.getRemoteAddr()) .put("newEmail", req.getParameter("newEmail")) .put("idToken", gitkitToken) .put("requestType", "NEW_EMAIL_ACCEPT"); } /** * Gitkit out-of-band actions. */ public enum OobAction { RESET_PASSWORD, CHANGE_EMAIL } /** * Wrapper class containing the out-of-band responses. */ public class OobResponse { private static final String SUCCESS_RESPONSE = "{\"success\": true}"; private static final String ERROR_PREFIX = "{\"error\": "; private final String email; private final String newEmail; private final Optional<String> oobUrl; private final OobAction oobAction; private final String responseBody; private final String recipient; public OobResponse(String responseBody) { this(null, null, Optional.<String>absent(), null, ERROR_PREFIX + responseBody + " }"); } public OobResponse(String email, String newEmail, String oobUrl, OobAction oobAction) { this(email, newEmail, Optional.of(oobUrl), oobAction, SUCCESS_RESPONSE); } public OobResponse(String email, String newEmail, Optional<String> oobUrl, OobAction oobAction, String responseBody) { this.email = email; this.newEmail = newEmail; this.oobUrl = oobUrl; this.oobAction = oobAction; this.responseBody = responseBody; this.recipient = newEmail == null ? email : newEmail; } public Optional<String> getOobUrl() { return oobUrl; } public OobAction getOobAction() { return oobAction; } public String getResponseBody() { return responseBody; } public String getEmail() { return email; } public String getNewEmail() { return newEmail; } public String getRecipient() { return recipient; } } /** * Builder class to construct Gitkit client instance. */ public static class Builder { private String clientId; private HttpSender httpSender = new HttpSender(); private String widgetUrl; private String serviceAccountEmail; private InputStream keyStream; private String serverApiKey; private String cookieName = "gtoken"; public Builder setGoogleClientId(String clientId) { this.clientId = clientId; return this; } public Builder setWidgetUrl(String url) { this.widgetUrl = url; return this; } public Builder setKeyStream(InputStream keyStream) { this.keyStream = keyStream; return this; } public Builder setServiceAccountEmail(String serviceAccountEmail) { this.serviceAccountEmail = serviceAccountEmail; return this; } public Builder setCookieName(String cookieName) { this.cookieName = cookieName; return this; } public Builder setHttpSender(HttpSender httpSender) { this.httpSender = httpSender; return this; } public Builder setServerApiKey(String serverApiKey) { this.serverApiKey = serverApiKey; return this; } public GitkitClient build() { return new GitkitClient(clientId, serviceAccountEmail, keyStream, widgetUrl, cookieName, httpSender, serverApiKey); } } private List<GitkitUser> jsonToList(JSONArray accounts) throws JSONException { List<GitkitUser> list = Lists.newLinkedList(); for (int i = 0; i < accounts.length(); i++) { list.add(jsonToUser(accounts.getJSONObject(i))); } return list; } private GitkitUser jsonToUser(JSONObject jsonUser) throws JSONException { GitkitUser user = new GitkitUser() .setLocalId(jsonUser.getString("localId")) .setEmail(jsonUser.getString("email")) .setName(jsonUser.optString("displayName")) .setPhotoUrl(jsonUser.optString("photoUrl")) .setProviders(jsonUser.optJSONArray("providerUserInfo")); if (jsonUser.has("providerUserInfo")) { JSONArray fedInfo = jsonUser.getJSONArray("providerUserInfo"); List<GitkitUser.ProviderInfo> providerInfo = new ArrayList<GitkitUser.ProviderInfo>(); for (int idp = 0; idp < fedInfo.length(); idp++) { JSONObject provider = fedInfo.getJSONObject(idp); providerInfo.add(new GitkitUser.ProviderInfo( provider.getString("providerId"), provider.getString("federatedId"), provider.optString("displayName"), provider.optString("photoUrl"))); } user.setProviders(providerInfo); } return user; } }
[ "Carl@Carl-Dator" ]
Carl@Carl-Dator
c4d2110e0112b881337b3f938bf4c5c33483631f
a976af8054c09aa3ec573bac156980ad851a0ab7
/crmchat/vendor/alipaysdk/easysdk/java/src/main/java/com/alipay/easysdk/marketing/openlife/models/AlipayOpenPublicLifeMsgRecallResponse.java
7e6692d489b088183dc8810b15cb80a7cb1b2feb
[ "MIT" ]
permissive
yabaoer/CRMchat
1277df300298ea8bf688cb08f75d0de9c2ce4df0
5aec898bcbc3b8d94db50ebc8a8be4ecd36b263a
refs/heads/main
2023-08-28T07:08:09.126019
2021-11-09T03:14:06
2021-11-09T03:14:06
461,561,412
1
0
MIT
2022-02-20T17:24:12
2022-02-20T17:24:11
null
UTF-8
Java
false
false
890
java
// This file is auto-generated, don't edit it. Thanks. package com.alipay.easysdk.marketing.openlife.models; import com.aliyun.tea.*; public class AlipayOpenPublicLifeMsgRecallResponse extends TeaModel { @NameInMap("http_body") @Validation(required = true) public String httpBody; @NameInMap("code") @Validation(required = true) public String code; @NameInMap("msg") @Validation(required = true) public String msg; @NameInMap("sub_code") @Validation(required = true) public String subCode; @NameInMap("sub_msg") @Validation(required = true) public String subMsg; public static AlipayOpenPublicLifeMsgRecallResponse build(java.util.Map<String, ?> map) throws Exception { AlipayOpenPublicLifeMsgRecallResponse self = new AlipayOpenPublicLifeMsgRecallResponse(); return TeaModel.build(map, self); } }
[ "136327134@qq.com" ]
136327134@qq.com
f475a667ea149fc6e848f663747124bbc9f85fd2
967d736eae4c5791ed9c7da80f570cc8efae88c2
/core/src/main/java/ru/mipt/engocab/data/json/custom/DictionarySerializer.java
050df6e3dcf9d6fd46ed2df9d879cfbb12ee4b78
[ "Apache-2.0" ]
permissive
ushakov-av/engocab
b619a0a5293fcff93eabaac70b523bdfd6176de4
cd011047680cce3d6d4ee3ac1d2950ac6fede987
refs/heads/master
2021-01-22T05:51:03.854324
2015-02-08T21:13:42
2015-02-08T21:13:42
27,241,997
0
0
null
null
null
null
UTF-8
Java
false
false
4,378
java
package ru.mipt.engocab.data.json.custom; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import ru.mipt.engocab.core.model.*; import static ru.mipt.engocab.data.json.custom.Fields.*; import java.io.IOException; import java.util.List; /** * @author Alexander Ushakov */ public class DictionarySerializer extends JsonSerializer<Dictionary> { @Override public void serialize(Dictionary dictionary, JsonGenerator jgen, SerializerProvider provider) throws IOException { jgen.writeStartObject(); jgen.writeFieldName(DICTIONARY); jgen.writeStartObject(); { for (WordContainer container : dictionary.getContainers()) { WordKey wordKey = container.getWordKey(); String key = wordKey.getWord() + "|" + PartOfSpeech.value(wordKey.getPartOfSpeech()) + "|" + wordKey.getNumber(); jgen.writeFieldName(key); jgen.writeStartObject(); { serializeWord(wordKey, jgen); List<WordRecord> records = container.getRecords(); records.sort((WordRecord r1, WordRecord r2) -> Integer.compare(r1.getIndex(), r2.getIndex())); jgen.writeFieldName(RECORDS); jgen.writeStartArray(); { for (WordRecord record : records) { jgen.writeStartObject(); { jgen.writeStringField(ID, record.getId()); jgen.writeNumberField(INDEX, record.getIndex()); jgen.writeStringField(TRANSLATION, record.getTranslation()); jgen.writeStringField(TIP, record.getTip()); jgen.writeStringField(DESCRIPTION, record.getDescription()); // Examples jgen.writeFieldName(EXAMPLES); jgen.writeStartArray(); { for (Example example : record.getExamples()) { serializeExample(example, jgen); } } jgen.writeEndArray(); // Synonyms jgen.writeFieldName(SYNONYMS); jgen.writeStartArray(); { for (Synonym synonym : record.getSynonyms()) { } } jgen.writeEndArray(); // Tags jgen.writeFieldName(TAGS); jgen.writeStartArray(); { for (String tag : record.getTags()) { jgen.writeString(tag); } } jgen.writeEndArray(); } jgen.writeEndObject(); } } jgen.writeEndArray(); } jgen.writeEndObject(); } } jgen.writeEndObject(); jgen.writeEndObject(); } private void serializeWord(WordKey wordKey, JsonGenerator jgen) throws IOException { jgen.writeStringField(WORD, wordKey.getWord()); jgen.writeStringField(POS, wordKey.getPartOfSpeech().toString()); jgen.writeNumberField(NUMBER, wordKey.getNumber()); jgen.writeStringField(TRANSCRIPTION, wordKey.getTranscription()); } private void serializeExample(Example example, JsonGenerator jgen) throws IOException { jgen.writeStartObject(); jgen.writeStringField(EX_WORD, example.getWordExample()); jgen.writeStringField(EX_TRANS, example.getTranslationExample()); jgen.writeStringField(EX_PHRASE, example.getPhrase()); jgen.writeEndObject(); } }
[ "ushakov.av@gmail.com" ]
ushakov.av@gmail.com
dd5829d4eca2766c9beafb23d51d912424fee539
39af93bb1493c15a20745075ad14d4ee6b3deea6
/src/main/java/entity/MstKota.java
e9ab3894bade0146bcfb4f8c4a26875126841841
[]
no_license
ikraam21/ZKProject
711f7bbff1f1e3354aa0252cc91c34113af62988
9b1d06624f43560db9c8ed6a21a1e0e34c7ba871
refs/heads/master
2021-05-07T06:22:46.005992
2017-11-23T01:31:09
2017-11-23T01:31:09
111,749,275
0
0
null
null
null
null
UTF-8
Java
false
false
570
java
package entity; public class MstKota { private String kodeKota; private String namaKota; private MstProvinsi mstProvinsi; public String getKodeKota() { return kodeKota; } public void setKodeKota(String kodeKota) { this.kodeKota = kodeKota; } public String getNamaKota() { return namaKota; } public void setNamaKota(String namaKota) { this.namaKota = namaKota; } public MstProvinsi getMstProvinsi() { return mstProvinsi; } public void setMstProvinsi(MstProvinsi mstProvinsi) { this.mstProvinsi = mstProvinsi; } }
[ "triap26@gmail.com" ]
triap26@gmail.com
c3c9ae6ea36c9d8b727c364510a99eeec3f8bdc1
bfab0434c481ce035f1c8da1b16a9fd35a031b31
/src/main/java/fi/seco/saha3/model/IRepository.java
723afe7bf5ddba9f28bdf1823f2566ef80e432f5
[]
no_license
swwasp/saha
edfaeb21de68408fec679ee6fc108fe7c12a75f6
171b68da954548c684a41fdb55e8737b17ef8276
refs/heads/master
2020-05-18T09:16:08.769824
2013-05-17T10:00:18
2013-05-17T10:00:18
39,357,961
0
0
null
null
null
null
UTF-8
Java
false
false
368
java
package fi.seco.saha3.model; import java.util.Collection; import java.util.Locale; /** * Common interface for local searches (to the SAHA project model) and * ONKI searches. * */ public interface IRepository { public IResults search(String query, Collection<String> parentRestrictions, Collection<String> typeRestrictions, Locale locale, int maxResults); }
[ "hhamalai@43518cfe-5713-1dcd-c615-06b53fc7efa9" ]
hhamalai@43518cfe-5713-1dcd-c615-06b53fc7efa9
00ac077f7409925e9974d29b9c0f8197e53f4076
23d73792759d0a56ae19609ec08ec6ca354ec81d
/src/main/java/page_202/designpatterns/isp/drone004/DriveControllerManager.java
6560d7d4310361d9ac2752547952f8beaa946757
[]
no_license
sout1217/spring_basic
244b91b71fa0f2b8ac75b35686053dc49f67142a
bccb5dc71a1e78336d6319671c54845820c08d74
refs/heads/master
2023-03-26T09:01:09.592309
2021-03-25T13:32:17
2021-03-25T13:32:17
345,038,023
0
0
null
null
null
null
UTF-8
Java
false
false
163
java
package page_202.designpatterns.isp.drone004; public class DriveControllerManager implements DriveController { @Override public void drive() { } }
[ "sout1217@naver.com" ]
sout1217@naver.com
1f6b71d269699fcb1c82e286077c4ce97144f1ad
818ad79c64329ca6df89d4f8520c7b5a976ce9b3
/system_admin/src/main/java/com/system/dao/IBaseDao.java
545e048f9d4ba468549d02152f334d1888740181
[]
no_license
huangchunjian123/leyou
531aa1f06be370f6990bb3c79c07ca8558b047a3
f57b85536ef1919bae8f84001a511a4653284938
refs/heads/master
2020-04-08T11:26:41.324387
2019-01-30T08:29:50
2019-01-30T08:29:50
159,306,185
0
0
null
null
null
null
UTF-8
Java
false
false
805
java
package com.system.dao; import com.system.common.util.Page; import java.io.Serializable; /** * @author zzy */ public interface IBaseDao<T>{ /** * 保存 * @param t * @return */ boolean save(T t); /** * 删除 * @param t * @return */ boolean delete(T t); /** * 根据id批量删除 * @param ids * @return */ boolean delById(Serializable... ids); /** * 更新 * @param t * @return */ boolean update(T t); /** * 根据id查询 * @param id * @return */ T findById(Serializable id); /** * 获取分页 * @param page * @param pageSize * @param args * @return */ Page<T> findPage(int page, int pageSize, Object... args); }
[ "huangchunjian1741@dingtalk.com" ]
huangchunjian1741@dingtalk.com
f040e1be3fb764f7ce02b145a135866917752624
e2990c8ea03e0f5fbea7ef99337cfe4298977280
/mq-service-api/src/main/java/com/mq/biz/bean/KafkaMsgRQ.java
2386746ee50a03ea12f97a74b5d50ed9c6492f08
[ "Apache-2.0" ]
permissive
HeShengJin/mq-kafka
d5a89350bee21f678cc52cfef4351c99350faed2
c21d433915b1beea7d5051d16a5d8878e11ff201
refs/heads/master
2022-02-15T02:19:57.764551
2019-07-27T04:00:26
2019-07-27T04:00:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
720
java
package com.mq.biz.bean; import com.fasterxml.jackson.annotation.JsonInclude; import com.mq.entity.BaseObject; import lombok.Data; import java.util.Date; /** * @version v1.0 * @ClassName KafkaMsgRQ<T> * T:数据的class类型 * @Description 简单的消息请求结构 */ @Data public class KafkaMsgRQ<T> extends BaseObject { //主题 String topic; //消息类型 String msgType; //消息子类型 String msgSubType; //系统ID String systemID; //业务消息主键(eg:订单Id ,商品Id) Object msgKey; //消息数据 @JsonInclude(JsonInclude.Include.NON_NULL) T msgData; //来源Ip String srcHost; //创建时间 private Date createtime; }
[ "huacke@163.com" ]
huacke@163.com
48e3e80d9590a31eb0e76d50af8d9d34a01b07ec
3f89e736cb6c2f3318c378936ee150479a527ffd
/Game of Thrones/src/Allegiance.java
650563859b209d2baf0e4f6c52f7a7f1108c7db4
[]
no_license
zapouria/AspectJ_SOEN6441
526b69a346a73f32613e32a4ebcf2d66b7a5e8e8
297975cffcf593b9feba016265115fae84726bc4
refs/heads/master
2022-04-24T17:17:46.311015
2020-04-27T16:25:35
2020-04-27T16:25:35
259,386,929
0
0
null
null
null
null
UTF-8
Java
false
false
66
java
public interface Allegiance { public void declare(); }
[ "spzahraei@yahoo.com" ]
spzahraei@yahoo.com
aabb0c1b7af3430218a86ade4151f8b8d8329fe8
073d18ec802fc11be9e979b944faba8ec58dce84
/src/utils/LinkedListOrderedList.java
593f78ccc0b7ce8c3355fca01e80867735d5e823
[]
no_license
putinrock1/Assignment1
dd4940f59294dd73ed94dd4ae7849d665e10ccb0
f27588e0ecbda0bd6d1fb8499aeb683862d99647
refs/heads/master
2021-01-20T20:15:05.347797
2016-08-01T16:51:12
2016-08-01T16:51:12
64,667,461
0
0
null
null
null
null
UTF-8
Java
false
false
4,640
java
package utils; import Exceptions.ElementAlreadyExistsException; import Exceptions.EmptyListException; import utils.Interfaces.IOrderedList; /** * @param <T> */ public class LinkedListOrderedList<T extends Comparable<T>> implements IOrderedList<T> { private LinkedListNode<T> first = null; private int length = 0; private int index = 0; /** * adds element in alpha-numeric order * * @param t T * @throws Exception */ @Override public void add(T t) throws Exception { if (this.contains(t)) { throw new ElementAlreadyExistsException("Element already exists in the list"); } LinkedListNode<T> newNode = new LinkedListNode<T>(t, null); if (this.first == null) { first = newNode; } else { if (this.first.getElement().compareTo(t) < 0) { LinkedListNode<T> node = this.first; boolean complete = false; do { if (node.getElement().compareTo(t) < 0) { if (node.getPointer() == null) { node.setPointer(newNode); complete = true; } else if (node.getPointer().getElement().compareTo(t) > 0) { LinkedListNode<T> afterNode = node.getPointer(); node.setPointer(newNode); newNode.setPointer(afterNode); complete = true; } } node = node.getPointer(); } while (!complete); } else { newNode.setPointer(this.first); this.first = newNode; } } this.length++; this.index = length; } /** * removes element at index * * @param i T * @throws Exception */ @Override public void remove(int i) throws Exception { if (this.isEmpty()) { throw new EmptyListException("Cannot remove from an empty list."); } if (i > this.length - 1) { throw new IndexOutOfBoundsException(); } LinkedListNode<T> removedNode = this.getNthNode(i); this.getNthNode(i - 1).setPointer(removedNode.getPointer()); this.length--; } /** * returns the index of an element * * @param t T * @return int */ public int indexOf(T t) { if (this.size() == 0) return -1; int count = 0; LinkedListNode<T> node = this.first; //for each node while (node != null) { if (node.getElement().equals(t)) { return count; } else { count++; node = node.getPointer(); } } count = -1; this.index = count; return count; } /** * returns true if list contains an element * * @param t T * @return boolean */ @Override public boolean contains(T t) { return this.indexOf(t) >= 0; } /** * returns true if list is empty * * @return boolean */ @Override public boolean isEmpty() { return this.first == null; } /** * returns size * * @return int */ @Override public int size() { return this.length; } /** * returns element at index * * @param i int * @return T */ @Override public T get(int i) { return this.getNthNode(i).getElement(); } /** * resets list */ @Override public void reset() { this.first = null; this.length = 0; } /** * gets next element * * @return T */ @Override public T getNext() { this.index++; return this.get(this.index + 1); } /** * returns element at index i * * @param i int * @return T */ private LinkedListNode<T> getNthNode(int i) { if (i > this.length - 1) { throw new IndexOutOfBoundsException(); } int count = 0; LinkedListNode<T> node = this.first; while (count < i) { node = node.getPointer(); count++; } this.index = i; return node; } /** * @return String */ @Override public String toString() { return "LinkedListIndexedList{" + "list={" + first + "}" + ", length=" + length + '}'; } }
[ "surya@thehacker.nvstu.edu" ]
surya@thehacker.nvstu.edu
9107b6bebe259440391c5d9c303327679b742123
abcf66282aabf4136196cfc8a595a44b3521cda9
/java/ORION 11J/Workin3/workin-core/src/main/java/org/workin/utils/reflection/ReflectionUtils.java
f5daaa53ef0023a29497637d31c1bdde370fc942
[]
no_license
leopallas/vieo
bce613c3f2212191116160e23473a3d89a4df03e
1bc2944989b82b10d94fda4d7857c5261fbe3175
refs/heads/master
2016-09-06T00:43:13.509248
2013-11-07T02:04:22
2013-11-07T02:04:22
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,763
java
/** * Copyright (c) 2005-2010 springside.org.cn * * Licensed under the Apache License, Version 2.0 (the "License"); * * $Id: ReflectionUtils.java 1303 2010-11-19 17:04:05Z calvinxiu $ */ package org.workin.utils.reflection; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.Assert; /** * * @author <a href="mailto:yao.angellin@gmail.com">Angellin Yao</a> * */ @SuppressWarnings({ "unchecked", "rawtypes" }) public class ReflectionUtils { public static final String CGLIB_CLASS_SEPARATOR = "$$"; private static Logger logger = LoggerFactory.getLogger(ReflectionUtils.class); /** * Invoke getter method from object * * @param obj * @param propertyName * @return */ public static Object invokeGetterMethod(Object obj, String propertyName) { String getterMethodName = "get" + StringUtils.capitalize(propertyName); return invokeMethod(obj, getterMethodName, new Class[] {}, new Object[] {}); } /** * Invoke setter method. It will find the setter method by class type for value * * @param obj * @param propertyName * @param value */ public static void invokeSetterMethod(Object obj, String propertyName, Object value) { invokeSetterMethod(obj, propertyName, value, null); } /** * Invoke setter method. * * @param obj * @param propertyName * @param value * @param propertyType * Used for finding the setter method, and it will be replace with class type of the value if value is null. */ public static void invokeSetterMethod(Object obj, String propertyName, Object value, Class<?> propertyType) { Class<?> type = propertyType != null ? propertyType : value.getClass(); String setterMethodName = "set" + StringUtils.capitalize(propertyName); invokeMethod(obj, setterMethodName, new Class[] { type }, new Object[] { value }); } /** * Read the property value of the object without using getter method, no matter the method is private or protected. * * @param obj * @param fieldName * @return */ public static Object getFieldValue(final Object obj, final String fieldName) { Field field = getAccessibleField(obj, fieldName); if (field == null) { throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]"); } Object result = null; try { result = field.get(obj); } catch (IllegalAccessException e) { logger.error("Impossibly throw errors: {}", e.getMessage()); } return result; } /** * Set the property value of the object without using getter method, no matter the method is private or protected. * * @param obj * @param fieldName * @param value */ public static void setFieldValue(final Object obj, final String fieldName, final Object value) { Field field = getAccessibleField(obj, fieldName); if (field == null) { throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]"); } try { field.set(obj, value); } catch (IllegalAccessException e) { logger.error("Impossibly throw errors: {}", e.getMessage()); } } /** * Iterator the super class for object, and retrieve the DeclareField, then this method will be forced set to available. * If DeclareFileld not find when super class is Object.class, then return null. * This method is used for situation of one time invoking. * @param obj * @param fieldName * @return */ public static Field getAccessibleField(final Object obj, final String fieldName) { Assert.notNull(obj, "object could not be null."); Assert.hasText(fieldName, "fieldName"); for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) { try { Field field = superClass.getDeclaredField(fieldName); field.setAccessible(true); return field; } catch (NoSuchFieldException e) {//NOSONAR // Field is not defined in this class, continue. } } return null; } /** * Get actual class type for the object AOPed by CGLIB. * * @param clazz * @return */ public static Class<?> getUserClass(Class<?> clazz) { if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) { Class<?> superClass = clazz.getSuperclass(); if (superClass != null && !Object.class.equals(superClass)) { return superClass; } } return clazz; } /** * Directly invoke the specific method, no matter the method is private or protected. * * @param obj * @param methodName * @param parameterTypes * @param args * @return */ public static Object invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes, final Object[] args) { Method method = getAccessibleMethod(obj, methodName, parameterTypes); if (method == null) { throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]"); } try { return method.invoke(obj, args); } catch (Exception e) { throw convertReflectionExceptionToUnchecked(e); } } /** * Iterator the super class for object, and retrieve the DeclareField, then this method will be forced set to available. * If DeclareFileld not find when super class is Object.class, then return null. * This method is used for situation of multiple invoking. 1) Use this method to get Method; 2) Invoke Method.invoke(Object obj, Object... args) * * @param obj * @param methodName * @param parameterTypes * @return */ public static Method getAccessibleMethod(final Object obj, final String methodName, final Class<?>... parameterTypes) { Assert.notNull(obj, "object could not be null."); for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) { try { Method method = superClass.getDeclaredMethod(methodName, parameterTypes); method.setAccessible(true); return method; } catch (NoSuchMethodException e) {//NOSONAR // Field is not defined in this class, continue. } } return null; } /** * Get super generic type defined in class. If not found, then return Object.class * eg. * public UserDao extends HibernateDao<User> * @param clazz The class to introspect * @return the first generic declaration, or Object.class if cannot be determined */ public static <T> Class<T> getSuperClassGenericType(final Class clazz) { return getSuperClassGenericType(clazz, 0); } /** * Get super generic type defined in class. If not found, then return Object.class * eg. * public UserDao extends HibernateDao<User,Long> * * @param clazz The class to introspect * @param index the Index of the generic declaration,start from 0. * @return the index generic declaration, or Object.class if cannot be determined */ public static Class getSuperClassGenericType(final Class clazz, final int index) { Type genType = clazz.getGenericSuperclass(); if (!(genType instanceof ParameterizedType)) { logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType"); return Object.class; } Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); if (index >= params.length || index < 0) { logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: " + params.length); return Object.class; } if (!(params[index] instanceof Class)) { logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter"); return Object.class; } return (Class) params[index]; } /** * Translate checked exception occurred when reflect to unchecked exception. * @param e * @return */ public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) { if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException || e instanceof NoSuchMethodException) { return new IllegalArgumentException("Reflection Exception.", e); } else if (e instanceof InvocationTargetException) { return new RuntimeException("Reflection Exception.", ((InvocationTargetException) e).getTargetException()); } else if (e instanceof RuntimeException) { return (RuntimeException) e; } return new RuntimeException("Unexpected Checked Exception.", e); } }
[ "leopallas@gmail.com" ]
leopallas@gmail.com
a5f31956608bff445f352f945b039e162385b13f
90eb7a131e5b3dc79e2d1e1baeed171684ef6a22
/sources/p005b/p096l/p097a/p113c/p131e/p136e/C2507tk.java
fef301f8722c4d01761ed053434c49c54eb6a8ab
[]
no_license
shalviraj/greenlens
1c6608dca75ec204e85fba3171995628d2ee8961
fe9f9b5a3ef4a18f91e12d3925e09745c51bf081
refs/heads/main
2023-04-20T13:50:14.619773
2021-04-26T15:45:11
2021-04-26T15:45:11
361,799,768
0
0
null
null
null
null
UTF-8
Java
false
false
1,643
java
package p005b.p096l.p097a.p113c.p131e.p136e; import android.os.Parcel; import android.os.Parcelable; import androidx.annotation.NonNull; import p005b.p006a.p007a.p024o.C0823f; import p005b.p096l.p097a.p113c.p119b.p122m.p123v.C1948a; /* renamed from: b.l.a.c.e.e.tk */ public final class C2507tk extends C1948a { public static final Parcelable.Creator<C2507tk> CREATOR = new C2531uk(); /* renamed from: g */ public String f4322g; /* renamed from: h */ public String f4323h; /* renamed from: i */ public String f4324i; /* renamed from: j */ public String f4325j; /* renamed from: k */ public String f4326k; /* renamed from: l */ public String f4327l; /* renamed from: m */ public String f4328m; public C2507tk() { } public C2507tk(String str, String str2, String str3, String str4, String str5, String str6, String str7) { this.f4322g = str; this.f4323h = str2; this.f4324i = str3; this.f4325j = str4; this.f4326k = str5; this.f4327l = str6; this.f4328m = str7; } public final void writeToParcel(@NonNull Parcel parcel, int i) { int w0 = C0823f.m403w0(parcel, 20293); C0823f.m395s0(parcel, 2, this.f4322g, false); C0823f.m395s0(parcel, 3, this.f4323h, false); C0823f.m395s0(parcel, 4, this.f4324i, false); C0823f.m395s0(parcel, 5, this.f4325j, false); C0823f.m395s0(parcel, 6, this.f4326k, false); C0823f.m395s0(parcel, 7, this.f4327l, false); C0823f.m395s0(parcel, 8, this.f4328m, false); C0823f.m331A0(parcel, w0); } }
[ "73280944+shalviraj@users.noreply.github.com" ]
73280944+shalviraj@users.noreply.github.com
177daf2761e488cf0ea8b770937999e36a1bad90
a28252ea8a3a684f22bde87e3d242635c93464b7
/src/test/java/com/project/bookstore/repository/BookRepositoryTest.java
86fc3a67dad75c65481724d617c4dd4526088216
[]
no_license
jrt0241/bookstore-back
55b7c0d4ef3bc6547f6ddff92c99de51bf2af4ca
4372e0a5aa40e7c8bb65181f2dbcc083eb29e633
refs/heads/master
2021-06-27T05:28:14.760632
2017-08-27T20:09:22
2017-08-27T20:09:22
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,359
java
package com.project.bookstore.repository; import com.project.bookstore.model.Book; import com.project.bookstore.model.Language; import com.project.bookstore.util.IsbnGenerator; import com.project.bookstore.util.NumberGenerator; import com.project.bookstore.util.TextUtil; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.EmptyAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; import javax.inject.Inject; import java.util.Date; import static org.junit.Assert.*; // This is a Test on Repository Class to check if all the Database related functionality are working properly @RunWith(Arquillian.class) public class BookRepositoryTest { @Inject private BookRepository bookRepository; // Since we are catching the exception here we expect the test to pass. If we don't put //Expection expected statement we shall get error in out tests. @Test(expected=Exception.class) public void findWithInvalidId(){ bookRepository.find(null); } @Test(expected=Exception.class) public void createInvalidBook(){ //Here we pass title as null and test the functionality. //initially without any changes/bean validations the title takes // null values and test passes. But it is not desirable. Book book = new Book("isnb",null,12F,123,Language.ENGLISH,new Date(),"http://image","description"); book=bookRepository.create(book); Long bookId= book.getId(); } @org.junit.Test public void create() throws Exception { //Test Counting Books assertEquals(Long.valueOf(0), bookRepository.countAll()); assertEquals(0, bookRepository.findAll().size()); //create a book Book book = new Book("isnb","a title",12F,123,Language.ENGLISH,new Date(),"http://image","description"); book=bookRepository.create(book); Long bookId= book.getId(); // Check created book assertNotNull(bookId); //Find Created book Book bookFound= bookRepository.find(bookId); //check the found book is correct assertEquals("a title",bookFound.getTitle()); assertTrue(bookFound.getIsbn().startsWith("13")); //Test Counting Books assertEquals(Long.valueOf(1), bookRepository.countAll()); assertEquals(1, bookRepository.findAll().size()); //Deleting the Book bookRepository.delete(bookId); assertEquals(Long.valueOf(0), bookRepository.countAll()); assertEquals(0, bookRepository.findAll().size()); } @Deployment public static JavaArchive createDeployment() { return ShrinkWrap.create(JavaArchive.class) .addClass(BookRepository.class)// add all depending classes over here in package or it will throw errors .addClass(Book.class) .addClass(Language.class) .addClass(TextUtil.class) .addClass(NumberGenerator.class) .addClass(IsbnGenerator.class) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml") .addAsManifestResource("META-INF/test-persistence.xml", "persistence.xml"); } }
[ "shreeram.malreddy@gmail.com" ]
shreeram.malreddy@gmail.com
205679456cb5dcfe0afd3ba9a28d3e4e893d320c
1236de321654fc48cfd8102d903c3867162785bc
/src/main/java/com/therealdanvega/config/CacheConfiguration.java
454a18efac8c62251267a322ba41e9eb527d85e9
[]
no_license
johnwr-response/a4jd-jhipster-tasks
0c9f65707759501e5fb51675fa1e1420d52fe1f1
1ab1497eada04dc30ffddb9c4e818c1059d09719
refs/heads/master
2023-07-28T11:22:46.233343
2020-04-19T14:00:34
2020-04-19T14:00:34
257,007,317
0
0
null
2023-07-11T14:00:26
2020-04-19T13:33:04
Java
UTF-8
Java
false
false
2,354
java
package com.therealdanvega.config; import java.time.Duration; import org.ehcache.config.builders.*; import org.ehcache.jsr107.Eh107Configuration; import org.hibernate.cache.jcache.ConfigSettings; import io.github.jhipster.config.JHipsterProperties; import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer; import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer; import org.springframework.cache.annotation.EnableCaching; import org.springframework.context.annotation.*; @Configuration @EnableCaching public class CacheConfiguration { private final javax.cache.configuration.Configuration<Object, Object> jcacheConfiguration; public CacheConfiguration(JHipsterProperties jHipsterProperties) { JHipsterProperties.Cache.Ehcache ehcache = jHipsterProperties.getCache().getEhcache(); jcacheConfiguration = Eh107Configuration.fromEhcacheCacheConfiguration( CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class, ResourcePoolsBuilder.heap(ehcache.getMaxEntries())) .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(ehcache.getTimeToLiveSeconds()))) .build()); } @Bean public HibernatePropertiesCustomizer hibernatePropertiesCustomizer(javax.cache.CacheManager cacheManager) { return hibernateProperties -> hibernateProperties.put(ConfigSettings.CACHE_MANAGER, cacheManager); } @Bean public JCacheManagerCustomizer cacheManagerCustomizer() { return cm -> { createCache(cm, com.therealdanvega.repository.UserRepository.USERS_BY_LOGIN_CACHE); createCache(cm, com.therealdanvega.repository.UserRepository.USERS_BY_EMAIL_CACHE); createCache(cm, com.therealdanvega.domain.User.class.getName()); createCache(cm, com.therealdanvega.domain.Authority.class.getName()); createCache(cm, com.therealdanvega.domain.User.class.getName() + ".authorities"); // jhipster-needle-ehcache-add-entry }; } private void createCache(javax.cache.CacheManager cm, String cacheName) { javax.cache.Cache<Object, Object> cache = cm.getCache(cacheName); if (cache == null) { cm.createCache(cacheName, jcacheConfiguration); } } }
[ "52628290+johnwr-response@users.noreply.github.com" ]
52628290+johnwr-response@users.noreply.github.com
bbc89f4f4ad008fb2e8e72c9c53e64bd6b879da7
3c6864459c06b5281a249e649dee0be918113953
/src/main/java/com/adityathebe/bitcoin/wallet/Wallet.java
b2f952d7442e030d34df5d2cb6741bda5b832a36
[]
no_license
adityathebe/bitcoin-java
c8afd6c38202903196a83bae38d1b3b959ec0091
680d7da30ea65f16b708d774f42719d69fe9a51f
refs/heads/master
2021-05-23T01:04:40.882834
2020-04-11T07:33:57
2020-04-11T07:33:57
253,165,519
2
0
null
null
null
null
UTF-8
Java
false
false
4,852
java
package com.adityathebe.bitcoin.wallet; import com.adityathebe.bitcoin.core.Address; import com.adityathebe.bitcoin.core.ECPrivateKey; import com.adityathebe.bitcoin.core.ECPublicKey; import com.adityathebe.bitcoin.crypto.ECDSA; import com.adityathebe.bitcoin.crypto.ECDSASignature; import com.adityathebe.bitcoin.utils.Base58; import static com.adityathebe.bitcoin.crypto.Crypto.hash256; import static com.adityathebe.bitcoin.script.ScriptOpCodes.*; import static com.adityathebe.bitcoin.utils.Utils.*; public class Wallet { private ECPrivateKey privateKey; private ECPublicKey publicKey; private Address address; public Wallet() { init(); } public Wallet(String privateKeyHex) { privateKey = new ECPrivateKey(privateKeyHex); init(); } private void init() { if (this.privateKey == null) { this.privateKey = new ECPrivateKey(); } this.publicKey = new ECPublicKey(this.privateKey); this.address = new Address(this.publicKey); } public ECPrivateKey getPrivateKey() { return privateKey; } public Address getAddress() { return address; } public ECPublicKey getPublicKey() { return publicKey; } public static String getHashFromAddress(String address) throws Exception { String dec = bytesToHex(Base58.decodeChecked(address)); return dec.substring(2); } /** * @param address P2PKH Legacy address * @param satoshi Amount in Satoshi * @return The hex encoded transaction */ public String createTransaction(String address, int satoshi, String parentTxHash, String inputIdx, String prevScriptPubKey) throws Exception { String nVersion = "01000000"; String inCount = "01"; // Input String prevOutHash = bytesToHex(changeEndian(hexToBytes(parentTxHash))); String prevOutN = inputIdx; String prevScriptPubKeyLength = Integer.toHexString(prevScriptPubKey.length() / 2); String sequence = "ffffffff"; // Output String outCount = "01"; String amount = Integer.toHexString(satoshi); while (amount.length() < 16) { amount = "0" + amount; } amount = bytesToHex(changeEndian(hexToBytes(amount))); // Finalize the output String hashFromAddress = getHashFromAddress(address); String hashLength = Integer.toHexString((hashFromAddress.length() / 2)); String scriptPubKey = Integer.toHexString(OP_DUP) + Integer.toHexString(OP_HASH160) + hashLength + hashFromAddress + Integer.toHexString(OP_EQUALVERIFY) + Integer.toHexString(OP_CHECKSIG); String scriptPubKeyLength = Integer.toHexString(scriptPubKey.length() / 2); String lockField = "00000000"; String hashCodeType = "01000000"; // Craft temp tx data String preTxData = nVersion + inCount + prevOutHash + prevOutN + prevScriptPubKeyLength + prevScriptPubKey + sequence + outCount + amount + scriptPubKeyLength + scriptPubKey + lockField + hashCodeType; System.out.println("\nPreTxData: " + preTxData); byte[] doubleHash = hash256(preTxData); ECDSASignature signature = ECDSA.sign(privateKey, doubleHash); String finalSignature = signature.getDerEncoded() + "01"; System.out.println("Sig verified: " + ECDSA.verify(signature, getPublicKey(), doubleHash)); // Create actual scriptSig String sigLength = Integer.toHexString(finalSignature.length() / 2); String pubKeyLength = Integer.toHexString((publicKey.getCompressed().length() / 2)); String scriptSig = sigLength + finalSignature + pubKeyLength + publicKey.getCompressed(); String scriptSigLength = Integer.toHexString(scriptSig.length() / 2); return nVersion + inCount + prevOutHash + prevOutN + scriptSigLength + scriptSig + sequence + outCount + amount + scriptPubKeyLength + scriptPubKey + lockField; } public static void main(String[] args) throws Exception { System.out.println("Wallet"); Wallet w = new Wallet("3E402774803FCBCA1CA7CC841E55A659182CCE5FF3A249275DA7EDC32FDF8BB2"); System.out.println("Private Key (Hex): " + w.getPrivateKey().getHex()); System.out.println("Public Key (Hex): " + w.getPublicKey().getCompressed()); System.out.println("Address: " + w.getAddress().getTestNetAddressHex()); String tx = w.createTransaction( "2NGZrVvZG92qGYqzTLjCAewvPZ7JE8S8VxE", 9900, "7e5c93f34b09877abea9b2f1793469e54d196aae8f7a434351bfd3ca4c428410", "00000000", "76a914745e794502c6307f10e71c66e066c8d7f714066688ac"); System.out.println("Tx (Raw):" + tx); System.out.println("Tx Hash: " + bytesToHex(changeEndian(hash256(tx)))); } }
[ "thebeaditya@gmail.com" ]
thebeaditya@gmail.com
fcc1b1dc7b9315c5c65c09ed591c285422e8cab4
5c41bba1b92814583f8dffa2cabc443a1e03d4c8
/BOEC-ejb/src/java/entity/Bill.java
fc48bf8a12f38d6dda44bffcb54261071a8400a0
[]
no_license
AnhHNPTIT/ProjectA-D
e59ae03b7417d6c11d133718dc134684406b6725
3652e3cd2320cb135988da5e42f65f81b391caa4
refs/heads/master
2022-07-07T18:18:23.853000
2020-05-13T11:29:19
2020-05-13T11:29:19
263,607,685
0
0
null
null
null
null
UTF-8
Java
false
false
5,379
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 entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; 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.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; /** * * @author skull */ @Entity @Table(name = "bill") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Bill.findAll", query = "SELECT b FROM Bill b"), @NamedQuery(name = "Bill.findById", query = "SELECT b FROM Bill b WHERE b.id = :id"), @NamedQuery(name = "Bill.findByEmployeePersonId", query = "SELECT b FROM Bill b WHERE b.employeePersonId = :employeePersonId"), @NamedQuery(name = "Bill.findBySumary", query = "SELECT b FROM Bill b WHERE b.sumary = :sumary"), @NamedQuery(name = "Bill.findByDate", query = "SELECT b FROM Bill b WHERE b.date = :date"), @NamedQuery(name = "Bill.findByNote", query = "SELECT b FROM Bill b WHERE b.note = :note"), @NamedQuery(name = "Bill.findByOrderShipCompanyCompanyId", query = "SELECT b FROM Bill b WHERE b.orderShipCompanyCompanyId = :orderShipCompanyCompanyId"), @NamedQuery(name = "Bill.findByEmployeeId", query = "SELECT b FROM Bill b WHERE b.employeeId = :employeeId")}) public class Bill implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "Id") private Integer id; @Basic(optional = false) @NotNull @Column(name = "EmployeePersonId") private int employeePersonId; @Basic(optional = false) @NotNull @Column(name = "Sumary") private float sumary; @Column(name = "Date") @Temporal(TemporalType.DATE) private Date date; @Size(max = 255) @Column(name = "Note") private String note; @Column(name = "OrderShipCompanyCompanyId") private Integer orderShipCompanyCompanyId; @Basic(optional = false) @NotNull @Column(name = "EmployeeId") private int employeeId; @JoinColumn(name = "EmployeePersonId2", referencedColumnName = "PersonId") @ManyToOne(optional = false) private Employee employeePersonId2; @JoinColumn(name = "ItemOrderId", referencedColumnName = "Id") @ManyToOne(optional = false) private ItemOrder orderId; public Bill() { } public Bill(Integer id) { this.id = id; } public Bill(Integer id, int employeePersonId, float sumary, int employeeId) { this.id = id; this.employeePersonId = employeePersonId; this.sumary = sumary; this.employeeId = employeeId; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public int getEmployeePersonId() { return employeePersonId; } public void setEmployeePersonId(int employeePersonId) { this.employeePersonId = employeePersonId; } public float getSumary() { return sumary; } public void setSumary(float sumary) { this.sumary = sumary; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public Integer getOrderShipCompanyCompanyId() { return orderShipCompanyCompanyId; } public void setOrderShipCompanyCompanyId(Integer orderShipCompanyCompanyId) { this.orderShipCompanyCompanyId = orderShipCompanyCompanyId; } public int getEmployeeId() { return employeeId; } public void setEmployeeId(int employeeId) { this.employeeId = employeeId; } public Employee getEmployeePersonId2() { return employeePersonId2; } public void setEmployeePersonId2(Employee employeePersonId2) { this.employeePersonId2 = employeePersonId2; } public ItemOrder getOrderId() { return orderId; } public void setOrderId(ItemOrder orderId) { this.orderId = orderId; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Bill)) { return false; } Bill other = (Bill) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "entity.Bill[ id=" + id + " ]"; } }
[ "anhhn97.ptit@gmail.com" ]
anhhn97.ptit@gmail.com
d32d9d16740748887a3341f8ef5365d3989a151d
aa7f74b59db0604a8bdc64ea4a5031f0bc31fd54
/src/com/suminghui/bycar/util/StringUtil.java
e3fc1693170b65ff0fe9ce19092acdaf0f745908
[]
no_license
tianxiao-zp/buycar
53f4f145a6cbd893a521ed2f9d8e10ea695e15dd
9b5fcf6843ff21b4d8d1fe7ca985ed59bf94fa4b
refs/heads/master
2021-05-30T19:41:41.150462
2016-02-26T09:36:45
2016-02-26T09:36:45
null
0
0
null
null
null
null
UTF-8
Java
false
false
10,866
java
package com.suminghui.bycar.util; import java.beans.PropertyDescriptor; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; public class StringUtil { public static final String EMPTY = ""; public static String intToString(int data) { return EMPTY + data; } public static boolean isEmpty(String data) { if (data == null || data.equals("")) { return true; } return false; } public static String htmlEncode(String txt) { if (txt != null) { txt = replace(txt, "&", "&amp;"); txt = replace(txt, "&amp;amp;", "&amp;"); txt = replace(txt, "&amp;quot;", "&quot;"); txt = replace(txt, "\"", "&quot;"); txt = replace(txt, "&amp;lt;", "&lt;"); txt = replace(txt, "<", "&lt;"); txt = replace(txt, "&amp;gt;", "&gt;"); txt = replace(txt, ">", "&gt;"); txt = replace(txt, "&amp;nbsp;", "&nbsp;"); } return txt; } public static String[] split(String strSource, String strDiv) { int arynum = 0, intIdx = 0, intIdex = 0; int div_length = strDiv.length(); if (strSource.compareTo("") != 0) { if (strSource.indexOf(strDiv) != -1) { intIdx = strSource.indexOf(strDiv); for (int intCount = 1; ; intCount++) { if (strSource.indexOf(strDiv, intIdx + div_length) != -1) { intIdx = strSource.indexOf(strDiv, intIdx + div_length); arynum = intCount; } else { arynum += 2; break; } } } else { arynum = 1; } } else { arynum = 0; } intIdx = 0; intIdex = 0; String[] returnStr = new String[arynum]; if (strSource.compareTo("") != 0) { if (strSource.indexOf(strDiv) != -1) { intIdx = strSource.indexOf(strDiv); returnStr[0] = strSource.substring(0, intIdx); for (int intCount = 1; ; intCount++) { if (strSource.indexOf(strDiv, intIdx + div_length) != -1) { intIdex = strSource.indexOf(strDiv, intIdx + div_length); returnStr[intCount] = strSource.substring(intIdx + div_length, intIdex); intIdx = strSource.indexOf(strDiv, intIdx + div_length); } else { returnStr[intCount] = strSource.substring(intIdx + div_length, strSource.length()); break; } } } else { returnStr[0] = strSource.substring(0, strSource.length()); return returnStr; } } else { return returnStr; } return returnStr; } public static String doWithNull(Object o) { if(o == null) { return ""; } else{ String returnValue = o.toString(); if(returnValue.equalsIgnoreCase("null")) { return ""; } else { return returnValue.trim(); } } } public static String replace(String str, String strSub, String strRpl) { String[] tmp = split(str, strSub); String returnstr = ""; if (tmp.length != 0) { returnstr = tmp[0]; for (int i = 0; i < tmp.length - 1; i++) { returnstr = doWithNull(returnstr) + strRpl + tmp[i + 1]; } } return doWithNull(returnstr); } // 数字正则 private static final Pattern RE_NUMBER = Pattern.compile("[0-9]+"); // 字符正则 private static final Pattern RE_CHARACTER = Pattern.compile("\\w+"); private static final Pattern Html_TAG = Pattern.compile("<style.*?</style>|<script.*?</script>|<([^>]*)>"); // 千分位显示 private static final DecimalFormat THOUSANDS_TAG = new DecimalFormat("#,###"); /** * 将一个字符数组中每两个字符中间加入一个字符 * * @param strs * 要处理的字符数组 * @param s * 要加入的字符 * @return */ public static String join(String[] strs, String s) { if (null == strs) return ""; StringBuilder sb = new StringBuilder(); for (int i = 0; i < strs.length; i++) { sb.append(strs[i]); if (i != strs.length - 1) sb.append(s); } return sb.toString(); } /** * 将一个字符串分割成一个字符数组 * * @param str * 要分割的字符串 * @param separatorChar * 分隔符 * @return */ public static String[] split(String str, char separatorChar) { return StringUtils.split(str, separatorChar); } /** * 将一个字符串通过指定字符分割后存入list列表 * * @param str * 要转换的字符串 * @param separatorChar * 分隔符 * @return */ public static List<String> splitToList(String str, char separatorChar) {// if (StringUtil.isBlank(str)) { return null; } List<String> list = new ArrayList<String>(); for (String s : StringUtil.split(str, separatorChar)) { list.add(s); } return list; } /** * 判断字符串 是不是为空 * * @param str * 要判断的字符串 * @return */ public static boolean isBlank(String str) { if (null == str) return true; if ("".equals(str.replaceAll(" ", " ").trim())) return true; return false; } /** * 获取随机长度的一个字符串 * * @param j * 要获得的字符串长度 * @return */ public static String toRandom(int j) { StringBuilder s = new StringBuilder(); for (int i = 0; i < j; i++) { Random r = new Random(); int n = r.nextInt(3); if (n == 0) { s.append(r.nextInt(9)); } else if (n == 1) { s.append((char) ('a' + Math.random() * 26)); } else { s.append((char) ('A' + Math.random() * 26)); } } return s.toString(); } private static char[] numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz" + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray(); /** * 获取随机长度的一个字符串 * * @param length * 要获得的字符串长度 * @return */ public static String randomString(int length) { if (length < 1) { return null; } // Create a char buffer to put random letters and numbers in. char[] randBuffer = new char[length]; for (int i = 0; i < randBuffer.length; i++) { randBuffer[i] = numbersAndLetters[new Random().nextInt(71)]; } return new String(randBuffer); } /** * 判断字符串是不是符合邮箱格式 * * @param mailAddr * 要校验的字符串 * @return 是返回true 否则 false */ public static boolean isMailAddr(String mailAddr) { String check = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$"; Pattern regex = Pattern.compile(check); Matcher matcher = regex.matcher(mailAddr); return matcher.matches(); } /** * 判断字符串是不是数字 * * @param str * 要校验的字符串 * @return */ public static boolean isNumber(String str) { return (str != null) && RE_NUMBER.matcher(str).matches(); } /** * 将一个字符串列表转换为字符串并用指定的符号分割 * * @param list * 要转换的字符串列表 * @param separatorChar * 指定的分割符 * @return */ public static String getListToString(List<String> list, char separatorChar) { if (null != list && list.size() > 0) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < list.size(); i++) { sb.append(list.get(i)); if (i != list.size() - 1) { sb.append(separatorChar); } } return sb.toString(); } return null; } /** * 取出html里所有标签和<scritp><style>内容 * * @param html * html内容 * @param replace * 替换内容 * @return */ public static String getHtmlToText(String html, String replace) { Matcher m = Html_TAG.matcher(html); return m.replaceAll(replace); } /** * 判断是否只包含字符 * * @param s * @return */ public static boolean regularCharacter(String s) { return RE_CHARACTER.matcher(s).matches(); } /** * 解析bean对象属性 * * @param p * @return */ public static String getDisplayName(PropertyDescriptor p) { if (null != p && null != p.getReadMethod()) { if (p.getPropertyType() == boolean.class) { return p.getReadMethod().getName().substring(2); } return p.getReadMethod().getName().substring(3); } return ""; } /** * 获取千分位 * * @param s * @return ##,###.00 */ public static String getThousands(String s) { try { return THOUSANDS_TAG.format(Double.valueOf(s)); } catch (Exception e) { return ""; } } public static void main(String[] args) { String s[] = { "a", "b", "c" }; System.out.println(StringUtil.join(s, ",")); } }
[ "465996346@qq.com" ]
465996346@qq.com
ce2aca7939b85956c9aa00271af927283cf232d3
2b20bb6fd2564da56555808623ef6792bbcb5b0b
/src/com/g4mesoft/graphics3d/Vertex3D.java
a0ab89d63c1bc1678c21bbcca9f4d29405414f7b
[ "MIT" ]
permissive
G4me4u/g4mengine
1ef5323311cc4b769aeccd541bdf8b7903f1060d
ab952d287f3a715d485100a7df562a4b999d2917
refs/heads/master
2021-06-02T19:28:44.356170
2020-06-30T15:56:18
2020-06-30T15:56:18
102,396,417
10
0
null
null
null
null
UTF-8
Java
false
false
1,736
java
package com.g4mesoft.graphics3d; import com.g4mesoft.math.Vec2f; import com.g4mesoft.math.Vec3f; import com.g4mesoft.math.Vec4f; public class Vertex3D { public final Vec4f pos; public final float[] data; public Vertex3D(int numData) { this.pos = new Vec4f(); this.data = new float[numData]; } public Vertex3D(Vec4f pos) { this(pos, 0); } public Vertex3D(Vec4f pos, int numData) { this.pos = pos; this.data = new float[numData]; } public void storeFloat(int location, float input) { data[location] = input; } public float loadFloat(int location) { return data[location]; } public void storeVec2f(int location, Vec2f input) { data[location + 0] = input.x; data[location + 1] = input.y; } public void loadVec2f(int location, Vec2f output) { output.x = data[location + 0]; output.y = data[location + 1]; } public void storeVec3f(int location, Vec3f input) { data[location + 0] = input.x; data[location + 1] = input.y; data[location + 2] = input.z; } public void loadVec3f(int location, Vec3f output) { output.x = data[location + 0]; output.y = data[location + 1]; output.z = data[location + 2]; } public void storeVec4f(int location, Vec4f input) { data[location + 0] = input.x; data[location + 1] = input.y; data[location + 2] = input.z; data[location + 2] = input.w; } public void loadVec4f(int location, Vec4f output) { output.x = data[location + 0]; output.y = data[location + 1]; output.z = data[location + 2]; output.w = data[location + 2]; } public void setVertex(Vertex3D other) { pos.set(other.pos); for (int i = data.length - 1; i >= 0; i--) data[i] = other.data[i]; } public int getNumData() { return data.length; } }
[ "G4me4u@gmail.com" ]
G4me4u@gmail.com
55f1de379e71b2c8734365227d95722c31ce56cf
93b2475fd35a53b863985a820d78573b4df968d1
/Práctica 1 - 2019/src/Punto/pMain.java
cff3c24016238756d8f756d884a56c7f1b18eda1
[]
no_license
josueaquino12/Algoritmos-y-Programaci-n-3
ef36650008a6d84b935c39a45cdb53456a258d9f
97d3872c0c4874bb8f2aa54a23ab6688fa589827
refs/heads/master
2020-06-25T04:30:09.044474
2019-07-29T19:54:12
2019-07-29T19:54:12
199,201,984
0
0
null
null
null
null
UTF-8
Java
false
false
353
java
package Punto; public class pMain { public static void main(String[] args) { Punto p = new Punto (5,3); Punto p1 = new Punto (3,2); Punto p2 = new Punto (7,8); p.imprimir(); p.desplazar(1,1); p.imprimir(); System.out.println("Distancia:----->" + Punto.distancia(p1, p2));; } }
[ "JosBen@DESKTOP-9BFHS37" ]
JosBen@DESKTOP-9BFHS37
fc30b092c46d3a54be320cd17bccdb712795c5a1
4f1577bfef6ec648d91ccb93298867395704eda7
/usertype.core/src/main/java/org/jadira/usertype/dateandtime/joda/PersistentLocalDate.java
dc58ab69c1f7b4d85b44a1b0039b6dd9c53dc566
[ "Apache-2.0" ]
permissive
TorqueITS/jadira-6.0.1.GA
e9b91e6c8ddb4b1f00fcd5b05c28f0e70c28be68
dc644a2260822cecdc472b3649ce447701907111
refs/heads/develop
2021-08-29T21:08:44.503113
2017-12-15T00:58:05
2017-12-15T00:58:05
112,560,991
0
0
Apache-2.0
2017-12-15T01:15:10
2017-11-30T03:41:17
Java
UTF-8
Java
false
false
1,807
java
/* * Copyright 2010, 2011 Christopher Pheby * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jadira.usertype.dateandtime.joda; import java.sql.Date; import org.hibernate.usertype.ParameterizedType; import org.jadira.usertype.dateandtime.joda.columnmapper.DateColumnLocalDateMapper; import org.jadira.usertype.spi.shared.AbstractParameterizedUserType; import org.jadira.usertype.spi.shared.IntegratorConfiguredType; import org.joda.time.LocalDate; /** * Persist {@link LocalDate} via Hibernate. This type shares database * representation with org.joda.time.contrib.hibernate.PersistentLocalDate * * The type is stored using the JVM timezone by default. * * Alternatively provide the 'databaseZone' parameter in the {@link org.joda.time.DateTimeZone#forID(String)} format * to indicate the zone of the database. Be careful to set this carefully. See https://jadira.atlassian.net/browse/JDF-26 * N.B. To use the zone of the JVM for the database zone you can also supply 'jvm' */ public class PersistentLocalDate extends AbstractParameterizedUserType<LocalDate, Date, DateColumnLocalDateMapper> implements ParameterizedType, IntegratorConfiguredType { private static final long serialVersionUID = 2918856421618299370L; }
[ "chris@jadira.co.uk" ]
chris@jadira.co.uk
cddc7cbd05826992702c7f2d72b36bdbec420143
dbba88db0d55aca07a9ad2026fed95e468901d2b
/configclient/src/main/java/com/playground/configclient/controller/TestController.java
b75a4fcbbc264088f87f05ea74824a76f8f003e0
[]
no_license
amit-mittal/spring-cloud-playground
deb451b3374c52994f6ba0d97f9b830c607047ba
acd96afad16b3b91ba16ba24599e4790bef7260b
refs/heads/master
2020-03-27T12:52:24.890277
2018-09-08T08:19:04
2018-09-08T08:19:04
146,575,236
1
0
null
null
null
null
UTF-8
Java
false
false
925
java
package com.playground.configclient.controller; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @Value("${lucky-word}") String luckyWord; @RequestMapping(value = "/", method = RequestMethod.GET) public String getLuckyWord() { return "The lucky word is " + luckyWord; } @RequestMapping(value = "/fail", method = RequestMethod.GET) @HystrixCommand(fallbackMethod = "fallbackMethod") public String doFailedCall() { throw new RuntimeException("Fail!!!!"); } public String fallbackMethod() { return "Don't worry, it's been taken care"; } }
[ "amit.mittal1993@gmail.com" ]
amit.mittal1993@gmail.com
1066e3f55edb4b43c5f8f31c67b38e3d201d3cb6
fe1ca817c8b9478c17b6d81a2a1497fc8a637e41
/src/main/java/org/usfirst/frc/team4028/robot/commands/auton/Auton_PIDTune_spinDown.java
45875910f45cd0aafa6c145585f4ac9babf4e03a
[]
no_license
Team4028/4028-PreBuild-Season-2019
d95665a156f72b829bfcda5903768fe8664226ea
53bc875e37ac11b37490e7de31b9c53237152af5
refs/heads/master
2020-04-09T02:46:54.707642
2018-12-06T22:21:33
2018-12-06T22:21:33
159,953,774
0
0
null
2018-12-07T00:52:44
2018-12-01T14:41:24
Java
UTF-8
Java
false
false
1,211
java
package org.usfirst.frc.team4028.robot.commands.auton; import com.ctre.phoenix.motorcontrol.can.TalonSRX; import com.ctre.phoenix.motorcontrol.ControlMode; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Subsystem; /** * */ public class Auton_PIDTune_spinDown extends Command { private TalonSRX _talon; public Auton_PIDTune_spinDown(Subsystem requiredSubsystem, TalonSRX talon) { _talon = talon; requires(requiredSubsystem); } // Called just before this Command runs the first time protected void initialize() { _talon.configOpenloopRamp(0.0, 10); _talon.set(ControlMode.PercentOutput, 0.0); } // Called repeatedly when this Command is scheduled to run protected void execute() { } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return _talon.getSelectedSensorVelocity(0) == 0; } // Called once after isFinished returns true protected void end() { System.out.println("Motor stopped."); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { _talon.set(ControlMode.PercentOutput, 0); } }
[ "njdonahue17@gmail.com" ]
njdonahue17@gmail.com
1934f8ea4ee14a435275b67231b7d7a2eedb32e2
62ac9c90814470dde6c30c58c7ad94db18acb77f
/src/main/java/kr/or/ddit/mul/mulCalculation.java
58515ca72aa0daf0e8d4bf0f7c1396d0c42e9a52
[]
no_license
DoaOh/lastjsp
ceb4f24efd68fee68a7cecfe62219585d506d554
ca7a85436fc5d34dd1c4cc301e2bf954307b33d5
refs/heads/master
2021-06-14T11:08:15.831074
2019-06-18T09:52:59
2019-06-18T09:52:59
192,501,429
0
0
null
2021-04-22T18:22:51
2019-06-18T08:45:15
JavaScript
UTF-8
Java
false
false
1,075
java
package kr.or.ddit.mul; import java.io.IOException; 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 org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Servlet implementation class mulCalculation */ @WebServlet("/mulCalculation") public class mulCalculation extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger logger = LoggerFactory .getLogger(mulCalculation.class); protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int mul1 = Integer.parseInt(request.getParameter("mul1")); int mul2 = Integer.parseInt(request.getParameter("mul2")); int mul = mul1 * mul2; request.getSession().setAttribute("mulResult", mul); request.getRequestDispatcher("/mul/mulResult.jsp").forward(request, response); } }
[ "8doadoa8@gmail.com" ]
8doadoa8@gmail.com
0dd1edd8906dcb7e2674063feacc107719d0e7d7
f9304c7fb4fe67eafd22c1814afab633977417c6
/src/main/java/com/ailk/listener/weblistener/MyHttpSessionAttributeListener.java
ecb04191a52d874b0eb28f7d63d5839c8c24b04a
[]
no_license
kisshello/watermelon
cf2b01fd49325be546809efcf2463fb3174e0c21
88cc8829d2d66471e8afeb04a0adf646a2deb51f
refs/heads/master
2021-06-25T20:26:40.555265
2020-04-26T02:56:31
2020-04-26T02:56:31
219,471,596
0
0
null
2020-10-13T17:43:29
2019-11-04T10:09:59
Java
UTF-8
Java
false
false
738
java
package com.ailk.listener.weblistener; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; /** * @description: * @author: wanghk3 * @time: 2020/4/5 17:38 */ public class MyHttpSessionAttributeListener implements HttpSessionAttributeListener { @Override public void attributeAdded(HttpSessionBindingEvent se) { System.out.println("向session中添加了属性"); } @Override public void attributeRemoved(HttpSessionBindingEvent se) { System.out.println("从session中移除了属性"); } @Override public void attributeReplaced(HttpSessionBindingEvent se) { System.out.println("session中的属性被替换了"); } }
[ "wanghk3@asiainfo.com" ]
wanghk3@asiainfo.com
0d4b921c87b24f3df749f651a2489a90f045d9af
65ad63c8f9a3798acc2565ed7101f62887c11f79
/src/main/java/com/guoanshequ/dc/das/dao/master/DsPesCustomerStoreMonthMapper.java
495a7a224e5f9019d113f4724647965bb8e61b94
[]
no_license
greatypine/ds
daef5b182769d4f6e23acf8095d7338104bc47f0
6c908fa035c3e77d58d3c2bb1f37fd6afaa4d254
refs/heads/master
2020-12-03T03:45:50.806074
2019-04-15T01:43:06
2019-04-15T01:43:06
95,770,084
0
0
null
null
null
null
UTF-8
Java
false
false
951
java
package com.guoanshequ.dc.das.dao.master; import java.util.Map; import org.springframework.stereotype.Repository; import com.guoanshequ.dc.das.datasource.DataSource; /** * * @author gbl * */ @Repository @DataSource("master") public interface DsPesCustomerStoreMonthMapper { /** * * @Title: deleteDsCustomer * @Description: TODO 按月删除门店用户 * 2018年4月16日 * @param @param param * @param @return * @return Integer * @throws * @author gbl */ public Integer deleteDsPesCustomer(Map<String,String> param); /** * * @Title: insertDsPesCustomer * @Description: TODO 按月产生门店用户数据(包括门店编号,城市,超10元拉新用户量,消费用户量,超10元消费用户量) * 2018年4月16日 * @param @return * @return int * @throws * @author gbl */ public Integer addDsPesCustomer(Map<String,String> param); }
[ "greatypine@163.com" ]
greatypine@163.com
d6027147831bcb66b5db872c668543967ce8db89
38c34ff168b64a67e969bd81a60556ad0b17e62c
/cbn-20170912/src/main/java/com/aliyun/cbn20170912/models/CreateCenResponseBody.java
1e281a3d541a8b519796d2c6b16fbe8fd439798d
[ "Apache-2.0" ]
permissive
bestchendong/alibabacloud-java-sdk
1474344c006641fbab882af4c277b5cbb343ea80
737c2b966c5e46903d5875e269c971cb80dd678f
refs/heads/master
2023-04-15T05:34:29.011451
2021-04-22T09:14:46
2021-04-22T09:14:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
875
java
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.cbn20170912.models; import com.aliyun.tea.*; public class CreateCenResponseBody extends TeaModel { @NameInMap("RequestId") public String requestId; @NameInMap("CenId") public String cenId; public static CreateCenResponseBody build(java.util.Map<String, ?> map) throws Exception { CreateCenResponseBody self = new CreateCenResponseBody(); return TeaModel.build(map, self); } public CreateCenResponseBody setRequestId(String requestId) { this.requestId = requestId; return this; } public String getRequestId() { return this.requestId; } public CreateCenResponseBody setCenId(String cenId) { this.cenId = cenId; return this; } public String getCenId() { return this.cenId; } }
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
924b7baf61592fedb576944e8b58e790beb1adb8
6253283b67c01a0d7395e38aeeea65e06f62504b
/decompile/app/Mms/src/main/java/com/android/mms/ui/HwCustAttachmentTypeSelectorAdapter.java
762c6ec4da14f9506f3caad24e2e41bb17f91941
[]
no_license
sufadi/decompile-hw
2e0457a0a7ade103908a6a41757923a791248215
4c3efd95f3e997b44dd4ceec506de6164192eca3
refs/heads/master
2023-03-15T15:56:03.968086
2017-11-08T03:29:10
2017-11-08T03:29:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
585
java
package com.android.mms.ui; import android.content.Context; import com.android.mms.ui.IconListAdapter.IconListItem; import java.util.List; public class HwCustAttachmentTypeSelectorAdapter { public void addExtItem(List<IconListItem> list, Context context) { } public boolean isCustLocationEnable() { return false; } public boolean isImModeNow() { return false; } public void addSubjectForSimpleUi(Context context, List<IconListItem> list) { } public void removeAdapterOptions(Context context, List<IconListItem> list) { } }
[ "liming@droi.com" ]
liming@droi.com
663092637d33cf0044ad929bec5810e0234d0851
3cc0e129d2a3018c8ed21297b296b992f202919b
/src/ListIterator.java
7b97c681c8dd8e5d44c4dc47c24600896ec0b99a
[]
no_license
shisannafiz/linkedlists
c640abdca5cc4671dcf8894f875176342d11d41d
322d36a9cf9b57f8ce180395f98ac98b8c17614f
refs/heads/master
2022-04-19T04:51:49.872883
2020-04-10T15:44:30
2020-04-10T15:44:30
254,671,945
0
0
null
null
null
null
UTF-8
Java
false
false
224
java
public interface ListIterator<AnyType> { public void add(AnyType newValue); public void remove(); public boolean hasPrevious(); public boolean hasNext(); public AnyType previous(); public AnyType next(); }
[ "shisannafiz8@gmail.com" ]
shisannafiz8@gmail.com
c2e1a1a0d3a9bab0f06259b8b0df879fa6b1187f
fba8af31d5d36d8a6cf0c341faed98b6cd5ec0cb
/src/main/java/com/alipay/api/response/AlipayMarketingToolFengdieSitesBatchqueryResponse.java
9f9a5e68f4a1b5539b0a82a90326636fa6ed220f
[ "Apache-2.0" ]
permissive
planesweep/alipay-sdk-java-all
b60ea1437e3377582bd08c61f942018891ce7762
637edbcc5ed137c2b55064521f24b675c3080e37
refs/heads/master
2020-12-12T09:23:19.133661
2020-01-09T11:04:31
2020-01-09T11:04:31
null
0
0
null
null
null
null
UTF-8
Java
false
false
780
java
package com.alipay.api.response; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.domain.FengdieSitesListRespModel; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.marketing.tool.fengdie.sites.batchquery response. * * @author auto create * @since 1.0, 2019-05-22 14:32:03 */ public class AlipayMarketingToolFengdieSitesBatchqueryResponse extends AlipayResponse { private static final long serialVersionUID = 3391769776888761643L; /** * 获取云凤蝶站点列表返回值模型 */ @ApiField("data") private FengdieSitesListRespModel data; public void setData(FengdieSitesListRespModel data) { this.data = data; } public FengdieSitesListRespModel getData( ) { return this.data; } }
[ "ben.zy@antfin.com" ]
ben.zy@antfin.com
dbba5f22821928725f0d9e2c27c04dab8d5f89c1
10198516150fe93bc2e00d6e5459c26e160f34ba
/repo/proj3/gitlet/Blob.java
bb66dbbc0c1bfe796af33128670196844f817c2d
[]
no_license
ultraviolex/CS61B
d9669662f989d7d3b26f60c35772f0ccc8b9c615
aead00d32033b63e92de9e543c83857e532ea97b
refs/heads/master
2022-09-11T02:19:41.615204
2020-06-01T21:32:13
2020-06-01T21:32:13
null
0
0
null
null
null
null
UTF-8
Java
false
false
809
java
package gitlet; import java.io.File; import java.io.Serializable; /** Blob class of gitlet. * @author Xiuhui Ming*/ public class Blob implements Serializable { /** Make a blob from a file. * @param f file. */ public Blob(File f) { _fileName = f.getName(); _contents = Utils.readContentsAsString(f); _ID = Utils.sha1("file", _contents); } /** Return filename.*/ public String getfileName() { return _fileName; } /** Return contents. */ public String getcontents() { return _contents; } /** Return ID. */ public String getID() { return _ID; } /** File name. */ private String _fileName; /** Contents of file. */ private String _contents; /** SHA ID. */ private String _ID; }
[ "mingxiuhui@berkeley.edu" ]
mingxiuhui@berkeley.edu
add7a5a82bab2e0bd2d3817f77bbe53ea1ac70ed
45de98b5e10d55f7f87062989dbf689a7c55f4d7
/app/build/generated/source/r/debug/android/support/loader/R.java
84fb44eacb951bfa3f9e32871350ff06f8ee53bf
[]
no_license
tv9nusantaraIT/nine_store_webview
32090522a70f4a79c77624a83d3082b637e1031c
fe009dfb230129bf8041831bbedf17d0d9c05fa3
refs/heads/master
2023-07-08T14:14:21.333332
2021-07-31T19:27:21
2021-07-31T19:27:21
391,444,052
0
0
null
null
null
null
UTF-8
Java
false
false
10,167
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package android.support.loader; public final class R { public static final class attr { public static final int alpha = 0x7f020027; public static final int font = 0x7f02007a; public static final int fontProviderAuthority = 0x7f02007c; public static final int fontProviderCerts = 0x7f02007d; public static final int fontProviderFetchStrategy = 0x7f02007e; public static final int fontProviderFetchTimeout = 0x7f02007f; public static final int fontProviderPackage = 0x7f020080; public static final int fontProviderQuery = 0x7f020081; public static final int fontStyle = 0x7f020082; public static final int fontVariationSettings = 0x7f020083; public static final int fontWeight = 0x7f020084; public static final int ttcIndex = 0x7f02013c; } public static final class color { public static final int notification_action_color_filter = 0x7f040040; public static final int notification_icon_bg_color = 0x7f040041; public static final int ripple_material_light = 0x7f04004b; public static final int secondary_text_default_material_light = 0x7f04004d; } public static final class dimen { public static final int compat_button_inset_horizontal_material = 0x7f05004b; public static final int compat_button_inset_vertical_material = 0x7f05004c; public static final int compat_button_padding_horizontal_material = 0x7f05004d; public static final int compat_button_padding_vertical_material = 0x7f05004e; public static final int compat_control_corner_material = 0x7f05004f; public static final int compat_notification_large_icon_max_height = 0x7f050050; public static final int compat_notification_large_icon_max_width = 0x7f050051; public static final int notification_action_icon_size = 0x7f05005b; public static final int notification_action_text_size = 0x7f05005c; public static final int notification_big_circle_margin = 0x7f05005d; public static final int notification_content_margin_start = 0x7f05005e; public static final int notification_large_icon_height = 0x7f05005f; public static final int notification_large_icon_width = 0x7f050060; public static final int notification_main_column_padding_top = 0x7f050061; public static final int notification_media_narrow_margin = 0x7f050062; public static final int notification_right_icon_size = 0x7f050063; public static final int notification_right_side_padding_top = 0x7f050064; public static final int notification_small_icon_background_padding = 0x7f050065; public static final int notification_small_icon_size_as_large = 0x7f050066; public static final int notification_subtext_size = 0x7f050067; public static final int notification_top_pad = 0x7f050068; public static final int notification_top_pad_large_text = 0x7f050069; } public static final class drawable { public static final int notification_action_background = 0x7f060058; public static final int notification_bg = 0x7f060059; public static final int notification_bg_low = 0x7f06005a; public static final int notification_bg_low_normal = 0x7f06005b; public static final int notification_bg_low_pressed = 0x7f06005c; public static final int notification_bg_normal = 0x7f06005d; public static final int notification_bg_normal_pressed = 0x7f06005e; public static final int notification_icon_background = 0x7f06005f; public static final int notification_template_icon_bg = 0x7f060060; public static final int notification_template_icon_low_bg = 0x7f060061; public static final int notification_tile_bg = 0x7f060062; public static final int notify_panel_notification_icon_bg = 0x7f060063; } public static final class id { public static final int action_container = 0x7f07000d; public static final int action_divider = 0x7f07000f; public static final int action_image = 0x7f070010; public static final int action_text = 0x7f070016; public static final int actions = 0x7f070017; public static final int async = 0x7f07001f; public static final int blocking = 0x7f070022; public static final int chronometer = 0x7f07002a; public static final int forever = 0x7f07003e; public static final int icon = 0x7f070044; public static final int icon_group = 0x7f070045; public static final int info = 0x7f070048; public static final int italic = 0x7f07004a; public static final int line1 = 0x7f07004c; public static final int line3 = 0x7f07004d; public static final int normal = 0x7f070055; public static final int notification_background = 0x7f070056; public static final int notification_main_column = 0x7f070057; public static final int notification_main_column_container = 0x7f070058; public static final int right_icon = 0x7f070062; public static final int right_side = 0x7f070063; public static final int tag_transition_group = 0x7f070083; public static final int tag_unhandled_key_event_manager = 0x7f070084; public static final int tag_unhandled_key_listeners = 0x7f070085; public static final int text = 0x7f070086; public static final int text2 = 0x7f070087; public static final int time = 0x7f07008a; public static final int title = 0x7f07008b; } public static final class integer { public static final int status_bar_notification_info_maxnum = 0x7f080004; } public static final class layout { public static final int notification_action = 0x7f09001d; public static final int notification_action_tombstone = 0x7f09001e; public static final int notification_template_custom_big = 0x7f09001f; public static final int notification_template_icon_group = 0x7f090020; public static final int notification_template_part_chronometer = 0x7f090021; public static final int notification_template_part_time = 0x7f090022; } public static final class string { public static final int status_bar_notification_info_overflow = 0x7f0b0029; } public static final class style { public static final int TextAppearance_Compat_Notification = 0x7f0c00ec; public static final int TextAppearance_Compat_Notification_Info = 0x7f0c00ed; public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0c00ee; public static final int TextAppearance_Compat_Notification_Time = 0x7f0c00ef; public static final int TextAppearance_Compat_Notification_Title = 0x7f0c00f0; public static final int Widget_Compat_NotificationActionContainer = 0x7f0c0158; public static final int Widget_Compat_NotificationActionText = 0x7f0c0159; } public static final class styleable { public static final int[] ColorStateListItem = { 0x010101a5, 0x0101031f, 0x7f020027 }; public static final int ColorStateListItem_android_color = 0; public static final int ColorStateListItem_android_alpha = 1; public static final int ColorStateListItem_alpha = 2; public static final int[] FontFamily = { 0x7f02007c, 0x7f02007d, 0x7f02007e, 0x7f02007f, 0x7f020080, 0x7f020081 }; public static final int FontFamily_fontProviderAuthority = 0; public static final int FontFamily_fontProviderCerts = 1; public static final int FontFamily_fontProviderFetchStrategy = 2; public static final int FontFamily_fontProviderFetchTimeout = 3; public static final int FontFamily_fontProviderPackage = 4; public static final int FontFamily_fontProviderQuery = 5; public static final int[] FontFamilyFont = { 0x01010532, 0x01010533, 0x0101053f, 0x0101056f, 0x01010570, 0x7f02007a, 0x7f020082, 0x7f020083, 0x7f020084, 0x7f02013c }; public static final int FontFamilyFont_android_font = 0; public static final int FontFamilyFont_android_fontWeight = 1; public static final int FontFamilyFont_android_fontStyle = 2; public static final int FontFamilyFont_android_ttcIndex = 3; public static final int FontFamilyFont_android_fontVariationSettings = 4; public static final int FontFamilyFont_font = 5; public static final int FontFamilyFont_fontStyle = 6; public static final int FontFamilyFont_fontVariationSettings = 7; public static final int FontFamilyFont_fontWeight = 8; public static final int FontFamilyFont_ttcIndex = 9; public static final int[] GradientColor = { 0x0101019d, 0x0101019e, 0x010101a1, 0x010101a2, 0x010101a3, 0x010101a4, 0x01010201, 0x0101020b, 0x01010510, 0x01010511, 0x01010512, 0x01010513 }; public static final int GradientColor_android_startColor = 0; public static final int GradientColor_android_endColor = 1; public static final int GradientColor_android_type = 2; public static final int GradientColor_android_centerX = 3; public static final int GradientColor_android_centerY = 4; public static final int GradientColor_android_gradientRadius = 5; public static final int GradientColor_android_tileMode = 6; public static final int GradientColor_android_centerColor = 7; public static final int GradientColor_android_startX = 8; public static final int GradientColor_android_startY = 9; public static final int GradientColor_android_endX = 10; public static final int GradientColor_android_endY = 11; public static final int[] GradientColorItem = { 0x010101a5, 0x01010514 }; public static final int GradientColorItem_android_color = 0; public static final int GradientColorItem_android_offset = 1; } }
[ "tv9nusantarait@gmail.com" ]
tv9nusantarait@gmail.com
0de781bd573cb3d05e3d72aacd88b558ee9efc1d
f692fe03c7dc6d7f5f3197276ad36ae799643794
/recruiting-core/src/test/java/it/f2informatica/test/services/gateway/mongodb/UserRepositoryGatewayMongoDBTest.java
520b927d04dd040c4e6f5787e46e2a96fcd42cbd
[ "Apache-2.0" ]
permissive
ShreySangal/recruiting-old-style
52076bad4b82502d0e5e9261484625d1dd0c39a9
9de7cf6a60b4b478b65477f8b79b179a0e0eea06
refs/heads/master
2021-11-13T10:02:48.774134
2016-03-09T09:23:54
2016-03-09T09:23:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,655
java
/* * ============================================================================= * * Copyright (c) 2014, Fernando Aspiazu * * 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 it.f2informatica.test.services.gateway.mongodb; import com.google.common.collect.Lists; import com.mongodb.CommandResult; import com.mongodb.WriteResult; import it.f2informatica.core.Authority; import it.f2informatica.core.gateway.EntityToModelConverter; import it.f2informatica.core.gateway.UserRepositoryGateway; import it.f2informatica.core.gateway.mongodb.UserRepositoryGatewayMongoDB; import it.f2informatica.core.model.RoleModel; import it.f2informatica.core.model.UserModel; import it.f2informatica.mongodb.domain.Role; import it.f2informatica.mongodb.domain.User; import it.f2informatica.mongodb.repositories.RoleRepository; import it.f2informatica.mongodb.repositories.UserRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import java.util.List; import static it.f2informatica.mongodb.domain.builder.RoleBuilder.role; import static it.f2informatica.mongodb.domain.builder.UserBuilder.user; import static it.f2informatica.test.services.builder.UserModelDataBuilder.userModel; import static org.fest.assertions.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class UserRepositoryGatewayMongoDBTest { @Mock private MongoTemplate mongoTemplate; @Mock private UserRepository userRepository; @Mock private RoleRepository roleRepository; @Mock private EntityToModelConverter<User, UserModel> userToModelConverter; @InjectMocks private UserRepositoryGateway userRepositoryGateway = new UserRepositoryGatewayMongoDB(); @Test public void findUserById() { when(userRepository.findOne(anyString())).thenReturn(getUser()); when(userToModelConverter.convert(getUser())).thenReturn(userModel().build()); UserModel userResponse = userRepositoryGateway.findUserById("52820f6f34bdf55624303fc1"); assertThat(userResponse.getUsername()).isEqualTo("jhon_kent77"); } @Test public void findByUsername() { when(userRepository.findByUsername(anyString())).thenReturn(getUser()); when(userToModelConverter.convert(getUser())).thenReturn(userModel().build()); UserModel userResponse = userRepositoryGateway.findByUsername("jhon_kent77"); assertThat(userResponse.getUsername()).isEqualTo("jhon_kent77"); } @Test public void findByUsernameAndPassword() { when(userRepository.findByUsernameAndPassword(anyString(), anyString())).thenReturn(getUser()); when(userToModelConverter.convert(getUser())).thenReturn(userModel().build()); UserModel userResponse = userRepositoryGateway.findByUsernameAndPassword("jhon_kent77", "okisteralio"); assertThat(userResponse.getUsername()).isEqualTo("jhon_kent77"); } @Test public void saveUser() { User user = getUser(); when(userRepository.save(any(User.class))).thenReturn(user); when(userToModelConverter.convert(user)).thenReturn(userModel().build()); UserModel userModelSaved = userRepositoryGateway.saveUser(userModel().build()); assertThat(userModelSaved.getUsername()).isEqualTo("jhon_kent77"); } private User getUser() { return user() .withId("52820f6f34bdf55624303fc1") .withUsername("jhon_kent77") .withPassword("okisteralio") .withRole(role().thatIsAdministrator()) .build(); } @Test public void loadRoles() { String userAuthority = Authority.ROLE_USER.toString(); RoleModel roleModel = new RoleModel(); roleModel.setRoleName(userAuthority); List<Role> roles = Lists.newArrayList( role().thatIsAdministrator(), role().withAuthorization(userAuthority).build() ); when(roleRepository.findAll()).thenReturn(roles); assertThat(userRepositoryGateway.loadRoles()).hasSize(2).contains(roleModel); } @Test public void findRoleByName() { String roleAdmin = Authority.ROLE_ADMIN.toString(); when(roleRepository.findByName(roleAdmin)).thenReturn(role().thatIsAdministrator()); RoleModel response = userRepositoryGateway.findRoleByName(roleAdmin); assertThat(response.getRoleName()).isEqualTo("ROLE_ADMIN"); } @Test public void updateUser() { stubUpdateSuccess(); userRepositoryGateway.updateUser(userModel().build()); } private void stubUpdateSuccess() { WriteResult writeResultMock = mock(WriteResult.class); CommandResult commandResult = mock(CommandResult.class); when(writeResultMock.getLastError()).thenReturn(commandResult); when(commandResult.ok()).thenReturn(true); when(mongoTemplate.updateFirst( any(Query.class), any(Update.class), any(Class.class)) ).thenReturn(writeResultMock); } }
[ "fumandito@gmail.com" ]
fumandito@gmail.com
4cfadee6822b283820e55d660e2f7bee9b7300eb
cbcc40b1acb557d0e025029dbfa85052caef831a
/src/main/java/com/altimetrik/brs/entity/Reservervation.java
ea4c9ebbbbdbd118d0c354fdf11c6b13ce07e293
[]
no_license
mjkumar-rgda/BusReservationApp
4f032cc1603e3ad1a2497c9785f3a43a67947669
ec437990720453e536517d3e9db068a1cbf92b35
refs/heads/master
2022-12-05T17:18:24.540847
2020-08-29T12:59:34
2020-08-29T12:59:34
291,271,101
0
0
null
null
null
null
UTF-8
Java
false
false
1,073
java
package com.altimetrik.brs.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import lombok.Builder; import lombok.Getter; import lombok.ToString; /** * . * @author: Manoj Kumar. * @version: 1.0. */ @Getter @Builder @ToString @Entity public class Reservervation implements Serializable { private static final long serialVersionUID = 8969328127927352690L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer reservationId; @ManyToOne @JoinColumn(nullable = false, name = "passingerId", updatable = true, insertable = true) @ToString.Exclude private Passinger passinger; @ManyToOne @JoinColumn(nullable = false, name = "busId", updatable = true, insertable = true) @ToString.Exclude private Bus bus; private Date travelDate; private Date dateOfBooking; private String[] bookedSeats; } // end of Bus entity
[ "54305140+mjkumar-rgda@users.noreply.github.com" ]
54305140+mjkumar-rgda@users.noreply.github.com
6cf2c78f2e14e633eda979b73cecb4f739084e5e
3181906569f945626897f4aa700138009b83fd78
/src/main/java/com/example/demo/DemoApplication.java
d5cff8a2da8030c467a162ee24480f4536c77da9
[]
no_license
chloer-nico/FullTextRetrieval2.0
8d54d27f0d52b9a0918c26d66fce34a3f4107d23
494768cad1fe6a25580740fd48cee2ffc38d09a7
refs/heads/master
2023-01-30T13:19:41.123047
2020-12-15T08:49:30
2020-12-15T08:49:30
321,604,556
0
0
null
null
null
null
UTF-8
Java
false
false
1,796
java
package com.example.demo; import com.example.demo.config.Sysconfig; import com.example.demo.lucene.LuceneDao; import org.apache.lucene.document.Document; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import java.util.List; /** * @author dhx */ @SpringBootApplication @EnableConfigurationProperties({Sysconfig.class}) public class DemoApplication implements CommandLineRunner { private final Sysconfig sysconfig; private final LuceneDao luceneDao; /** * DemoApplication的构造函数 * */ public DemoApplication(@Autowired Sysconfig sysconfig, @Autowired LuceneDao luceneDao){ this.sysconfig = sysconfig; this.luceneDao = luceneDao; } public static void main(String[] args){ SpringApplication app = new SpringApplication(DemoApplication.class); app.run(args); } @Override public void run(String... args) throws Exception { //构建索引 // luceneDao.indexDoc(); //搜索 List<Document> documentList=luceneDao.search("学院","学院"); System.out.println("共有数据"+documentList.size()); for(int i=0;i<documentList.size();i++){ System.out.println("第"+i+"条内容标题为————————————\n"+documentList.get(i).get("title")); System.out.println("第"+i+"条内容内容为——————————\n"+documentList.get(i).get("contents")); } //关闭 luceneDao.destroy(); } }
[ "694144275@qq.com" ]
694144275@qq.com
e67d9ae9ddccc4e09424d57e228ea59869704df7
a07b5f7029dd945c77069dd2f1b0fc11d84aa4a5
/src/com/lesson2/calculator/Calculator.java
add04262addaa47e16dd38fbe46b888b32eaf4ec
[]
no_license
titanmet/startjava_test
ef9e7dcf38b90d9beae261d979e18c3b3458dd12
40040f914554dc9e4b7a074e3a6ac6a4584ec73c
refs/heads/master
2023-06-01T11:14:29.448078
2021-06-17T18:43:59
2021-06-17T18:43:59
376,775,943
0
0
null
null
null
null
UTF-8
Java
false
false
1,708
java
package com.startjava.lesson2.calculator; public class Calculator { public double sum; public int num1; public char ch; public int num2; public String answer = "да"; public void setNum1(int num1) { this.num1 = num1; } public void setCh(char ch) { this.ch = ch; } public void setNum2(int num2) { this.num2 = num2; } public String getAnswer() { return answer; } public void setAnswer(String answer) { this.answer = answer; } public void calc(){ switch (ch){ case ('+'): sum = num1 + num2; System.out.println(num1 + " + " + num2 + " = " + sum); break; case ('-'): sum = num1 - num2; System.out.println(num1 + " - " + num2 + " = " + sum); break; case ('*'): sum = num1 * num2; System.out.println(num1 + " * " + num2 + " = " + sum); break; case ('/'): sum = num1 / num2; System.out.println(num1 + " / " + num2 + " = " + sum); break; case ('^'): sum = Math.pow(num1, num2); System.out.println(num1 + " ^ " + num2 + " = " + sum); break; case ('%'): sum = num1 % num2; System.out.println(num1 + " % " + num2 + " = " + sum); break; default: System.out.println("Not operation"); } } }
[ "titanmet@mail.ru" ]
titanmet@mail.ru
f2858d716e2672cb84475364b229af9325f4a7dd
2efa8b58a8682aa731a765cd1db0b6b5a80edba2
/src/main/java/com/thinkgem/jeesite/modules/oa/entity/Leave.java
fae3ec8f6d5ed24eab90deebd9fd9a942fc2efb0
[ "Apache-2.0" ]
permissive
tangsiyi/jeesite-xf
da62699b59737c38709fa2e1b29a432cb7f567c5
3d5bf2c14e05f25c2d150f538aae0e909edd5b11
refs/heads/master
2022-12-23T04:02:09.849446
2019-10-20T12:50:29
2019-10-20T12:50:29
215,002,434
0
0
Apache-2.0
2022-12-16T08:01:02
2019-10-14T09:29:50
JavaScript
UTF-8
Java
false
false
3,866
java
/** * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation */ package com.thinkgem.jeesite.modules.oa.entity; import java.util.Date; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; import org.hibernate.validator.constraints.Length; import com.fasterxml.jackson.annotation.JsonFormat; import com.thinkgem.jeesite.common.persistence.IdEntity; import com.thinkgem.jeesite.modules.sys.utils.DictUtils; /** * 请假Entity * @author liuj * @version 2013-04-05 */ @Entity @Table(name = "oa_leave") @DynamicInsert @DynamicUpdate @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class Leave extends IdEntity<Leave> { private static final long serialVersionUID = 1L; private String reason; // 请假原因 private String processInstanceId; // 流程实例编号 private Date startTime; // 请假开始日期 private Date endTime; // 请假结束日期 private Date realityStartTime; // 实际开始时间 private Date realityEndTime; // 实际结束时间 private String leaveType; // 假种 private String processStatus; //流程状态 private boolean pass; private boolean audit; private String auditRemarks; public Leave() { super(); } public Leave(String id){ this(); this.id = id; } public String getLeaveType() { return leaveType; } public void setLeaveType(String leaveType) { this.leaveType = leaveType; } @Transient public String getLeaveTypeDictLabel() { return DictUtils.getDictLabel(leaveType, "oa_leave_type", ""); } @Length(min=1, max=255) public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @Temporal(TemporalType.TIMESTAMP) @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } @Temporal(TemporalType.TIMESTAMP) @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } @Temporal(TemporalType.TIMESTAMP) @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getRealityStartTime() { return realityStartTime; } public void setRealityStartTime(Date realityStartTime) { this.realityStartTime = realityStartTime; } @Temporal(TemporalType.TIMESTAMP) @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getRealityEndTime() { return realityEndTime; } public void setRealityEndTime(Date realityEndTime) { this.realityEndTime = realityEndTime; } public String getProcessStatus() { return processStatus; } public void setProcessStatus(String processStatus) { this.processStatus = processStatus; } @Transient public boolean isPass() { return pass; } @Transient public void setPass(boolean pass) { this.pass = pass; } @Transient public String getAuditRemarks() { return auditRemarks; } @Transient public void setAuditRemarks(String auditRemarks) { this.auditRemarks = auditRemarks; } @Transient public boolean isAudit() { return audit; } @Transient public void setAudit(boolean audit) { this.audit = audit; } }
[ "271548546@qq.com" ]
271548546@qq.com
85a1909d64e951878de7ee8deabde82977812e35
b6b4977560b197e9ff5b80e746581d714d4311bd
/PythonApi/app/src/main/java/com/seesmile/chat/pythonapi/base/BaseActivity.java
d9af996aff992494b0e1f9e3a5c6caab20c834d2
[]
no_license
SeeSmile/SmileChat
cd9b765e60ac14c3e8122e13ded9fa04f1ab3dcf
0af7a5c589fe0cf0a99a40554747a6b141bcfa75
refs/heads/master
2021-01-20T18:24:17.746161
2016-07-20T09:40:12
2016-07-20T09:40:12
63,326,300
0
0
null
null
null
null
UTF-8
Java
false
false
1,018
java
package com.seesmile.chat.pythonapi.base; import android.content.Context; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.AttributeSet; import android.view.View; import com.seesmile.chat.pythonapi.R; import butterknife.ButterKnife; /** * Created by FuPei on 2016/7/15. */ public class BaseActivity extends AppCompatActivity { @Override public void setContentView(@LayoutRes int layoutResID) { super.setContentView(layoutResID); ButterKnife.inject(this); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); initData(); initView(); } @Override protected void onStart() { super.onStart(); initListener(); } public void initListener() { } public void initData() { } public void initView() { } }
[ "1092443178@qq.com" ]
1092443178@qq.com
33d57fb776ff2df60a5613fc706e04259710262b
1e8673f3e5277b63bfc419078f06ae9454fa2f5d
/InterfaceSpringBoot/src/main/java/app/Application.java
6867998605b3cfadb026cdf6bc69f53519fb9a5e
[]
no_license
reyinever/interfaceAutoTest
50e775d848e45e3dc7b0c45f58eeae32185d5833
47101f2785de3c5d424f18011338b9f0c1bcb139
refs/heads/master
2022-07-08T18:37:10.655627
2019-07-31T08:18:40
2019-07-31T08:18:40
139,323,764
0
0
null
2022-06-21T01:32:34
2018-07-01T11:32:57
Java
UTF-8
Java
false
false
420
java
package app; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @ComponentScan("com.tester") //托管的包 public class Application { //程序的入口 public static void main(String[] args){ SpringApplication.run(Application.class,args); } }
[ "reyi_never@163.com" ]
reyi_never@163.com
655401c654cc27fb5975248fbfe03115167a37b0
1930db0b5515570c0364e3e069661fdc4496fa74
/Interface/src/Sample.java
355702761ffe98a665e8bd1d2b438ebd0d12a6d2
[]
no_license
MANUCHANDRAN94/java_study
287e7167a2e74fa8ef6758df13e36c5db33f6ea2
016575e70b91107254e4981deb5f0c4c9460c63c
refs/heads/master
2022-07-12T11:02:58.050755
2020-05-15T09:25:19
2020-05-15T09:25:19
264,151,264
0
0
null
null
null
null
UTF-8
Java
false
false
374
java
public class Sample implements Hello { public void Ontext(String text) { System.out.println("3constructor"); System.out.println(text); System.out.println("4constructor"); } Sample() { TextScanner t=new TextScanner(this); System.out.println("Sample constructor"); t.scan(); } public static void main(String[] args) { Sample s=new Sample(); } }
[ "m4manu001@gmail.com" ]
m4manu001@gmail.com
2b4fe566ffd7ed66164f34b44f893a5e5e56ebfa
b8bd0161d72c4ca1eca465dde3f2d898ca9f5f39
/src/com/itedu365/best5201/Before.java
a18a975ed421f4f54f8000122a5836c79329bb01
[]
no_license
cakin24/TheBestCodeAndArchitectOptimize
2a3f07242ada411c0533c1587f88f90cf84fca1f
bdc671f410df0a46d89d20f468e4b08ce8f0703a
refs/heads/master
2020-09-15T20:43:05.916235
2019-11-23T07:58:38
2019-11-23T07:58:38
223,552,748
1
0
null
null
null
null
UTF-8
Java
false
false
748
java
/* * 本书配套视频教程网址(架构师系列培训): * www.365itedu.com * 365IT学院,让学习变得更简单! */ package com.itedu365.best5201; /** * * 【Java代码与架构之完美优化——实战经典】 * * 52、避免捕获NullPointerException或Error * * @author 颜廷吉 */ public class Before { // 调用method1 public static void method2() { try { // 抛出AssertionError(Error子类) assert -1 >= 0 : "有负数!"; } catch (Error e) { // 截获Error错误 e.printStackTrace(); } catch (NullPointerException e) { // 截获NullPointerException e.printStackTrace(); } } }
[ "798103175@qq.com" ]
798103175@qq.com
1cdb9cf1e29241be32e08ba636dd918b485433a4
b3c6241c31f563c06ff1b0881652d1f800e2b332
/cdm/src/test/java/thredds/catalog2/xml/parser/stax/GeospatialRangeTypeParserTest.java
6fad8e323e61a0c1194b9fed96d3eb4fc58f1a89
[ "NetCDF" ]
permissive
feihugis/thredds-target-4.3.23
f56346a42ab398467761a9f5d5a27a2a1a5854bd
5d853cac7529dc742208cc23addf78522dbace58
refs/heads/master
2021-03-16T10:06:15.407497
2017-11-07T06:27:38
2017-11-07T06:27:38
50,969,901
0
0
null
null
null
null
UTF-8
Java
false
false
6,257
java
package thredds.catalog2.xml.parser.stax; import org.junit.Test; import org.junit.Before; import static org.junit.Assert.*; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLEventReader; import javax.xml.namespace.QName; import thredds.catalog2.xml.parser.ThreddsXmlParserException; import thredds.catalog2.xml.names.ThreddsMetadataElementNames; import thredds.catalog2.xml.names.CatalogNamespaceUtils; import thredds.catalog2.builder.ThreddsBuilderFactory; import thredds.catalog2.builder.ThreddsMetadataBuilder; import thredds.catalog2.simpleImpl.ThreddsBuilderFactoryImpl; /** * Test the thredds.catalog2.xml.parser.stax.GeospatialRangeTypeParser in isolation. * * @author edavis * @since 4.0 */ public class GeospatialRangeTypeParserTest { private ThreddsBuilderFactory fac; private ThreddsMetadataBuilder.GeospatialCoverageBuilder gspCovBldr; private String rootDocBaseUri; private String startElementName; private String sizeElementName; private String resolutionElementName; private String unitsElementName; @Before public void createMockObjects() { this.fac = new ThreddsBuilderFactoryImpl(); this.gspCovBldr = this.fac.newThreddsMetadataBuilder().getGeospatialCoverageBuilder(); this.rootDocBaseUri = "http://test/thredds/catalog2/xml/parser/stax/GeospatialRangeTypeParserTest/"; this.startElementName = ThreddsMetadataElementNames.SpatialRangeType_Start.getLocalPart(); this.sizeElementName = ThreddsMetadataElementNames.SpatialRangeType_Size.getLocalPart(); this.resolutionElementName = ThreddsMetadataElementNames.SpatialRangeType_Resolution.getLocalPart(); this.unitsElementName = ThreddsMetadataElementNames.SpatialRangeType_Units.getLocalPart(); } // ToDo Need to implement GeospatialRangeTypeParser before this test will work. //@Test public void checkFullySpecifiedGeospatialRangeType() throws XMLStreamException, ThreddsXmlParserException { String docBaseUri = this.rootDocBaseUri + "checkFullySpecifiedGeospatialRangeType.test"; String elementName = "someElemOfTypeGeospatialRange"; String start = "-55.5"; String size = "23.0"; String resolution = "0.5"; String units = "degrees_east"; String xml = buildGeospatialRangeTypeElementAsDocRoot( elementName, start, size, resolution, units ); assertGeospatialRangeTypeXmlAsExpected( xml, docBaseUri, elementName, start, size, resolution, units ); } private String buildGeospatialRangeTypeElementAsDocRoot( String elementName, String start, String size, String resolution, String units ) { StringBuilder sb = new StringBuilder(); if ( start != null ) sb.append( buildGeospatialRangeTypeStartElement( start )); if ( size != null ) sb.append( " <size>" ).append( size ).append( "</size>\n" ); if ( resolution != null ) sb.append( " <resolution>" ).append( resolution ).append( "</resolution>\n" ); if ( units != null ) sb.append( " <units>" ).append( units ).append( "</units>\n" ); return StaxParserTestUtils.wrapContentXmlInXmlDocRootElement( elementName, null, sb.toString() ); } private String buildGeospatialRangeTypeStartElement( String start ) { StringBuilder sb = new StringBuilder().append( "<" ).append( this.startElementName).append( ">" ) .append( start ).append( "</").append( this.startElementName).append(">\n" ); return sb.toString(); } private String buildGeospatialRangeTypeSizeElement( String size ) { StringBuilder sb = new StringBuilder().append( "<" ).append( this.sizeElementName).append( ">" ) .append( size ).append( "</").append( this.sizeElementName).append(">\n" ); return sb.toString(); } private String buildGeospatialRangeTypeResolutionElement( String resolution ) { StringBuilder sb = new StringBuilder().append( "<" ).append( this.resolutionElementName).append( ">" ) .append( resolution ).append( "</").append( this.resolutionElementName).append(">\n" ); return sb.toString(); } private String buildGeospatialRangeTypeUnitsElement( String units ) { StringBuilder sb = new StringBuilder().append( "<" ).append( this.unitsElementName).append( ">" ) .append( units ).append( "</").append( this.unitsElementName).append(">\n" ); return sb.toString(); } private void assertGeospatialRangeTypeXmlAsExpected( String docXml, String docBaseUri, String expectedRootElementName, String expectedStart, String expectedSize, String expectedResolution, String expectedUnits ) throws XMLStreamException, ThreddsXmlParserException { XMLEventReader reader = StaxParserTestUtils.createXmlEventReaderOnXmlString( docXml, docBaseUri ); StaxParserTestUtils.advanceReaderToFirstStartElement( reader ); QName rootElemQName = CatalogNamespaceUtils.getThreddsCatalogElementQualifiedName( expectedRootElementName ); GeospatialRangeTypeParser.Factory factory = new GeospatialRangeTypeParser.Factory( rootElemQName ); assertNotNull( factory); assertTrue( factory.isEventMyStartElement( reader.peek() )); GeospatialRangeTypeParser parser = factory.getNewParser( reader, this.fac, this.gspCovBldr ); assertNotNull( parser); ThreddsMetadataBuilder.GeospatialRangeBuilder bldr = (ThreddsMetadataBuilder.GeospatialRangeBuilder) parser.parse(); assertNotNull( bldr ); // // assertTrue( bldr instanceof ThreddsMetadataBuilder.DateRangeBuilder ); // ThreddsMetadataBuilder.DateRangeBuilder tmBldr = (ThreddsMetadataBuilder.DateRangeBuilder) bldr; // // assertEquals( startDate, tmBldr.getStartDate()); // assertNull( tmBldr.getStartDateFormat()); // assertEquals( endDate, tmBldr.getEndDate()); // assertNull( tmBldr.getEndDateFormat() ); // assertEquals( duration, tmBldr.getDuration() ); // assertEquals( resolution, tmBldr.getResolution() ); } }
[ "hufei68@gmail.com" ]
hufei68@gmail.com
d72fd328a00834d6beb15c4170181ef9b227de6f
83b6a9a3d2be905c940b9166f7056c89c720eaf1
/compling.core/source/compling/gui/GrammarWritingUtilities.java
3715a1e6e4c6a40905b6a42739b33dd07ff5affb
[]
no_license
icsi-berkeley/ecg_compling
75a07f301a9598661fa71ba5d764094b06b953b3
89c810d49119ba7cb76a7323ebbf051a9cfb9b9c
refs/heads/master
2021-09-15T01:57:44.493832
2015-12-14T18:42:08
2015-12-14T18:42:08
26,875,943
1
0
null
null
null
null
UTF-8
Java
false
false
15,470
java
// ============================================================================= //File : GrammarWritingUtilities.java //Author : emok //Change Log : Created on Jul 28, 2007 //============================================================================= package compling.gui; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; import compling.annotation.AnnotationException; import compling.annotation.childes.ChildesAnnotation.GoldStandardAnnotation; import compling.annotation.childes.ChildesIterator; import compling.annotation.childes.ChildesTranscript; import compling.annotation.childes.ChildesTranscript.ChildesClause; import compling.annotation.childes.ChildesTranscript.ChildesEvent; import compling.annotation.childes.ChildesTranscript.ChildesItem; import compling.annotation.childes.FeatureBasedEntity.Binding; import compling.annotation.childes.FeatureBasedEntity.ExtendedFeatureBasedEntity; import compling.context.ContextException.ItemNotDefinedException; import compling.context.ContextModel; import compling.context.ContextUtilities.MiniOntologyFormatter; import compling.context.ContextUtilities.OntologyGraphPrinter; import compling.context.ContextUtilities.SimpleOntologyPrinter; import compling.context.MiniOntology; import compling.grammar.GrammarException; import compling.grammar.ecg.ECGGrammarUtilities; import compling.grammar.ecg.ECGGrammarUtilities.SimpleGrammarPrinter; import compling.grammar.ecg.Grammar; import compling.grammar.unificationgrammar.TypeSystemException; import compling.gui.LearnerPrefs.LP; import compling.parser.ParserException; import compling.parser.ecgparser.Analysis; import compling.parser.ecgparser.ECGAnalyzer; import compling.parser.ecgparser.NoECGAnalysisFoundException; import compling.simulator.Simulator; import compling.simulator.SimulatorException; import compling.simulator.SimulatorException.ScriptNotFoundException; import compling.util.Pair; import compling.util.PriorityQueue; import compling.util.fileutil.ExtensionFileFilter; import compling.util.fileutil.FileUtils; import compling.utterance.Word; //============================================================================= public class GrammarWritingUtilities { static PrintStream printStream = System.out; private Set<Pair<String, String>> undefinedLex = new LinkedHashSet<Pair<String, String>>(); private Set<String> undefinedScripts = new LinkedHashSet<String>(); private Set<String> undefinedTypes = new LinkedHashSet<String>(); private boolean analyze = false; private boolean simulate = false; private boolean makeSnapShots = false; private int fileCounter = 1; File output = null; List<File> dataFiles = null; String ontFileName = null; StringBuffer defs = null; Grammar grammar = null; Simulator simulator = null; ContextModel contextModel = null; ECGAnalyzer analyzer = null; LearnerPrefs preferences = null; public GrammarWritingUtilities(LearnerPrefs prefs) { try { preferences = prefs; makeSnapShots = preferences.getSetting(LP.OUTPUT_SNAPSHOTS) == null ? false : Boolean.valueOf(preferences .getSetting(LP.OUTPUT_SNAPSHOTS)); output = preferences.getSetting(LP.OUTPUT_SNAPSHOTS_PATH) == null ? null : new File( preferences.getSetting(LP.OUTPUT_SNAPSHOTS_PATH)); if (output != null && output.isFile() && !makeSnapShots) { setPrintStream(new PrintStream(output)); } File baseDirectory = preferences.getBaseDirectory(); List<String> dpaths = preferences.getList(LP.DATA_PATHS); String dext = preferences.getSetting(LP.DATA_EXTENSIONS); dataFiles = FileUtils.getFilesUnder(baseDirectory, dpaths, new ExtensionFileFilter(dext)); grammar = ECGGrammarUtilities.read(preferences); grammar.update(); contextModel = grammar.getContextModel(); List<String> spaths = preferences.getList(LP.SCRIPT_PATHS); String sext = preferences.getSetting(LP.SCRIPT_EXTENSIONS); simulator = new Simulator(contextModel, FileUtils.getFilesUnder(baseDirectory, spaths, new ExtensionFileFilter(sext))); analyze = Boolean.valueOf(preferences.getSetting(LP.ANALYZE)); simulate = Boolean.valueOf(preferences.getSetting(LP.SIMULATE)); } catch (IOException ioe) { outputErrorMessage(ioe); } catch (TypeSystemException e) { outputErrorMessage(e); } } protected static void setPrintStream(PrintStream printStream) { GrammarWritingUtilities.printStream = printStream; } protected void outputErrorMessage(Exception e) { System.out.println(e.getMessage()); if (e.getCause() != null) { System.err.println(e.getMessage()); System.err.println(e.getCause().getMessage()); } if (!(e instanceof ScriptNotFoundException || e instanceof ItemNotDefinedException || e.getMessage().contains( "No speech act annotation found"))) { e.printStackTrace(System.err); } } public Grammar getGrammar() { return grammar; } protected void checkGoldStandardAnnotation(ChildesClause clause) { GoldStandardAnnotation annotation = clause.getChildesAnnotation().getGoldStandardTier().getContent(); String vern = clause.getChildesAnnotation().getVernacularTier().getContent(); for (ExtendedFeatureBasedEntity tag : annotation.getArgumentStructureAnnotations()) { if (tag.getSpanLeft() != null && tag.getSpanRight() != null) { int left = tag.getSpanLeft(); int right = tag.getSpanRight(); printStream.print(tag.getJDOMElement().getName() + "\t"); printStream.print(vern.substring(left, right) + "\t"); if (tag.getAttributeValue("ref") != null) { printStream.print(tag.getAttributeValue("ref")); } else { printStream.print(tag.getCategory()); } printStream.print("\t"); if (tag.getCategory() != null && tag.getCategory().toLowerCase().contains("state")) { try { printStream.print(tag.getBinding("property").iterator().next().getAttributeValue("value")); } catch (NullPointerException e) { } } printStream.println("\t" + clause.getSource()); for (String role : tag.getRoles()) { for (Binding binding : tag.getBinding(role)) { if (binding.getSpanLeft() != null && binding.getSpanRight() != null) { int bleft = binding.getSpanLeft(); int bright = binding.getSpanRight(); printStream.print("\t"); printStream.print(vern.substring(bleft, bright) + "\t"); if (binding.getAttributeValue("ref") != null) { printStream.print(binding.getAttributeValue("ref")); } else if (binding.getAttributeValue("value") != null) { printStream.print(binding.getAttributeValue("value")); } else { printStream.print(binding.getField()); } printStream.print("\t"); if (binding.getAttributeValue("subcat") != null) { printStream.print(binding.getAttributeValue("subcat")); } printStream.println("\t" + clause.getSource()); } } } } // System.out.println(tag); } // System.out.println(annotation); } protected void checkLexicon(ChildesClause clause, Grammar grammar) { List<Word> undefinedWords = new ArrayList<Word>(); List<Word> words = clause.getElements(); for (Word word : words) { try { // grammar.getLexicalConstruction("\"" + word.getOrthography() + "\""); } catch (GrammarException ge) { undefinedWords.add(word); int index = words.indexOf(word); String chinese = clause.getChildesAnnotation().getVernacularTier().getWordsAt(index, index + 1); boolean added = undefinedLex.add(new Pair<String, String>(word.getOrthography(), String.valueOf(chinese))); if (added) { System.out.println(word.getOrthography() + " : " + chinese); } } } } protected void printUtterance(ChildesClause clause) { List<Word> words = clause.getElements(); StringBuilder sb = new StringBuilder(); for (Word word : words) { sb.append(word.getOrthography()).append(' '); } System.out.println(sb); } protected void crazyCounting(ChildesClause clause) { Word targetWord = new Word("gei3"); List<Word> words = clause.getElements(); int index = words.indexOf(targetWord); if (index != -1) { String vern = clause.getChildesAnnotation().getVernacularTier().getContent(); GoldStandardAnnotation annotation = clause.getChildesAnnotation().getGoldStandardTier().getContent(); for (ExtendedFeatureBasedEntity tag : annotation.getAllAnnotations()) { if (tag.getSpanLeft() != null && tag.getSpanLeft() == index && tag.getSpanRight() == index + 1) { System.out.println(vern + "\t" + tag.getCategory()); break; } else if (tag.getType() != null && tag.getType().equals("benefaction") || tag.getType().equals("malefaction")) { System.out.println(vern + "\t" + tag.getType()); break; } } } } protected void analyzeUtterance(ChildesClause clause) { System.out.println("Analyzing.... "); printUtterance(clause); PriorityQueue<?> pqa; try { if (analyzer.robust()) { pqa = analyzer.getBestPartialParses(clause); } else { pqa = analyzer.getBestParses(clause); } while (pqa.size() > 0) { System.out.println("\n\nRETURNED ANALYSIS\n____________________________\n"); System.out.println("Cost: " + pqa.getPriority()); System.out.println(pqa.next()); } } catch (NoECGAnalysisFoundException neafe) { System.out.println("\n\nEXCEPTIONALLY BAD ANALYSIS\n____________________________\n"); for (Analysis a : neafe.getAnalyses()) { System.out.println(a); } } catch (ParserException pe) { System.err.println(pe.getLocalizedMessage()); pe.printStackTrace(); System.out.println(analyzer.getParserLog()); } } protected void processTranscript(File datafile) throws IOException { ChildesTranscript transcript = new ChildesTranscript(datafile); if (simulate) { simulator.initializeParticipants(transcript.getParticipantIDs()); simulator.initializeSetting(transcript.getSettingEntitiesAndBindings(), transcript.getSetupEntitiesAndBindings()); } ChildesIterator transcriptIter = transcript.iterator(); while (transcriptIter.hasNext()) { try { ChildesItem item = transcriptIter.next(); if (item instanceof ChildesClause) { ChildesClause clause = (ChildesClause) item; if (clause.size() > 0) { // System.out.println("clause id = " + clause.getID()); if (simulate) { boolean success = simulator.registerUtterance(clause, new HashSet<String>()); } checkLexicon(clause, grammar); // checkGoldStandardAnnotation(clause); // printUtterance(clause); // crazyCounting(clause); // printStatus(success, verbose); if (analyze) { analyzeUtterance(clause); } } } else if (item instanceof ChildesEvent && simulate) { boolean success = simulator.simulateEvent((ChildesEvent) item); if (!success) System.out.println(item.getID() + " " + success); // printStatus(success, verbose); } if (makeSnapShots) { makeSnapShot(); } } catch (ScriptNotFoundException snfe) { // outputErrorMessage(snfe); undefinedScripts.add(snfe.getScriptName()); } catch (ItemNotDefinedException infe) { // outputErrorMessage(infe); undefinedTypes.add(infe.getUnknownItem()); } catch (SimulatorException se) { outputErrorMessage(se); } } if (!makeSnapShots && output != null) { outputContextModelGraph(); } } protected void processTranscripts() { try { for (File dataFile : dataFiles) { System.out.println("Processing... " + dataFile.getName() + " ..... "); System.out.flush(); grammar.getContextModel().reset(); if (analyze) { analyzer = new ECGAnalyzer(grammar); } processTranscript(dataFile); } } catch (IOException ioe) { outputErrorMessage(ioe); } catch (AnnotationException ae) { outputErrorMessage(ae); } catch (SimulatorException se) { outputErrorMessage(se); } catch (GrammarException ge) { outputErrorMessage(ge); } finally { outputToFile(); } } public void outputToFile() { printStream.println("============================"); printStream.println("Undefined Lexical Items"); printStream.println("============================"); for (Pair<String, String> lex : undefinedLex) { printStream.println(lex.getFirst() + ":" + lex.getSecond()); } printStream.println("\n\n"); printStream.println("============================"); printStream.println("Undefined Types"); printStream.println("============================"); for (String type : undefinedTypes) { printStream.println(type); } printStream.println("\n\n"); printStream.println("============================"); printStream.println("Undefined Scripts"); printStream.println("============================"); for (String script : undefinedScripts) { printStream.println(script); } } public void outputContextModelGraph() { MiniOntology.setFormatter(new OntologyGraphPrinter()); printStream.println(contextModel.getMiniOntology()); } public void makeSnapShot() throws IOException { int zeros = 3 - String.valueOf(fileCounter).length(); String count = ""; for (int i = 0; i < zeros; i++) { count += "0"; } count += String.valueOf(fileCounter); String filename = "contextModel" + count + ".dt"; File snapshot = new File(output, filename); setPrintStream(new PrintStream(snapshot)); outputContextModelGraph(); String[] cmd = { "cmd", "/c", "dot", "-Nshape=polygon", "-Nsides=6", "-o", output.getPath() + File.separator + "cm" + count + ".png", "-Tpng", snapshot.getPath() }; Runtime.getRuntime().exec(cmd); fileCounter++; } public void printStatus(boolean success, boolean verbose) { System.out.println(success); if (verbose) { System.out.println("*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*"); MiniOntologyFormatter old = MiniOntology.getFormatter(); MiniOntology.setFormatter(new SimpleOntologyPrinter()); System.out.println(contextModel.getMiniOntology()); MiniOntology.setFormatter(old); System.out.println("~~~~~~~~~~~~~ cache ~~~~~~~~~~~~~~"); System.out.println(contextModel.getContextModelCache()); System.out.println("*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*"); } } public static void setLoggingLevel(Level level) { Logger rootLogger = LogManager.getLogManager().getLogger(""); for (Handler existing : rootLogger.getHandlers()) { rootLogger.removeHandler(existing); } rootLogger.setLevel(level); rootLogger.addHandler(new LoggingHandler()); } public static void main(String[] argv) throws IOException { if (argv.length < 1) { String errormsg = "usage: <learner preference file>"; System.err.println(errormsg); System.exit(1); } LearnerPrefs prefs = new LearnerPrefs(argv[0]); String globalLoggingLevel = prefs.getLoggingLevels().get(ComplingPackage.GLOBAL); Level loggingLevel = globalLoggingLevel != null ? Level.parse(globalLoggingLevel) : Level.INFO; setLoggingLevel(loggingLevel); GrammarWritingUtilities util = new GrammarWritingUtilities(prefs); Grammar.setFormatter(new SimpleGrammarPrinter()); util.processTranscripts(); } }
[ "lucag@icsi.berkeley.edu" ]
lucag@icsi.berkeley.edu
562407ac6bab9710b23ada2065bee1cc0413f49f
e28f2c9cbee582c442d9d63d1bcd68b929db18a6
/oopIntro/src/oopIntro/Product.java
9f548e4e1a4046b416fdd36063a195bcbbcd6cd2
[]
no_license
ramazankayis/JavaCampHomeWork
3ef05d94712bc8f3b6a62c141b40e4e1b376dc5a
08e877f40791893cafe018ef72402528ea512008
refs/heads/master
2023-07-04T11:35:09.486180
2021-08-08T14:30:51
2021-08-08T14:30:51
365,373,553
1
0
null
null
null
null
UTF-8
Java
false
false
1,193
java
package oopIntro; public class Product { int id; String name; double unitPrice; String detail; double discount; double unitPriceAfterDiscount; public Product() { } public Product(int id, String name, double unitPrice, String detail,double discount,double unitPriceAfterDiscount) { super(); this.id = id; this.name = name; this.unitPrice = unitPrice; this.detail = detail; this.discount= discount; this.unitPriceAfterDiscount= unitPriceAfterDiscount; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getUnitPrice() { return unitPrice; } public void setUnitPrice(double unitPrice) { this.unitPrice = unitPrice; } public String getDetail() { return detail; } public void setDetail(String detail) { this.detail = detail; } public double getDiscount() { return discount; } public void setDiscount(double discount) { this.discount = discount; } public double getUnitPriceAfterDiscount() { return this.unitPrice- (this.unitPrice*this.discount/100); } }
[ "11260047@ogrenci.firat.edu.tr" ]
11260047@ogrenci.firat.edu.tr
0d0aa5650a87fc55be50b6f2b7881b1ff0960caa
bca0bf5c2f40d3d92dcb28d8699ebf648d61e8d2
/games-obstacle/core/src/com/obstacleavoid/screen/game/GameRenderer.java
36124d973bfc8ebbfb7bf73df6aab29402bd718c
[]
no_license
nvg/android
8d2ebd462d4950bb35337f3e0524843dcfdb7d63
ec911402cad361041ae661f6beec8a8463cd40f5
refs/heads/master
2022-07-23T17:51:01.219944
2020-05-18T20:05:50
2020-05-18T20:05:50
254,755,654
0
0
null
null
null
null
UTF-8
Java
false
false
6,455
java
package com.obstacleavoid.screen.game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.AssetManager; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.GlyphLayout; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.graphics.glutils.ShapeRenderer; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.viewport.FitViewport; import com.badlogic.gdx.utils.viewport.Viewport; import com.obstacleavoid.assets.AssetDescriptors; import com.obstacleavoid.assets.RegionNames; import com.obstacleavoid.config.GameConfig; import com.obstacleavoid.entity.Background; import com.obstacleavoid.entity.Obstacle; import com.obstacleavoid.entity.Player; import com.obstacleavoid.util.GdxUtils; import com.obstacleavoid.util.ViewportUtils; import com.obstacleavoid.util.debug.DebugCameraController; public class GameRenderer implements Disposable { // == attributes == private OrthographicCamera camera; private Viewport viewport; private ShapeRenderer renderer; private OrthographicCamera hudCamera; private Viewport hudViewport; private BitmapFont font; private final GlyphLayout layout = new GlyphLayout(); private DebugCameraController debugCameraController; private final GameController controller; private final AssetManager assetManager; private final SpriteBatch batch; private TextureRegion playerRegion; private TextureRegion obstacleRegion; private TextureRegion backgroundRegion; // == constructors == public GameRenderer(SpriteBatch batch, AssetManager assetManager, GameController controller) { this.batch = batch; this.assetManager = assetManager; this.controller = controller; init(); } // == init == private void init() { camera = new OrthographicCamera(); viewport = new FitViewport(GameConfig.WORLD_WIDTH, GameConfig.WORLD_HEIGHT, camera); renderer = new ShapeRenderer(); hudCamera = new OrthographicCamera(); hudViewport = new FitViewport(GameConfig.HUD_WIDTH, GameConfig.HUD_HEIGHT, hudCamera); font = assetManager.get(AssetDescriptors.FONT); // create debug camera controller debugCameraController = new DebugCameraController(); debugCameraController.setStartPosition(GameConfig.WORLD_CENTER_X, GameConfig.WORLD_CENTER_Y); TextureAtlas gamePlayAtlas = assetManager.get(AssetDescriptors.GAME_PLAY); playerRegion = gamePlayAtlas.findRegion(RegionNames.PLAYER); obstacleRegion = gamePlayAtlas.findRegion(RegionNames.OBSTACLE); backgroundRegion = gamePlayAtlas.findRegion(RegionNames.BACKGROUND); } // == public methods == public void render(float delta) { // not wrapping inside alive cuz we want to be able to control camera even when there is game over debugCameraController.handleDebugInput(delta); debugCameraController.applyTo(camera); if(Gdx.input.isTouched() && !controller.isGameOver()) { Vector2 screenTouch = new Vector2(Gdx.input.getX(), Gdx.input.getY()); Vector2 worldTouch = viewport.unproject(new Vector2(screenTouch)); System.out.println("screenTouch= " + screenTouch); System.out.println("worldTouch= " + worldTouch); Player player = controller.getPlayer(); worldTouch.x = MathUtils.clamp(worldTouch.x, 0, GameConfig.WORLD_WIDTH - player.getWidth()); player.setX(worldTouch.x); } // clear screen GdxUtils.clearScreen(); renderGamePlay(); // render ui/hud renderUi(); // render debug graphics renderDebug(); } public void resize(int width, int height) { viewport.update(width, height, true); hudViewport.update(width, height, true); ViewportUtils.debugPixelPerUnit(viewport); } @Override public void dispose() { renderer.dispose(); } // == private methods == private void renderGamePlay() { viewport.apply(); batch.setProjectionMatrix(camera.combined); batch.begin(); // draw background Background background = controller.getBackground(); batch.draw(backgroundRegion, background.getX(), background.getY(), background.getWidth(), background.getHeight() ); // draw player Player player = controller.getPlayer(); batch.draw(playerRegion, player.getX(), player.getY(), player.getWidth(), player.getHeight() ); // draw obstacles for (Obstacle obstacle : controller.getObstacles()) { batch.draw(obstacleRegion, obstacle.getX(), obstacle.getY(), obstacle.getWidth(), obstacle.getHeight() ); } batch.end(); } private void renderUi() { hudViewport.apply(); batch.setProjectionMatrix(hudCamera.combined); batch.begin(); String livesText = "LIVES: " + controller.getLives(); layout.setText(font, livesText); font.draw(batch, livesText, 20, GameConfig.HUD_HEIGHT - layout.height ); String scoreText = "SCORE: " + controller.getDisplayScore(); layout.setText(font, scoreText); font.draw(batch, scoreText, GameConfig.HUD_WIDTH - layout.width - 20, GameConfig.HUD_HEIGHT - layout.height ); batch.end(); } private void renderDebug() { viewport.apply(); renderer.setProjectionMatrix(camera.combined); renderer.begin(ShapeRenderer.ShapeType.Line); drawDebug(); renderer.end(); ViewportUtils.drawGrid(viewport, renderer); } private void drawDebug() { Player player = controller.getPlayer(); player.drawDebug(renderer); Array<Obstacle> obstacles = controller.getObstacles(); for (Obstacle obstacle : obstacles) { obstacle.drawDebug(renderer); } } }
[ "nick.goupinets@gmail.com" ]
nick.goupinets@gmail.com
7f991f28eab8e16eba41cabe5e2f197600b23108
ad80d2061bfbb06cbee5aef707d6c60de25cbe98
/src/ArrayInJava/CountCharacterInString.java
692624dd4d01fbe3657f7566877f54c6bfddd473
[]
no_license
Vutienbka/JavaWeb-Abuntu
5ae7d1deb1ffce65ee8695b005014465d03c91a0
ba3bf99ac0663a07a45cab7982d81eeb8a6cabc5
refs/heads/master
2020-12-07T16:32:59.113203
2020-01-18T08:06:51
2020-01-18T08:06:51
232,752,053
0
0
null
null
null
null
UTF-8
Java
false
false
766
java
package ArrayInJava; import java.util.Scanner; public class CountCharacterInString { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Nhap chuoi:"); String string = scanner.nextLine(); System.out.println("Nhap ky tu can tim:"); // string.charAt(i): lay ky tu tai vij tri thu i trong chuoi char character = scanner.nextLine().charAt(0); char[] charArray = string.toCharArray(); //doi chuoi thanh mang ky tu int count = 0; for(int i=0; i< charArray.length; i++) if(charArray[i] == character) count ++; System.out.println("So ky tu " + character + " trong chuoi da nhap la: " + count); } }
[ "vutienbka@gmail.com" ]
vutienbka@gmail.com
1502cd15ddaa6390d5b447788d44e011d2ee6608
c08be51efd0f0ebc6061177dfec4b897c602c858
/clinic/src/main/java/org/fhi360/lamis/modules/clinic/service/ClinicService.java
ee520e7259b86afe0a00cd07348cfaaff791e2ee
[]
no_license
lamisplus/fhi360-lamis3updates
de4ee811975e9f00e52f2c46096003179f362d67
ee573cf2b9291f91b2cb1ef230b386ba26bc63e3
refs/heads/master
2022-12-02T20:37:37.480801
2020-08-19T08:37:14
2020-08-19T08:37:14
288,662,576
0
0
null
null
null
null
UTF-8
Java
false
false
5,545
java
package org.fhi360.lamis.modules.clinic.service; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.fhi360.lamis.modules.clinic.web.rest.vm.ClinicVM; import org.lamisplus.modules.lamis.legacy.domain.entities.*; import org.lamisplus.modules.lamis.legacy.domain.entities.enumerations.ClientStatus; import org.lamisplus.modules.lamis.legacy.domain.repositories.*; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; @Service @RequiredArgsConstructor @Slf4j public class ClinicService { private final ClinicRepository clinicRepository; private final PatientRepository patientRepository; private final StatusHistoryRepository statusHistoryRepository; private final ClinicOpportunisticInfectionRepository clinicOpportunisticInfectionRepository; private final ClinicAdhereRepository clinicAdhereRepository; private final AdhereRepository adhereRepository; private final OpportunisticInfectionRepository opportunisticInfectionRepository; private final DevolveRepository devolveRepository; private final JdbcTemplate jdbcTemplate; public Clinic saveClinic(ClinicVM vm) { Clinic clinic = vm.getClinic(); if (clinic.getCommence() != null && clinic.getCommence()) { patientRepository.findById(clinic.getPatient().getId()).ifPresent(patient -> { patient.setDateStarted(clinic.getDateVisit()); patientRepository.save(patient); StatusHistory history = new StatusHistory(); history.setFacility(patient.getFacility()); history.setPatient(patient); history.setStatus(ClientStatus.ART_START); history.setDateStatus(clinic.getDateVisit()); }); } List<OpportunisticInfection> infections; List<Adhere> adheres; if (!clinic.isNew()) { infections = clinicOpportunisticInfectionRepository.findByClinic(clinic).stream() .map(ClinicOpportunisticInfection::getOpportunisticInfection) .filter(i -> vm.getOiList().contains(i)) .collect(Collectors.toList()); clinic.getOpportunisticInfections().clear(); clinic.getOpportunisticInfections().addAll(infections); adheres = clinicAdhereRepository.findByClinic(clinic).stream() .map(ClinicAdhere::getAdhere) .filter(ca -> vm.getAdhereList().contains(ca)) .collect(Collectors.toList()); clinic.getAdheres().clear(); clinic.getAdheres().addAll(adheres); } if (vm.getOiList() != null) { vm.getOiList().forEach(oi -> { if (oi != null && oi.getId() != null) { opportunisticInfectionRepository.findById(oi.getId()) .ifPresent(o -> clinic.getOpportunisticInfections().add(o)); } }); } if (vm.getAdhereList() != null) { vm.getAdhereList().forEach(adhere -> { if (adhere != null && adhere.getId() != null) { adhereRepository.findById(adhere.getId()) .ifPresent(a -> clinic.getAdheres().add(a)); } }); } if (vm.getAdrList() != null) { List<ClinicAdverseDrugReaction> cadr = vm.getAdrList().stream() .map(ca -> { ca.setClinic(clinic); return ca; }) .collect(Collectors.toList()); clinic.getClinicAdverseDrugReactions().addAll(cadr); } return clinicRepository.save(clinic); } public void deleteClinic(String clinicId) { clinicRepository.findByUuid(clinicId).ifPresent(clinic -> deleteClinic(clinic.getId())); } public void deleteClinic(Long clinicId) { clinicRepository.findById(clinicId).ifPresent(clinic -> { Patient patient = clinic.getPatient(); devolveRepository.findByPatient(patient) .forEach(devolve -> { if (devolve.getRelatedClinic() != null && Objects.equals(clinicId, devolve.getRelatedClinic().getId())) { devolve.setRelatedClinic(null); devolveRepository.save(devolve); } }); if (clinic.getCommence() != null && clinic.getCommence() && patient.getDateStarted().equals(clinic.getDateVisit())) { patient.setDateStarted(null); patientRepository.save(patient); statusHistoryRepository.findByPatient(patient).stream() .filter(s -> s.getStatus().equals(ClientStatus.ART_START)) .forEach(statusHistoryRepository::delete); } clinicRepository.delete(clinic); }); } public Boolean enrolledOnOTZ(Long patientId) { try { Boolean enrolled = jdbcTemplate.queryForObject("select (extra->'otz'->>'enrolledOnOTZ')::boolean from clinic where " + "patient_id = ? and commence = true", Boolean.class, patientId); return enrolled != null ? enrolled : false; } catch (Exception e) { return false; } } }
[ "matthew.edor@gmail.com" ]
matthew.edor@gmail.com
9e34cb87abcfde8f69fce2c5d991d5e8f9ae9a27
bfd60fe949807d6a70a07a09b897ad9f0187f671
/src/main/java/org/jsapar/compose/cell/package-info.java
bf8491c31640afb1daf526693338ccba09d62bc9
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
org-tigris-jsapar/jsapar
ad221d7748bad42c708052e995dde596cd6a67e3
0113c8d3dcb821438a4eb065080ab8c506105610
refs/heads/master
2023-08-21T21:26:47.813228
2023-08-03T08:25:48
2023-08-03T08:25:48
102,112,317
13
4
Apache-2.0
2020-10-13T12:41:24
2017-09-01T12:51:18
Java
UTF-8
Java
false
false
113
java
/** Internal classes for composing {@link org.jsapar.model.Cell} instances. */ package org.jsapar.compose.cell;
[ "p.jonas.stenberg@gmail.com" ]
p.jonas.stenberg@gmail.com
9ac55d7e21aceaf9575b514bee48862be1d5a197
f25287f4e5dc9e8e965e90bb6105ea64f55dfb87
/app/src/main/java/com/hanks/mvc/base/BaseConstant.java
827c50ec0b0b2c553113ec51f837251c5638387d
[]
no_license
hanks7/Mvc
c149a76ede81a4b76b1ffb08424619457a281a6e
24ff2860af1f015d47006d97ffdc2bb5bf4b2fe5
refs/heads/master
2020-05-07T16:50:55.862444
2019-04-11T07:56:09
2019-04-11T07:56:09
180,702,208
0
0
null
null
null
null
UTF-8
Java
false
false
255
java
package com.hanks.mvc.base; /** * @author 侯建军 47466436@qq.com * @class com.hanks.mvc.base.BaseConstant * @time 2019/4/11 14:19 * @description 请填写描述 */ public class BaseConstant { public final static boolean IS_RELEASE = false; }
[ "474664736@qq.com" ]
474664736@qq.com
34a2549450aefd06fa78e85793dd950d9bb569d5
cae0c60a38d3ed25f59039c0d9fdcb123d53e21c
/src/com/example/alex/common/ShowResultUtil.java
3fc60dc302fbaba6661d868319cf220ff2502357
[]
no_license
liangxiaofei1100/AndroidStudy
a340ff3f11c933635cd0adea3a83118a29778090
1b5ef2222be57935c5126c3ae4bc62b9375f8857
refs/heads/master
2016-09-05T14:27:07.287326
2015-10-19T01:58:05
2015-10-19T01:58:05
9,311,010
2
0
null
null
null
null
UTF-8
Java
false
false
691
java
package com.example.alex.common; import android.widget.TextView; public class ShowResultUtil { private TextView mTextView; public ShowResultUtil() { } public ShowResultUtil(TextView textView) { mTextView = textView; } public void showInTextView(String msg) { showInTextView(mTextView, msg); } public static void showInTextView(TextView textView, String msg) { if (textView != null) { if (!msg.endsWith("\n")) { textView.append(TimeUtil.getCurrentTime() + " " + msg + '\n'); } else { textView.append(TimeUtil.getCurrentTime() + " " + msg); } } } }
[ "liangxiaofei1100@163.com" ]
liangxiaofei1100@163.com
867fd82b56c8e51fbb189474b57c5bf0035bfc31
c5ea8613c7da6d35107851f5d83be477d3851234
/src/main/java/io/hanmomhanda/wubwur/Application.java
8d7be8c3bc05f89b451c1d790631e592caf3b3fc
[]
no_license
hanmomhanda/wubwur
277950ca05c805fb96ebffe826f975e420df0f96
009d15075470bfad09d14c460374bd521a2391ed
refs/heads/master
2016-09-10T15:39:37.699708
2015-08-10T23:43:28
2015-08-10T23:43:28
40,087,149
0
0
null
null
null
null
UTF-8
Java
false
false
662
java
package io.hanmomhanda.wubwur; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import java.util.Arrays; @SpringBootApplication public class Application { public static void main(String[] args) { ApplicationContext ctx = SpringApplication.run(Application.class, args); // // System.out.println("만세~"); // // String[] beanNames = ctx.getBeanDefinitionNames(); // Arrays.sort(beanNames); // for(String beanName : beanNames) { // System.out.println(beanName); // } } }
[ "hanmomhanda@gmail.com" ]
hanmomhanda@gmail.com
d2b4c9b6a974c05123728ce1df91df46e981b8bf
b65a1caab3ed0ed42e17d5592f3e9ba2ac446c1e
/Session8-SCF/src/Animal.java
a22a00c932dcacf9864f4a7f774d44d81b36c007
[]
no_license
meta-ashish-bansal/GET2020
c68c222a1dd08221cd0eb69ffa2d4240cde5c66d
76530b7a8256f44f8f2de1ebbbe3f48edefa7f19
refs/heads/master
2023-01-24T19:55:02.969999
2020-04-15T16:27:38
2020-04-15T16:27:38
232,491,015
0
0
null
2020-01-08T07:24:56
2020-01-08T06:07:39
null
UTF-8
Java
false
false
483
java
abstract public class Animal { int ageOfAnimal; static int counter =0; final int animalId; String animalName; String categoryOfAnimal; float weightOfAnimal; String soundOfAnimal; public Animal(int age,String name, String category, float weight,String sound) { this.ageOfAnimal = age; this.animalName = name; this.categoryOfAnimal = category; this.weightOfAnimal = weight; animalId = counter++; soundOfAnimal = sound; } abstract public String getSound(); }
[ "ashish.bansal@metacube.com" ]
ashish.bansal@metacube.com
63e06e0bb8c078c96404b7da328ea2841d8ac4c3
507ac956031d03763e57b17b7f3e42b877a940b2
/CodeTP3-20191120/BreadthFirstSearch.java
b0bc81903285504bd7c666756845a5c322208ab9
[]
no_license
Krisy98/tp3Algo_genAleaArbresCouvrants
6a190151c6ade2ec5f413d35dc3b677f3c6cacce
bcd89fad90b4ce7bce3586131365de5ecf1c3967
refs/heads/master
2020-09-13T19:04:17.600619
2019-12-10T22:46:31
2019-12-10T22:46:31
222,876,819
0
0
null
null
null
null
UTF-8
Java
false
false
1,103
java
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class BreadthFirstSearch { public static ArrayList<Arc> generateTree(Graph graph, int source) { ArrayList<Arc> tree = new ArrayList<>(); List<Integer> waitingList = new LinkedList(); List<Boolean> visited = new LinkedList<>(); for (int index=0; index < graph.order; index++) visited.add(false); waitingList.add(source); visited.add(source, true); while (waitingList.size() != 0){ source = waitingList.get(0); waitingList.remove(0); for (int index=0; index < graph.outAdjacency.get(source).size(); index++){ int destination = graph.outAdjacency.get(source).get(index).support.dest; if (!visited.get(destination).booleanValue()){ tree.add(graph.outAdjacency.get(source).get(index)); visited.set(destination, true); waitingList.add(destination); } } } return tree; } }
[ "chris13cozzo@gmail.com" ]
chris13cozzo@gmail.com
f6277e74260878f825f4b6a9be6371fb8d526347
2eac4f51a2e4363349e852ce3af8ca234c1a13f7
/fx/trunk/fx-datamanager/src/main/java/com/jeff/fx/datamanager/TimeRange.java
476bb3bd9df5a590fb994a170d20d0bd4760dbfd
[]
no_license
johnffracassi/jcfx
4e19ac0fdba174db0fe3eb2fc8848652a5c99c11
b0a2349fdd1de0bf60c7ccf9a17af4e43e0a1727
refs/heads/master
2016-09-05T15:13:49.981403
2011-07-21T05:54:28
2011-07-21T05:54:28
41,260,482
0
0
null
null
null
null
UTF-8
Java
false
false
665
java
package com.jeff.fx.datamanager; import java.awt.FlowLayout; import javax.swing.JLabel; import javax.swing.JPanel; import org.joda.time.LocalTime; public class TimeRange extends JPanel { private static final long serialVersionUID = 999290000L; private TimePicker start; private TimePicker end; public TimeRange() { start = new TimePicker(); end = new TimePicker(); init(); } public LocalTime getStart() { return start.getTime(); } public LocalTime getEnd() { return end.getTime(); } private void init() { setLayout(new FlowLayout(3)); add(new JLabel("Start Time")); add(start); add(new JLabel("End Time")); add(end); } }
[ "jeffcann@360c4b46-674e-11de-9b35-9190732fe600" ]
jeffcann@360c4b46-674e-11de-9b35-9190732fe600
4f9c7d4bb9177929b36008da6a5891e529e4acdf
2749a4353814e8a8e6e88cd019a327e66c7761b1
/src/main/java/com/rsw/views/ProgressWebView.java
24a07a429fbe482d67b619dfb5bd90d0172fc3c4
[]
no_license
renshiwu/BetterHealth
f3ac6ff024789f909e0f8b93610fc8db02420563
61c6d501c8bccfa10d849a8254e2fcf8292626af
refs/heads/main
2022-12-31T13:12:50.448472
2020-10-23T01:34:27
2020-10-23T01:34:27
306,498,670
6
0
null
null
null
null
UTF-8
Java
false
false
1,306
java
package com.rsw.views; import android.content.Context; import android.util.AttributeSet; import android.webkit.WebView; import android.widget.ProgressBar; @SuppressWarnings("deprecation") public class ProgressWebView extends WebView { private ProgressBar progressbar; public ProgressWebView(Context context, AttributeSet attrs) { super(context, attrs); progressbar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal); progressbar.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 3, 0, 0)); addView(progressbar); setWebChromeClient(new myWebChromeClient()); } public class myWebChromeClient extends android.webkit.WebChromeClient { @Override public void onProgressChanged(WebView view, int newProgress) { if (newProgress == 100) { progressbar.setVisibility(GONE); } else { if (progressbar.getVisibility() == GONE) progressbar.setVisibility(VISIBLE); progressbar.setProgress(newProgress); } super.onProgressChanged(view, newProgress); } } // @Override // protected void onScrollChanged(int l, int t, int oldl, int oldt) { // LayoutParams lp = (LayoutParams) progressbar.getLayoutParams(); // lp.x = l; // lp.y = t; // progressbar.setLayoutParams(lp); // super.onScrollChanged(l, t, oldl, oldt); // } }
[ "812083100@qq.com" ]
812083100@qq.com
101611cac879e2231f115747c8959a9299d2e06c
d4caf6382751541d8d14a639f0cabc2fb9a21f13
/src/main/java/org/alArbiyaHotelManagement/model/NotificationDeliveryBoy.java
5f6993190a5b6738f2f1046436d20dd0974e1c1a
[]
no_license
iyashiyas/alArbiyaHotelManagement
24661326b90bb5b6578dc140703d5fa3dc04dc3c
d9fa509d284933329644db27f2c9637a52e5cab1
refs/heads/master
2021-01-12T17:42:41.140524
2017-05-24T07:27:09
2017-05-24T07:27:09
71,627,373
0
1
null
2016-10-23T12:17:20
2016-10-22T08:43:01
Java
UTF-8
Java
false
false
1,682
java
package org.alArbiyaHotelManagement.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "NOTIFICATIONDELIVERYBOY") public class NotificationDeliveryBoy { @Id @GeneratedValue @Column(name="NOTIFICATION_ID") private long id; @Column(name="ROOM_ID") private long roomId; @Column(name="ORDER_ID") private long orderId; @Column(name="READ_STATUS") private String readStatus; @Column(name="ORDER_STATUS") private String orderStatus; @Column(name="DELIVERY_BOY_ID") private long deliveryBoyId; @Column(name="DELIVERY_BOY_NAME") private String deliveryBoyName; public long getId() { return id; } public void setId(long id) { this.id = id; } public long getRoomId() { return roomId; } public void setRoomId(long roomId) { this.roomId = roomId; } public long getOrderId() { return orderId; } public void setOrderId(long orderId) { this.orderId = orderId; } public String getReadStatus() { return readStatus; } public void setReadStatus(String readStatus) { this.readStatus = readStatus; } public String getOrderStatus() { return orderStatus; } public void setOrderStatus(String orderStatus) { this.orderStatus = orderStatus; } public long getDeliveryBoyId() { return deliveryBoyId; } public void setDeliveryBoyId(long deliveryBoyId) { this.deliveryBoyId = deliveryBoyId; } public String getDeliveryBoyName() { return deliveryBoyName; } public void setDeliveryBoyName(String deliveryBoyName) { this.deliveryBoyName = deliveryBoyName; } }
[ "shiyas009@gmail.com" ]
shiyas009@gmail.com
d4961b60287dfc4ade651c0bb165285dad860d3e
6f2d0bb2639fc607b1ef9573b1aa606d63fe6f96
/src/test/java/com/affinitas/sudoku/SudokuTestUtils.java
77a9f8c1d5f7bf12b24afe64e2da826dd1712c38
[]
no_license
ganoush/sudoku
fb756c7a11e28263fec9fa7539110978289721eb
c357393d3040f3accbff5c398a0d436e3303ebd1
refs/heads/master
2021-01-13T16:00:38.858531
2017-01-20T03:23:11
2017-01-20T03:23:11
76,747,249
0
0
null
null
null
null
UTF-8
Java
false
false
2,135
java
package com.affinitas.sudoku; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.http.MediaType; import java.nio.charset.Charset; /** * Created by ganeshnagarajan on 12/18/16. */ public class SudokuTestUtils { public static int[][] SUDOKU_ONE_MOVE_FINISH={ {0,3,4,6,7,8,9,1,2}, {6,7,2,1,9,5,3,4,8}, {1,9,8,3,4,2,5,6,7}, {8,5,9,7,6,1,4,2,3}, {4,2,6,8,5,3,7,9,1}, {7,1,3,9,2,4,8,5,6}, {9,6,1,5,3,7,2,8,4}, {2,8,7,4,1,9,6,3,5}, {3,4,5,2,8,6,1,7,9} }; public static int[][] SUDOKU_INVALID_MOVE={ {0,3,3,6,7,8,9,1,2}, {6,7,2,1,9,5,3,4,8}, {1,9,8,3,4,2,5,6,7}, {8,5,9,7,6,1,4,2,3}, {4,2,6,8,5,3,7,9,1}, {7,1,3,9,2,4,8,5,6}, {9,6,1,5,3,7,2,8,4}, {2,8,7,4,1,9,6,3,5}, {3,4,5,2,8,6,1,7,9} }; public static int[][] SUDOKU_COMPLETION={ {5,3,4,6,7,8,9,1,2}, {6,7,2,1,9,5,3,4,8}, {1,9,8,3,4,2,5,6,7}, {8,5,9,7,6,1,4,2,3}, {4,2,6,8,5,3,7,9,1}, {7,1,3,9,2,4,8,5,6}, {9,6,1,5,3,7,2,8,4}, {2,8,7,4,1,9,6,3,5}, {3,4,5,2,8,6,1,7,9} }; public static int[][] SUDOKU_INVALID_NUMBER={ {15,3,4,6,7,8,9,1,2}, {6,7,2,1,9,5,3,4,8}, {1,9,8,3,4,2,5,6,7}, {8,5,9,7,6,1,4,2,3}, {4,2,6,8,5,3,7,9,1}, {7,1,3,9,2,4,8,5,6}, {9,6,1,5,3,7,2,8,4}, {2,8,7,4,1,9,6,3,5}, {3,4,5,2,8,6,1,7,9} }; public static final MediaType SUDOKU_REQUEST_JSON_TYPE = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8") ); public static String asJsonString(final Object obj) { try { ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(obj); } catch (Exception e) { throw new RuntimeException(e); } } }
[ "ganeshatmail@gmail.com" ]
ganeshatmail@gmail.com
9fa1f4498fcfc4d232c92eb95a7fa5761677ee83
8e689d49971806aee78ae205d8c3be69dd688c06
/portal.ejb/src/main/java/org/vamdc/portal/session/queryLog/PersistentQueryLog.java
7840f9a3a8820f3d973358f839074e9402662eee
[]
no_license
VAMDC/VAMDC-Portal
25666b9e39f36e09479d8118dcd0b91a04ac3065
01698a22649b6b3026686a39fd69cd71c8fb4fc8
refs/heads/master
2022-06-03T22:44:31.463316
2022-05-18T15:52:28
2022-05-18T15:52:28
27,481,771
1
0
null
2022-05-18T15:52:29
2014-12-03T10:29:29
Java
UTF-8
Java
false
false
2,087
java
package org.vamdc.portal.session.queryLog; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.persistence.EntityManager; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Logger; import org.jboss.seam.annotations.Name; import org.jboss.seam.log.Log; import org.vamdc.portal.entity.query.HttpHeadResponse; import org.vamdc.portal.entity.query.Query; import org.vamdc.portal.entity.security.User; import org.vamdc.portal.session.security.UserInfo; @Name("persistentQueryLog") public class PersistentQueryLog { @Logger private Log log; @In private UserInfo auth; @In private EntityManager entityManager; @SuppressWarnings("unchecked") public List<Query> getStoredQueries(){ List<Query> queries = null; User user = auth.getUser(); if (user!=null){ queries=entityManager.createQuery("from Query where user.username =:username").setParameter("username", user.getUsername()).getResultList(); } if (queries!=null && queries.size()>0){ return Collections.unmodifiableList(queries); } return new ArrayList<Query>(); } public void save(Query query) { deleteStaleResponses(query.getQueryID()); entityManager.persist(query); for (HttpHeadResponse response:query.getResponses()){ response.setQuery(query); entityManager.persist(response); } } private void deleteStaleResponses(Integer queryID){ User user = auth.getUser(); if (user!=null&& queryID!=null){ entityManager.createQuery("delete from HttpHeadResponse where queryID = :queryID") .setParameter("queryID", queryID).executeUpdate(); } } public void delete(Integer queryID) { User user = auth.getUser(); if (user!=null){ Query toRemove = (Query)entityManager.createQuery("from Query where user.username = :username and queryID = :queryID") .setParameter("username",user.getUsername()) .setParameter("queryID", queryID).getSingleResult(); for (HttpHeadResponse response:toRemove.getResponses()) entityManager.remove(response); entityManager.remove(toRemove); } } }
[ "misha@doronin.org" ]
misha@doronin.org
493448cebff51c78fc06e0e27cdda99b5b287fc7
5596290192e725ab0cc7a3e2713d009ed4d4611c
/sp02-itemservice/src/main/java/com/tedu/sp02/item/controller/ItemController.java
1f55e8751814b0e256f07d449621d8339bbf8ef7
[]
no_license
huangZH90/test1
41163d52adf238335afdd9de4cf1c9228ab3f4f0
632331bf3e1bddd177c1b5d8ed418df86142b1c4
refs/heads/master
2020-07-11T20:19:49.128512
2019-08-28T02:08:33
2019-08-28T02:08:33
204,636,449
0
0
null
null
null
null
UTF-8
Java
false
false
1,503
java
package com.tedu.sp02.item.controller; import java.util.List; import java.util.Random; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.tedu.sp01.pojo.Item; import com.tedu.sp01.service.ItemService; import com.tedu.web.util.JsonResult; import lombok.extern.slf4j.Slf4j; @RestController @Slf4j public class ItemController { @Autowired private ItemService itemService; @Value("${server.port}") private int port; @GetMapping("/{orderId}") public JsonResult<List<Item>> getItems(@PathVariable String orderId) throws Exception{ log.info("server.port="+port+", orderId="+orderId); ///--设置随机延迟 //long t = new Random().nextInt(5000); //if(Math.random()<0.6) { // log.info("item-service-"+port+" - 暂停 "+t); // Thread.sleep(t); //} ///~~ List<Item> items = itemService.getItems(orderId); return JsonResult.ok(items).msg("port="+port); } @PostMapping("/decreaseNumber") public JsonResult decreaseNumber(@RequestBody List<Item> items) { itemService.decreaseNumbers(items); return JsonResult.ok(); } }
[ "455029284@qq.com" ]
455029284@qq.com
753747a0f235dbc9b600ccd8a2e4626f852b882e
a1e58fe75651b47e44aedd768ce4c4c0e618c7ac
/webPersona/src/main/java/pe/reniec/webpersona/dao/dao.java
56a373b5b21f72c438f6ce9602cb635f113647e3
[]
no_license
PierCajo/NegociosJavaNet
65c5e91a7ca15ed91acc3635920bc8cc9afc1044
3319861da99f30d41f4a17a84f3c3908dd3d9aac
refs/heads/master
2021-01-15T21:19:13.581332
2012-10-09T03:33:40
2012-10-09T03:33:40
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,347
java
package pe.reniec.webpersona.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import pe.reniec.webpersona.excepcion.DAOExcepcion; import pe.reniec.webpersona.modelo.Persona; import pe.reniec.webpersona.util.ConexionBD; public class dao extends BaseDao { public int login(String dni) throws DAOExcepcion { System.out.println("login" + dni); Connection con = null; PreparedStatement stmt = null; ResultSet rs = null; int valor = 0; try { String query = "select estado from persona where dni=?"; System.out.println(query); con = ConexionBD.obtenerConexion(); System.out.println("ya obtuvo la conexion"); stmt = con.prepareStatement(query); System.out.println("despues de preparar"); stmt.setString(1, dni); rs = stmt.executeQuery(); if (rs.next()) { valor = rs.getInt("estado"); } } catch (SQLException e) { System.err.println(e.getMessage()); throw new DAOExcepcion(e.getMessage()); } finally { this.cerrarResultSet(rs); this.cerrarStatement(stmt); this.cerrarConexion(con); } if (valor == 0) { return 0; } else { return valor; } } public Collection<Persona> ValidarInfo(String dni) throws DAOExcepcion { Collection<Persona> lstPersona = new ArrayList<Persona>(); Connection con = null; PreparedStatement stmt = null; ResultSet rs = null; Persona persona = new Persona(); try { String query = "select Dni,Nombres,Apellidos,direccion,telefono,Estado from persona where Dni=?"; System.out.println(query); con = ConexionBD.obtenerConexion(); System.out.println("ya obtuvo la conexion"); stmt = con.prepareStatement(query); stmt.setString(1, dni); rs = stmt.executeQuery(); //if (rs.next()) { // valor = rs.getInt("estado"); //} // String query = "select Dni,Nombres,Apellidos,direccion,telefono,Estado from persona where dni=?"; // System.out.println(query); // con = ConexionBD.obtenerConexion(); // System.out.println("ya obtuvo la conexion"); // stmt = con.prepareStatement(query); // System.out.println("antes de pasar el parametrpo"); // stmt.setString(1, dni); // rs = stmt.executeQuery(); if (rs.next()) { //while (rs.next()) { persona.setDni(rs.getString("dni")); persona.setNombres(rs.getString("nombres")); persona.setApellidos(rs.getString("apellidos")); persona.setDireccion(rs.getString("direccion")); persona.setTelefono(rs.getString("telefono")); persona.setEstado(rs.getInt("estado")); System.out.println(persona.getApellidos()); lstPersona.add(persona); //} } else { persona.setDni("000000"); persona.setNombres("No Autorizada"); persona.setApellidos("No Autorizada"); persona.setDireccion("No Autorizada"); persona.setTelefono("No Autorizada"); persona.setEstado(0); lstPersona.add(persona); } } catch (SQLException e) { System.err.println("msg"+e.getMessage()); throw new DAOExcepcion(e.getMessage()); } finally { this.cerrarResultSet(rs); this.cerrarStatement(stmt); this.cerrarConexion(con); } System.out.println("listado de personas"); //System.out.println(lstPersona.size()); return lstPersona; //return persona.getApellidos(); } }
[ "piercajo@gmail.com" ]
piercajo@gmail.com
18a62610fe603df3c20cdaa20ccc33e761fa0587
dbea5534f5f53f5bb206cd007d6bf9de6b81aaf1
/src/main/java/com/example/course/controller/CourseTypeController.java
f0f40994d83abb8e1ac6b0fb49d055b592737921
[]
no_license
nicexgk/course
edad4bc9a1015053a0d2c7186e9abdcf5bba9a71
86076704eada7bc2e6aa30c0c2cdfcd8deac90e9
refs/heads/master
2020-04-30T08:59:33.329330
2019-03-24T16:09:15
2019-03-24T16:09:15
176,733,728
0
0
null
null
null
null
UTF-8
Java
false
false
764
java
package com.example.course.controller; import com.example.course.entity.CourseType; import com.example.course.service.CourseTypeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; @RestController @RequestMapping("/course") public class CourseTypeController { @Autowired CourseTypeService courseTypeService; @RequestMapping("/type/catalog") public ArrayList<CourseType> courseTypeCatalog(){ ArrayList<CourseType> courseTypeList = courseTypeService.courseTypeNavigation(); return courseTypeList; } }
[ "1621392651@qq.com" ]
1621392651@qq.com
a7851e562d3e04e91012cb75c03dbb883d3c6594
3796020d9086ad76b298266776bc8114b293bb63
/src/ventanas/GuardarEnArcade.java
b1086976df6498840a033041f040b98c0b45ab3a
[]
no_license
Ibaii99/AirFootball
b7cfee071d7874a585570c404262edb218ae8334
e11a2aa01f6c1c06016c8ded815b775a27515313
refs/heads/master
2023-09-03T11:44:30.554364
2021-11-22T16:17:36
2021-11-22T16:17:36
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,074
java
package ventanas; import javax.swing.JFrame; import entidades.BaseDeDatos; import fisicas.FisicasNuevas; import objetos.ScrollablePanel; import java.awt.BorderLayout; import java.awt.Font; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.LayoutStyle.ComponentPlacement; import javax.swing.JButton; import java.awt.event.ActionListener; import java.sql.ResultSet; import java.util.logging.Level; import java.awt.event.ActionEvent; import javax.swing.JList; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; import javax.swing.JScrollPane; import javax.swing.JPanel; public class GuardarEnArcade extends JFrame { private JTextField textField; private JTable table; /** Ventana donde salen los registros de las puntuaciones mas altas de arcade y donde guardamos nuestro registro * @param bd * @param fisicas * @param ganadosArcade Partidos ganados en modo arcade */ public GuardarEnArcade(BaseDeDatos bd, FisicasNuevas fisicas, int ganadosArcade) { setSize(474, 203); ScrollablePanel panelClasificacion = new ScrollablePanel(new BorderLayout()); //Implementamos aqui la clase ScrollablePanel por problemas con el JScrollPane panelClasificacion.setScrollableWidth(ScrollablePanel.ScrollableSizeHint.FIT); panelClasificacion.setScrollableHeight(ScrollablePanel.ScrollableSizeHint.STRETCH); getContentPane().add(panelClasificacion, BorderLayout.CENTER); DefaultTableModel model = new DefaultTableModel(); table = new JTable(model); model.addColumn("Usuario"); model.addColumn("Partidas ganadas"); String header[] = { "Usuario", "Partidos ganados" }; for (int i = 0; i < table.getColumnCount(); i++) { TableColumn column1 = table.getTableHeader().getColumnModel().getColumn(i); column1.setHeaderValue(header[i]); } table.getTableHeader().setFont(table.getTableHeader().getFont().deriveFont(Font.BOLD)); anadirATabla(model, bd); getContentPane().setLayout(new BorderLayout(0, 0)); JScrollPane scrollPane = new JScrollPane(table); panelClasificacion.add(scrollPane); getContentPane().add(panelClasificacion); JPanel panelNorte = new JPanel(); getContentPane().add(panelNorte, BorderLayout.NORTH); JLabel lblUsuario = new JLabel("Usuario:"); panelNorte.add(lblUsuario); textField = new JTextField(); panelNorte.add(textField); textField.setColumns(10); JButton btnGuardar = new JButton("Guardar"); panelNorte.add(btnGuardar); btnGuardar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { if (textField.getText() == null || textField.getText() == "") { JOptionPane.showMessageDialog(null, "Introduce el usuario.", "ERROR DE GUARDADO", JOptionPane.WARNING_MESSAGE); } else { bd.init(); bd.getCon().createStatement().executeUpdate("INSERT INTO Arcade(Usuario, 'Partidos ganados') " + "VALUES ('" + textField.getText() + "', " + ganadosArcade + ");"); bd.close(); } } catch (Exception e1) { JOptionPane.showMessageDialog(null, "NO SE HA PODIDO INTRODUCIR A LA BASE DE DATOS", "ERROR", JOptionPane.WARNING_MESSAGE); e1.printStackTrace(); } Inicio i = new Inicio(bd, fisicas); i.setVisible(true); dispose(); } }); setVisible(true); } private void anadirATabla(DefaultTableModel model, BaseDeDatos bd) { try { bd.init(); String query = "SELECT * FROM ARCADE ORDER BY \"Partidos Ganados\" DESC;"; ResultSet rs = bd.getCon().createStatement().executeQuery(query); while (rs.next()) { String nombre = rs.getString("Usuario"); int ganados = rs.getInt("Partidos Ganados"); model.addRow(new Object[] { nombre, ganados }); } rs.close(); bd.close(); } catch (Exception eee) { eee.printStackTrace(); } } }
[ "jorge.elbusto@opendeusto.es" ]
jorge.elbusto@opendeusto.es
44553053d9d0a61dc7929ccd22b03423746d8368
4c1f4cb5e454b2d7b9bd6c006c2b4475a1e00e6b
/JPA/cassandra/src/main/java/nivance/jpa/cassandra/prepare/support/exception/CassandraInsufficientReplicasAvailableException.java
35758fd04a0075498a4218e2d93dacd9c5483d88
[]
no_license
nivance/OSGi_Project
cabfa6ed4b73481a64a6e2bd30d205ead86b0318
57347607207461a3c1cfd36ac87ab7acdab38ed1
refs/heads/master
2020-07-04T03:02:58.766971
2015-01-16T13:01:11
2015-01-16T13:01:11
29,348,180
1
0
null
null
null
null
UTF-8
Java
false
false
1,556
java
/* * Copyright 2013 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 * * 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 nivance.jpa.cassandra.prepare.support.exception; import org.springframework.dao.TransientDataAccessException; /** * Spring data access exception for Cassandra when insufficient replicas are available for a given consistency level. * * @author Matthew T. Adams */ public class CassandraInsufficientReplicasAvailableException extends TransientDataAccessException { private static final long serialVersionUID = 6415130674604814905L; private int numberRequired; private int numberAlive; public CassandraInsufficientReplicasAvailableException(String msg) { super(msg); } public CassandraInsufficientReplicasAvailableException(int numberRequired, int numberAlive, String msg, Throwable cause) { super(msg, cause); this.numberRequired = numberRequired; this.numberAlive = numberAlive; } public int getNumberRequired() { return numberRequired; } public int getNumberAlive() { return numberAlive; } }
[ "limingjian@joyveb.com" ]
limingjian@joyveb.com
27cf4568090da43b4730734337274857c4f88116
e0abcd6fb8d5f5bc884be64e9e2838ff43386e25
/src/main/java/football/tickets/service/mapper/OrderMapper.java
df2a1a2186d171d00675e401757d7b1079fe90d2
[]
no_license
Nazar-yo/football-tickets-app
77754fb5566fecc6e01b763afb1a7bb01d9a96ac
5a8d9c9eaef41a6a1fb8102c8e707cffc2a9a627
refs/heads/main
2023-06-12T13:53:03.097060
2021-07-09T19:36:06
2021-07-09T19:36:06
376,284,256
0
0
null
null
null
null
UTF-8
Java
false
false
1,078
java
package football.tickets.service.mapper; import football.tickets.dto.response.OrderResponseDto; import football.tickets.model.Order; import football.tickets.model.Ticket; import football.tickets.util.DateTimePatternUtil; import java.time.format.DateTimeFormatter; import java.util.stream.Collectors; import org.springframework.stereotype.Component; @Component public class OrderMapper implements ResponseDtoMapper<OrderResponseDto, Order> { private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DateTimePatternUtil.DATE_TIME_PATTERN); @Override public OrderResponseDto mapToDto(Order order) { OrderResponseDto responseDto = new OrderResponseDto(); responseDto.setId(order.getId()); responseDto.setUserId(order.getUser().getId()); responseDto.setOrderTime(order.getOrderTime().format(formatter)); responseDto.setTicketIds(order.getTickets() .stream() .map(Ticket::getId) .collect(Collectors.toList())); return responseDto; } }
[ "bilaknazar@gmail.com" ]
bilaknazar@gmail.com
f03e225c52e06a004f3cc2422a6b046296857ab1
aa60ca068c5d56bf494f502a8392ce0967ae97b5
/advance-interview-practice/src/main/java/leetcode/contests/ContetsAE/Contests10.java
a6a9f605b8090b1bb8cf9ac019c99f0d83dc2dcf
[]
no_license
cyadav1010/spiceworks
4c5727325ecaf25442133b2b0f0fca35d2e39227
d7dc09824b81ae91395ec071e7f5fd6fa55dfbd5
refs/heads/master
2022-12-31T18:16:06.402553
2020-09-06T06:04:30
2020-09-06T06:04:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
12,319
java
package leetcode.contests.ContetsAE; import com.google.common.base.Strings; import org.junit.Test; import java.net.Inet4Address; import java.sql.Struct; import java.util.*; import java.util.stream.IntStream; public class Contests10 { @Test public void ContestsSolution() { List<Integer> a = new ArrayList<>(); String s = "rrlrlrllrlrlrlrlrlrlrllrlrlrrrrlrlrlr"; // 37 // 1 // 5 // 2014650 a.add(2); a.add(5); a.add(4); a.add(6); a.add(8); // System.out.println(segment(3, a)); String[] A = {"tars", "rats", "arts", "star"}; // System.out.println(numSimilarGroups(A)); int[][] graph = {{1, 1, 0, 0, 0, 0, 0, 0, 0, 0}, {1, 1, 0, 0, 0, 0, 0, 0, 0, 1}, {0, 0, 1, 0, 1, 0, 0, 0, 0, 1}, {0, 0, 0, 1, 0, 0, 0, 0, 0, 1}, {0, 0, 1, 0, 1, 0, 1, 0, 0, 1}, {0, 0, 0, 0, 0, 1, 1, 0, 0, 0}, {0, 0, 0, 0, 1, 1, 1, 0, 0, 1}, {0, 0, 0, 0, 0, 0, 0, 1, 1, 0}, {0, 0, 0, 0, 0, 0, 0, 1, 1, 0}, {0, 1, 1, 1, 1, 0, 1, 0, 0, 1}}; int[] in = {9, 0, 2}; // System.out.println(minMalwareSpread(graph, in)); int[] prices = {70, 4, 83, 56, 94, 72, 78, 43, 2, 86, 65, 100, 94, 56, 41, 66, 3, 33, 10, 3, 45, 94, 15, 12, 78, 60, 58, 0, 58, 15, 21, 7, 11, 41, 12, 96, 83, 77, 47, 62, 27, 19, 40, 63, 30, 4, 77, 52, 17, 57, 21, 66, 63, 29, 51, 40, 37, 6, 44, 42, 92, 16, 64, 33, 31, 51, 36, 0, 29, 95, 92, 35, 66, 91, 19, 21, 100, 95, 40, 61, 15, 83, 31, 55, 59, 84, 21, 99, 45, 64, 90, 25, 40, 6, 41, 5, 25, 52, 59, 61, 51, 37, 92, 90, 20, 20, 96, 66, 79, 28, 83, 60, 91, 30, 52, 55, 1, 99, 8, 68, 14, 84, 59, 5, 34, 93, 25, 10, 93, 21, 35, 66, 88, 20, 97, 25, 63, 80, 20, 86, 33, 53, 43, 86, 53, 55, 61, 77, 9, 2, 56, 78, 43, 19, 68, 69, 49, 1, 6, 5, 82, 46, 24, 33, 85, 24, 56, 51, 45, 100, 94, 26, 15, 33, 35, 59, 25, 65, 32, 26, 93, 73, 0, 40, 92, 56, 76, 18, 2, 45, 64, 66, 64, 39, 77, 1, 55, 90, 10, 27, 85, 40, 95, 78, 39, 40, 62, 30, 12, 57, 84, 95, 86, 57, 41, 52, 77, 17, 9, 15, 33, 17, 68, 63, 59, 40, 5, 63, 30, 86, 57, 5, 55, 47, 0, 92, 95, 100, 25, 79, 84, 93, 83, 93, 18, 20, 32, 63, 65, 56, 68, 7, 31, 100, 88, 93, 11, 43, 20, 13, 54, 34, 29, 90, 50, 24, 13, 44, 89, 57, 65, 95, 58, 32, 67, 38, 2, 41, 4, 63, 56, 88, 39, 57, 10, 1, 97, 98, 25, 45, 96, 35, 22, 0, 37, 74, 98, 14, 37, 77, 54, 40, 17, 9, 28, 83, 13, 92, 3, 8, 60, 52, 64, 8, 87, 77, 96, 70, 61, 3, 96, 83, 56, 5, 99, 81, 94, 3, 38, 91, 55, 83, 15, 30, 39, 54, 79, 55, 86, 85, 32, 27, 20, 74, 91, 99, 100, 46, 69, 77, 34, 97, 0, 50, 51, 21, 12, 3, 84, 84, 48, 69, 94, 28, 64, 36, 70, 34, 70, 11, 89, 58, 6, 90, 86, 4, 97, 63, 10, 37, 48, 68, 30, 29, 53, 4, 91, 7, 56, 63, 22, 93, 69, 93, 1, 85, 11, 20, 41, 36, 66, 67, 57, 76, 85, 37, 80, 99, 63, 23, 71, 11, 73, 41, 48, 54, 61, 49, 91, 97, 60, 38, 99, 8, 17, 2, 5, 56, 3, 69, 90, 62, 75, 76, 55, 71, 83, 34, 2, 36, 56, 40, 15, 62, 39, 78, 7, 37, 58, 22, 64, 59, 80, 16, 2, 34, 83, 43, 40, 39, 38, 35, 89, 72, 56, 77, 78, 14, 45, 0, 57, 32, 82, 93, 96, 3, 51, 27, 36, 38, 1, 19, 66, 98, 93, 91, 18, 95, 93, 39, 12, 40, 73, 100, 17, 72, 93, 25, 35, 45, 91, 78, 13, 97, 56, 40, 69, 86, 69, 99, 4, 36, 36, 82, 35, 52, 12, 46, 74, 57, 65, 91, 51, 41, 42, 17, 78, 49, 75, 9, 23, 65, 44, 47, 93, 84, 70, 19, 22, 57, 27, 84, 57, 85, 2, 61, 17, 90, 34, 49, 74, 64, 46, 61, 0, 28, 57, 78, 75, 31, 27, 24, 10, 93, 34, 19, 75, 53, 17, 26, 2, 41, 89, 79, 37, 14, 93, 55, 74, 11, 77, 60, 61, 2, 68, 0, 15, 12, 47, 12, 48, 57, 73, 17, 18, 11, 83, 38, 5, 36, 53, 94, 40, 48, 81, 53, 32, 53, 12, 21, 90, 100, 32, 29, 94, 92, 83, 80, 36, 73, 59, 61, 43, 100, 36, 71, 89, 9, 24, 56, 7, 48, 34, 58, 0, 43, 34, 18, 1, 29, 97, 70, 92, 88, 0, 48, 51, 53, 0, 50, 21, 91, 23, 34, 49, 19, 17, 9, 23, 43, 87, 72, 39, 17, 17, 97, 14, 29, 4, 10, 84, 10, 33, 100, 86, 43, 20, 22, 58, 90, 70, 48, 23, 75, 4, 66, 97, 95, 1, 80, 24, 43, 97, 15, 38, 53, 55, 86, 63, 40, 7, 26, 60, 95, 12, 98, 15, 95, 71, 86, 46, 33, 68, 32, 86, 89, 18, 88, 97, 32, 42, 5, 57, 13, 1, 23, 34, 37, 13, 65, 13, 47, 55, 85, 37, 57, 14, 89, 94, 57, 13, 6, 98, 47, 52, 51, 19, 99, 42, 1, 19, 74, 60, 8, 48, 28, 65, 6, 12, 57, 49, 27, 95, 1, 2, 10, 25, 49, 68, 57, 32, 99, 24, 19, 25, 32, 89, 88, 73, 96, 57, 14, 65, 34, 8, 82, 9, 94, 91, 19, 53, 61, 70, 54, 4, 66, 26, 8, 63, 62, 9, 20, 42, 17, 52, 97, 51, 53, 19, 48, 76, 40, 80, 6, 1, 89, 52, 70, 38, 95, 62, 24, 88, 64, 42, 61, 6, 50, 91, 87, 69, 13, 58, 43, 98, 19, 94, 65, 56, 72, 20, 72, 92, 85, 58, 46, 67, 2, 23, 88, 58, 25, 88, 18, 92, 46, 15, 18, 37, 9, 90, 2, 38, 0, 16, 86, 44, 69, 71, 70, 30, 38, 17, 69, 69, 80, 73, 79, 56, 17, 95, 12, 37, 43, 5, 5, 6, 42, 16, 44, 22, 62, 37, 86, 8, 51, 73, 46, 44, 15, 98, 54, 22, 47, 28, 11, 75, 52, 49, 38, 84, 55, 3, 69, 100, 54, 66, 6, 23, 98, 22, 99, 21, 74, 75, 33, 67, 8, 80, 90, 23, 46, 93, 69, 85, 46, 87, 76, 93, 38, 77, 37, 72, 35, 3, 82, 11, 67, 46, 53, 29, 60, 33, 12, 62, 23, 27, 72, 35, 63, 68, 14, 35, 27, 98, 94, 65, 3, 13, 48, 83, 27, 84, 86, 49, 31, 63, 40, 12, 34, 79, 61, 47, 29, 33, 52, 100, 85, 38, 24, 1, 16, 62, 89, 36, 74, 9, 49, 62, 89}; System.out.println(maxProfit(1000000000, prices)); } public int maxProfit(int k, int[] prices) { int n = prices.length; System.out.println(n); if (k == 0 || n <= 1) return 0; int[][] dp = new int[2][n]; int min = prices[0]; int ans = 0; if(k>n/2){ for (int i = 1; i < n; i++) { ans+=Math.max(0, prices[i]-prices[i-1]); } return ans; } for (int i = 1; i < n; i++) { if (prices[i] - min > 0) { dp[0][i] = prices[i] - min; ans = Math.max(ans, dp[0][i]); } min = Math.min(min, prices[i]); } for (int t = 2; t<=(n/2)+1 && t <= k; t++) { int max = 0; dp[1] = new int[n]; for (int last = 0; last < n; last++) { if (dp[0][last] > 0) { max = Math.max(dp[0][last], max); } if (max > 0 && last + 2 < n) { min = prices[last + 1]; for (int i = last + 2; i < n; i++) { if (prices[i] - min > 0) { dp[1][i] = Math.max(dp[1][i], max + prices[i] - min); ans = Math.max(ans, dp[1][i]); } min = Math.min(min, prices[i]); } } } dp[0] = dp[1]; } return ans; } public int numSimilarGroups(String[] A) { int l = A.length; UnionFind unionFind = new UnionFind(l); IntStream.range(0, l).forEach(i -> IntStream.range(i + 1, l) .forEach(j -> unionFind.group(A, i, j))); return unionFind.result; } class UnionFind { int parent[]; int result = 0; UnionFind(Integer n) { parent = new int[n]; IntStream.range(0, n).forEach(i -> parent[i] = i); result = n; } public void group(String[] A, int i, int j) { if (isSimilar(A[i], A[j])) { union(i, j); } } public int union(int i, int j) { int p1 = findGroupId(i); int p2 = findGroupId(j); if (p1 == p2) { return p1; } parent[p2] = p1; result--; return result; } public int findGroupId(int i) { if (parent[i] == i) { return i; } parent[i] = findGroupId(parent[i]); return parent[i]; } public boolean isSimilar(String a, String b) { int l = a.length(); long diff = IntStream.range(0, l) .filter(i -> a.charAt(i) != b.charAt(i)) .count(); return diff == 0 || diff == 2; } } public static int segment(int x, List<Integer> space) { int last = 0; int n = space.size(); int max = 0; for (int i = 1; i < x; i++) { if (space.get(i) <= space.get(last)) { last = i; } } max = Math.max(max, space.get(last)); for (int i = x; i < n; ) { if (i - x + 1 <= last) { if (space.get(i) <= space.get(last)) { last = i; } max = Math.max(max, space.get(last)); i++; } else { last++; int t = last; while (t <= i) { if (space.get(t) <= space.get(last)) { last = t; } t++; } } } return max; } public int minMalwareSpread(int[][] graph, int[] initial) { int m = graph.length; int n = graph[0].length; List<Integer>[] network = new ArrayList[301]; IntStream.range(0, m).forEach(i -> network[i] = new ArrayList<>()); IntStream.range(0, m).forEach(i -> IntStream.range(0, n).forEach(j -> { if (graph[i][j] == 1) { network[i].add(j); network[j].add(i); } }) ); int l = initial.length; boolean visited[] = new boolean[301]; int group[] = new int[301]; IntStream.range(0, l).forEach(i -> group[initial[i]] = 1); IntStream.range(0, l).forEach(i -> { if (!visited[initial[i]]) dfsMaxGroup(network, initial[i], initial[i], group, visited); }); int ans = -1; int c = 0; int tt = 0; int ans2 = 0; for (int i = 0; i < 301; i++) { if (group[i] >= 1) { if (c == 0) { ans = i; c = 1; } else { if (group[i] > group[ans]) { ans = i; } } } else { if (group[i] == -1 && tt == 0) { ans2 = i; tt = 1; } } } return ans > 0 ? ans : ans2; } public int dfsMaxGroup(List<Integer>[] network, int prt, int node, int group[], boolean visited[]) { if ((prt != node && group[node] == 1) || group[node] == -1) { group[node] = -1; return -1; } if (visited[node]) { return 0; } visited[node] = true; List<Integer> adjs = network[node]; int nodes = 1; Map<Integer, Double> map = new HashMap<>(); for (int nd : adjs) { int t = dfsMaxGroup(network, prt, nd, group, visited); if (t == -1) { if (group[node] == 1) { group[node] = -1; } return -1; } nodes += t; } if (group[node] == 1) { group[node] = nodes; } return nodes; } public static long prison(int n, int m, List<Integer> h, List<Integer> v) { int hh = h.size(); int vv = v.size(); boolean[] hvis = new boolean[n + 2]; boolean[] vvis = new boolean[m + 2]; for (int i = 0; i < hh; i++) { hvis[h.get(i)] = true; } for (int i = 0; i < vv; i++) { vvis[v.get(i)] = true; } int hmax = 1; int lastFound = 0; for (int i = 1; i <= n + 1; i++) { if (!hvis[i]) { hmax = Math.max(hmax, i - lastFound); lastFound = i; } } int vmax = 1; lastFound = 0; for (int i = 1; i <= m + 1; i++) { if (!vvis[i]) { vmax = Math.max(vmax, i - lastFound); lastFound = i; } } return hmax * vmax; } }
[ "oyadav@groupon.com" ]
oyadav@groupon.com
1d5b24e739787a6d52ef376e3a41a99a04a00273
670db6fc228ad7ef92aaad838415fb2e4143805b
/src/my/program/resumeemulator/ResumeActivity.java
606f6e12d906911f344173283de44f52a93295cd
[]
no_license
seriizel/ResumeEmulator
fde05ce161e42f65a2888ebd58918e122b1c1e57
3b1e64b42d8cb928a08c6f87f4259c1d1638b333
refs/heads/master
2020-05-01T07:13:47.628136
2013-09-14T20:46:00
2013-09-14T20:46:00
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,084
java
package my.program.resumeemulator; import java.util.Calendar; import android.os.Bundle; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.app.Activity; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.Intent; import android.view.View; public class ResumeActivity extends Activity { private Button buttonDate, buttonSend; private TextView textDate; private Spinner spinnerGender; private EditText editFIO, editPost, editSalary, editPhone, editEmail; private int Year; private int Month; private int Day; static final int DATE_DIALOG_ID = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_resume); buttonDate = (Button) findViewById(R.id.buttonDate); buttonSend = (Button) findViewById(R.id.buttonSend); textDate = (TextView) findViewById(R.id.textDate); spinnerGender = (Spinner) findViewById(R.id.spinnerGender); editFIO = (EditText) findViewById(R.id.editFIO); editPost = (EditText) findViewById(R.id.editPost); editSalary = (EditText) findViewById(R.id.editSalary); editPhone = (EditText) findViewById(R.id.editPhone); editEmail = (EditText) findViewById(R.id.editEmail); Calendar c = Calendar.getInstance(); Year = c.get(Calendar.YEAR); Month = c.get(Calendar.MONTH); Day = c.get(Calendar.DAY_OF_MONTH); buttonDate.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { showDialog(DATE_DIALOG_ID); } }); buttonSend.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(ResumeActivity.this, AnswerActivity.class); intent.putExtra("Resume", editFIO.getText().toString()+"\n" + textDate.getText().toString()+"\n" + spinnerGender.getSelectedItem().toString()+"\n" + editPost.getText().toString()+"\n" + editSalary.getText().toString()+"\n" + editPhone.getText().toString()+"\n" + editEmail.getText().toString()); startActivity(intent); } }); updateDisplay(); } private void updateDisplay() { textDate.setText( new StringBuilder() .append(Day).append(".") .append(Month+1).append(".") .append(Year)); } private DatePickerDialog.OnDateSetListener DateSetListener = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { Year = year; Month = monthOfYear; Day = dayOfMonth; updateDisplay(); } }; protected Dialog onCreateDialog(int id) { return new DatePickerDialog(this, DateSetListener, Year, Month, Day); } }
[ "serii-zel@rambler.ru" ]
serii-zel@rambler.ru
22016160da415a7c681a1086b08814e49ae71f4d
92f0b33fc3c1dc4caf051edf31c5f42d2d9d5b88
/SeleniumPractice/src/selpkg/FbSignUp.java
5f1fbe932720bddd49bf2bf276362f9894a4a230
[]
no_license
LavleenKaur/SeleniumPractice
f627fecda6ca0ae385bc06aea9b1247df27e9301
bcba7b22f37b0b3ac7ce82cb9568837f77be119b
refs/heads/master
2022-12-12T10:25:32.638224
2020-09-16T05:14:53
2020-09-16T05:14:53
294,924,500
0
0
null
null
null
null
UTF-8
Java
false
false
2,028
java
package selpkg; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; public class FbSignUp { public static void main(String[] args) throws InterruptedException{ System.setProperty("webdriver.chrome.driver","../SeleniumPractice/chromedriver.exe"); ChromeDriver driver=new ChromeDriver(); driver.get("https://www.facebook.com"); driver.manage().window().maximize(); WebElement createacc=driver.findElement(By.id("u_0_2")); createacc.click(); Thread.sleep(3000); //driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS); WebElement fname=driver.findElement(By.name("firstname")); fname.sendKeys("Anne"); WebElement lname=driver.findElement(By.name("lastname")); lname.sendKeys("Peterson"); //driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); WebElement email1=driver.findElement(By.id("u_1_g"));//id of email textbox email1.sendKeys("Anne95@gmail.com"); WebElement email2=driver.findElement(By.id("u_1_j"));//id of email textbox email2.sendKeys("Anne95@gmail.com"); //driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); WebElement newpass=driver.findElement(By.name("reg_passwd__")); newpass.sendKeys("Anne@123"); WebElement dobday=driver.findElement(By.id("day")); Select d=new Select(dobday); d.selectByIndex(10);//selecting date 10 by passing the index from dropdown WebElement dobmonth=driver.findElement(By.id("month")); Select m=new Select(dobmonth); m.selectByVisibleText("Jul");// selecting month July by passing the text from dropdown WebElement dobyear=driver.findElement(By.id("year")); Select y=new Select(dobyear); y.selectByValue("1995");//passing value 1995 WebElement gender=driver.findElement(By.cssSelector("input[value='1']")); gender.click(); WebElement signup=driver.findElement(By.name("websubmit")); signup.click(); } }
[ "hp@hp" ]
hp@hp
004473548c98114b19509050b985027559307074
a5cc431cc84994751051e23d91e17a0a6a85ff5f
/app/src/main/java/com/udacity/popularmovies/events/DownloadedMovieListEvent.java
455f691203f12655cfc93b9af3bdd5339c12deb1
[ "MIT" ]
permissive
erickprieto/UdacityPopularMoviesApp
12ecd0b5d4c17a71ac3de61e971273d78ab2e700
1a1fa732b8d9101f2ec3531e9880a71fb26eed6a
refs/heads/master
2020-04-01T06:31:23.397791
2018-11-11T04:50:15
2018-11-11T04:50:15
108,640,700
0
0
null
null
null
null
UTF-8
Java
false
false
725
java
package com.udacity.popularmovies.events; import com.udacity.popularmovies.models.Movie; import java.util.List; public class DownloadedMovieListEvent { private boolean popularMovie; private List<Movie> modelos; public DownloadedMovieListEvent(List<Movie> modelos, boolean popularMovie) { this.modelos = modelos; this.popularMovie = popularMovie; } public List<Movie> getModelos() { return modelos; } public void setModelos(List<Movie> modelos) { this.modelos = modelos; } public boolean isPopularMovie() { return popularMovie; } public void setPopularMovie(boolean popularMovie) { this.popularMovie = popularMovie; } }
[ "erickprieto@hotmail.com" ]
erickprieto@hotmail.com
d7c0bceaea7448de904d2e501bae16681b2c7e17
27dced2adec698f50508e38c3a7db6e39f3b7d96
/src/main/java/com/novarch/jojomod/entities/stands/dirtyDeedsDoneDirtCheap/EntityDirtyDeedsDoneDirtCheap.java
e4906b78b34ad6aa6eec8ecf312b5add660d2d68
[]
no_license
kingcrimson-13/JoJo-s-Bizarre-Survival
297a2755f5ac3fe2c314d1b700d91d61d4b2431d
5ce4bdb8382b7c944ad955d73401bce8c01258c9
refs/heads/master
2022-11-15T20:45:52.424455
2020-06-24T19:07:18
2020-06-24T19:07:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
8,755
java
package com.novarch.jojomod.entities.stands.dirtyDeedsDoneDirtCheap; import com.novarch.jojomod.capabilities.stand.Stand; import com.novarch.jojomod.entities.stands.EntityStandBase; import com.novarch.jojomod.entities.stands.EntityStandPunch; import com.novarch.jojomod.events.EventD4CTeleportProcessor; import com.novarch.jojomod.init.DimensionInit; import com.novarch.jojomod.init.EntityInit; import com.novarch.jojomod.init.SoundInit; import com.novarch.jojomod.util.DimensionHopTeleporter; import com.novarch.jojomod.util.Util; import mcp.MethodsReturnNonnullByDefault; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityType; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.potion.EffectInstance; import net.minecraft.potion.Effects; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.dimension.DimensionType; import net.minecraft.world.server.ServerWorld; import javax.annotation.ParametersAreNonnullByDefault; @SuppressWarnings("ConstantConditions") @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault public class EntityDirtyDeedsDoneDirtCheap extends EntityStandBase { private int oratick = 0; private int oratickr = 0; public EntityDirtyDeedsDoneDirtCheap(EntityType<? extends EntityStandBase> type, World world) { super(type, world); this.spawnSound = SoundInit.SPAWN_D4C.get(); this.standID = Util.StandID.dirtyDeedsDoneDirtCheap; } public EntityDirtyDeedsDoneDirtCheap(World world) { super(EntityInit.D4C.get(), world); this.spawnSound = SoundInit.SPAWN_D4C.get(); this.standID = Util.StandID.dirtyDeedsDoneDirtCheap; } /** * Used to shorten the code of the method below, removing the need to make a <code>new</code> {@link DimensionHopTeleporter} every time {@link Entity}# changeDimension is called. * * @param entity The {@link Entity} that will be transported. * @param type The {@link DimensionType} the entity will be transported to. */ private void changeDimension(DimensionType type, Entity entity) { entity.changeDimension(type, new DimensionHopTeleporter((ServerWorld) entity.getEntityWorld(), entity.getPosX(), entity.getPosY(), entity.getPosZ())); } private void transportEntity(Entity entity) { if (entity.world.getDimension().getType() == DimensionType.OVERWORLD) changeDimension(DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE), entity); else if (entity.world.getDimension().getType() == DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE)) changeDimension(DimensionType.OVERWORLD, entity); else if (entity.world.getDimension().getType() == DimensionType.THE_NETHER) changeDimension(DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE_NETHER), entity); else if (entity.world.getDimension().getType() == DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE_NETHER)) changeDimension(DimensionType.THE_NETHER, entity); else if (entity.world.getDimension().getType() == DimensionType.THE_END) changeDimension(DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE_END), entity); else if (entity.world.getDimension().getType() == DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE_END)) changeDimension(DimensionType.THE_END, entity); } private void changePlayerDimension(PlayerEntity player) { if (player.world.getDimension().getType() == DimensionType.OVERWORLD) EventD4CTeleportProcessor.d4cPassengers.put(player, DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE)); else if (player.world.getDimension().getType() == DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE)) EventD4CTeleportProcessor.d4cPassengers.put(player, DimensionType.OVERWORLD); else if (player.world.getDimension().getType() == DimensionType.THE_NETHER) EventD4CTeleportProcessor.d4cPassengers.put(player, DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE_NETHER)); else if (player.world.getDimension().getType() == DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE_NETHER)) EventD4CTeleportProcessor.d4cPassengers.put(player, DimensionType.THE_NETHER); else if (player.world.getDimension().getType() == DimensionType.THE_END) EventD4CTeleportProcessor.d4cPassengers.put(player, DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE_END)); else if (player.world.getDimension().getType() == DimensionType.byName(DimensionInit.D4C_DIMENSION_TYPE_END)) EventD4CTeleportProcessor.d4cPassengers.put(player, DimensionType.THE_END); } @Override public void tick() { super.tick(); this.fallDistance = 0.0F; if (getMaster() != null) { PlayerEntity player = getMaster(); Stand.getLazyOptional(player).ifPresent(props -> { if (props.getCooldown() > 0) props.subtractCooldown(1); player.addPotionEffect(new EffectInstance(Effects.RESISTANCE, 40, 2)); if ((player.world.getBlockState(new BlockPos(player.getPosition().getX(), player.getPosition().getY(), player.getPosition().getZ() - 1)).getMaterial() != Material.AIR && player.world.getBlockState(new BlockPos(player.getPosition().getX(), player.getPosition().getY(), player.getPosition().getZ() + 1)).getMaterial() != Material.AIR) || (player.world.getBlockState(new BlockPos(player.getPosition().getX() - 1, player.getPosition().getY(), player.getPosition().getZ())).getMaterial() != Material.AIR && player.world.getBlockState(new BlockPos(player.getPosition().getX() + 1, player.getPosition().getY(), player.getPosition().getZ())).getMaterial() != Material.AIR)) { if (player.isCrouching() || player.isAirBorne) { if (props.getAbility() && props.getCooldown() <= 0) { changePlayerDimension(player); world.getServer().getWorld(this.dimension).getEntities() .filter(entity -> entity instanceof LivingEntity) .filter(entity -> !(entity instanceof PlayerEntity)) .filter(entity -> !(entity instanceof EntityStandBase)) .filter(entity -> entity.getDistance(player) < 3.0f || entity.getDistance(this) < 3.0f) .forEach(this::transportEntity); world.getPlayers() .stream() .filter(playerEntity -> Stand.getCapabilityFromPlayer(playerEntity).getStandID() != Util.StandID.GER) .filter(playerEntity -> player.getDistance(player) < 3.0f || playerEntity.getDistance(this) < 3.0f) .forEach(this::changePlayerDimension); player.getFoodStats().addStats(-3, 0.0f); props.setStandOn(false); props.setCooldown(200); this.remove(); } } } }); if (standOn) { followMaster(); setRotationYawHead(player.rotationYaw); setRotation(player.rotationYaw, player.rotationPitch); if (!player.isAlive()) remove(); if (player.isSprinting()) { if (attackSwing(player)) this.oratick++; if (this.oratick == 1) { if (!player.isCreative()) player.getFoodStats().addStats(-1, 0.0F); if (!this.world.isRemote) this.orarush = true; } } else if (attackSwing(getMaster())) { if (!this.world.isRemote) { this.oratick++; if (this.oratick == 1) { this.world.playSound(null, new BlockPos(this.getPosX(), this.getPosY(), this.getPosZ()), SoundInit.PUNCH_MISS.get(), getSoundCategory(), 1.0F, 0.8F / (this.rand.nextFloat() * 0.4F + 1.2F) + 0.5F); EntityStandPunch.DirtyDeedsDoneDirtCheap dirtyDeedsDoneDirtCheap = new EntityStandPunch.DirtyDeedsDoneDirtCheap(this.world, this, player); dirtyDeedsDoneDirtCheap.shoot(player, player.rotationPitch, player.rotationYaw, 2.0F, 0.2F); this.world.addEntity(dirtyDeedsDoneDirtCheap); } } } if (player.swingProgressInt == 0) this.oratick = 0; if (this.orarush) { player.setSprinting(false); this.oratickr++; if (this.oratickr >= 10) if (!this.world.isRemote) { player.setSprinting(false); EntityStandPunch.DirtyDeedsDoneDirtCheap dirtyDeedsDoneDirtCheap1 = new EntityStandPunch.DirtyDeedsDoneDirtCheap(this.world, this, player); dirtyDeedsDoneDirtCheap1.setRandomPositions(); dirtyDeedsDoneDirtCheap1.shoot(player, player.rotationPitch, player.rotationYaw, 2.0F, 0.2F); this.world.addEntity(dirtyDeedsDoneDirtCheap1); EntityStandPunch.DirtyDeedsDoneDirtCheap dirtyDeedsDoneDirtCheap2 = new EntityStandPunch.DirtyDeedsDoneDirtCheap(this.world, this, player); dirtyDeedsDoneDirtCheap2.setRandomPositions(); dirtyDeedsDoneDirtCheap2.shoot(player, player.rotationPitch, player.rotationYaw, 2.0F, 0.2F); this.world.addEntity(dirtyDeedsDoneDirtCheap2); } if (this.oratickr >= 80) { this.orarush = false; this.oratickr = 0; } } } } } }
[ "ivan.pecotic25@gmail.com" ]
ivan.pecotic25@gmail.com
5365a211f124896ff7c669504b74b8d1631d19d7
a2353927105bf7d503fe47f23b87c6cc7a75e27c
/src/test/java/pl/pateman/wiredi/testcomponents/impl/LettersOnlyRandomStringGenerator.java
b163ce0d79ad7f7f2ac6e6aaa9dd41eaf986695d
[ "Unlicense" ]
permissive
pateman/WireDI
e1e022e625af6f5ce29cbc51b66df1ceeb0f8562
eee4fcecbe71da89ed2025ae370a1bffe84fbd42
refs/heads/master
2020-04-08T21:10:58.688958
2019-04-28T17:36:44
2019-04-28T17:36:44
159,733,168
1
0
null
null
null
null
UTF-8
Java
false
false
704
java
package pl.pateman.wiredi.testcomponents.impl; import pl.pateman.wiredi.annotation.WireComponent; import pl.pateman.wiredi.testcomponents.RandomStringGenerator; import java.util.Random; @WireComponent(name = "lettersOnlyRandomStringGenerator", multiple = true) public class LettersOnlyRandomStringGenerator extends AbstractRandomStringGenerator implements RandomStringGenerator { private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST"; private final Random random; public LettersOnlyRandomStringGenerator() { random = new Random(); } @Override public String generate() { return getRandomString(ALPHABET, random, 6); } }
[ "patrick.nusbaum@gmail.com" ]
patrick.nusbaum@gmail.com
41ecb51f6ed47a0200b01c645bf2d7d960826134
f4e15ee34808877459d81fd601d6be03bdfb4a9d
/org/fourthline/cling/registry/RegistrationException.java
e1b953845245b8b6f43a3bde891e61c9a3ad38ce
[]
no_license
Lianite/wurm-server-reference
369081debfa72f44eafc6a080002c4a3970f8385
e4dd8701e4af13901268cf9a9fa206fcb5196ff0
refs/heads/master
2023-07-22T16:06:23.426163
2020-04-07T23:15:35
2020-04-07T23:15:35
253,933,452
0
0
null
null
null
null
UTF-8
Java
false
false
692
java
// // Decompiled by Procyon v0.5.30 // package org.fourthline.cling.registry; import org.fourthline.cling.model.ValidationError; import java.util.List; public class RegistrationException extends RuntimeException { public List<ValidationError> errors; public RegistrationException(final String s) { super(s); } public RegistrationException(final String s, final Throwable throwable) { super(s, throwable); } public RegistrationException(final String s, final List<ValidationError> errors) { super(s); this.errors = errors; } public List<ValidationError> getErrors() { return this.errors; } }
[ "jdraco6@gmail.com" ]
jdraco6@gmail.com
49055873ab95ce70e76b318217f7324825f2910b
f7fbc015359f7e2a7bae421918636b608ea4cef6
/base-one/tags/hsqldb_1_8_0_RC8/src/org/hsqldb/util/SqlServerTransferHelper.java
9e583d8ac7d5007a57eb69bac4bb85099a4fa287
[]
no_license
svn2github/hsqldb
cdb363112cbdb9924c816811577586f0bf8aba90
52c703b4d54483899d834b1c23c1de7173558458
refs/heads/master
2023-09-03T10:33:34.963710
2019-01-18T23:07:40
2019-01-18T23:07:40
155,365,089
0
0
null
null
null
null
UTF-8
Java
false
false
4,200
java
/* Copyright (c) 2001-2005, The HSQL Development Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the HSQL Development Group nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG, * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hsqldb.util; import java.sql.Types; // sqlbob@users 20020325 - patch 1.7.0 - reengineering /** * Conversions from SQLServer7 databases * * @version 1.7.0 */ class SqlServerTransferHelper extends TransferHelper { private boolean firstTinyintRow; private boolean firstSmallintRow; SqlServerTransferHelper() { super(); } SqlServerTransferHelper(TransferDb database, Traceable t, String q) { super(database, t, q); } String formatTableName(String t) { if (t == null) { return t; } if (t.equals("")) { return t; } if (t.indexOf(' ') != -1) { return ("[" + t + "]"); } else { return (formatIdentifier(t)); } } int convertFromType(int type) { // MS SQL 7 specific problems (Northwind database) if (type == 11) { tracer.trace("Converted DATETIME (type 11) to TIMESTAMP"); type = Types.TIMESTAMP; } else if (type == -9) { tracer.trace("Converted NVARCHAR (type -9) to VARCHAR"); type = Types.VARCHAR; } else if (type == -8) { tracer.trace("Converted NCHAR (type -8) to VARCHAR"); type = Types.VARCHAR; } else if (type == -10) { tracer.trace("Converted NTEXT (type -10) to VARCHAR"); type = Types.VARCHAR; } else if (type == -1) { tracer.trace("Converted LONGTEXT (type -1) to LONGVARCHAR"); type = Types.LONGVARCHAR; } return (type); } void beginTransfer() { firstSmallintRow = true; firstTinyintRow = true; } Object convertColumnValue(Object value, int column, int type) { // solves a problem for MS SQL 7 if ((type == Types.SMALLINT) && (value instanceof Integer)) { if (firstSmallintRow) { firstSmallintRow = false; tracer.trace("SMALLINT: Converted column " + column + " Integer to Short"); } value = new Short((short) ((Integer) value).intValue()); } else if ((type == Types.TINYINT) && (value instanceof Integer)) { if (firstTinyintRow) { firstTinyintRow = false; tracer.trace("TINYINT: Converted column " + column + " Integer to Byte"); } value = new Byte((byte) ((Integer) value).intValue()); } return (value); } }
[ "(no author)@7c7dc5f5-a22d-0410-a3af-b41755a11667" ]
(no author)@7c7dc5f5-a22d-0410-a3af-b41755a11667
0e796814908e65b9e6947779876bd03e4c73d29e
9ca7ea8ed22d19554bacc45e5005f7853fdbdd84
/test/fiduciaryadvisor/OffshoreTest.java
ce6518a45d1d84daea2d0bc6812f102de271c4a1
[]
no_license
tschultz1216/FiduciaryAdviser
3d6f2218aaecff23c2af5357af0ddfae72a3bb1b
9062f54a68f90ffe34c3d638fe1131c00f3a7e44
refs/heads/master
2020-03-16T03:22:49.316230
2018-05-08T13:03:17
2018-05-08T13:03:17
132,486,362
0
0
null
null
null
null
UTF-8
Java
false
false
1,405
java
package fiduciaryadvisor; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * @author Leng Ghuy, Deborah Lawrence, Todd Schultz * @class CSCI-338 Software Engineering * @assignment Team Project - FiduciaryInvestmentAdviser * @date May 8th, 2018 */ public class OffshoreTest { public OffshoreTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of calculate method, of class Offshore. */ @Test public void testCalculate() { System.out.println("calculate"); float money = 7000F; int years = 40; Offshore instance = new Offshore(); float expResult = 10422.046875F; float result = instance.calculate(money, years); assertEquals(expResult, result, 0.0001); } /** * Test of getRisk method, of class Offshore. */ @Test public void testGetRisk() { System.out.println("getRisk"); Offshore instance = new Offshore(); boolean expResult = true; boolean result = instance.getRisk(); assertEquals(expResult, result); } }
[ "tschultz@unca.edu" ]
tschultz@unca.edu
8a9af205a7018411129f749f62209e7fdd54c4f3
a1aa05955e90a73e4fe38c2bd9eab6456a974c50
/src/optimization/genetic/operator/mutation/MutationByDistribution.java
8ca6b0c53f13b1e96eb5ceb025ee13aa8ee009fa
[]
no_license
game013/EvolutiveComputation
ae429afc86979fa40ebfa6b0c0ca1aefdd8fbc5e
fd31d0be7f0a6192213cbd7f449f8530d00300d5
refs/heads/master
2021-01-24T18:57:25.904491
2017-06-02T04:23:52
2017-06-02T04:23:52
84,480,989
0
0
null
null
null
null
UTF-8
Java
false
false
2,501
java
/** * COPYRIGHT (C) 2015. All Rights Reserved. */ package optimization.genetic.operator.mutation; import java.util.Optional; import optimization.distribution.Distribution; import optimization.distribution.ParametricalDistribution; import optimization.function.fitness.Function; import optimization.function.space.Space; import optimization.util.type.Solution; import optimization.util.type.SolutionParameter; import optimization.util.type.constant.ParameterName; /** * @author Oscar Garavito * */ public class MutationByDistribution<C> implements GeneticMutator<double[], C> { /** * Distribution to be used in variation. */ private final Distribution distribution; /** * @param distribution */ public MutationByDistribution(Distribution distribution) { this.distribution = distribution; } /* * (non-Javadoc) * @see * optimization.genetic.operator.mutation.GeneticMutator#mutate(optimization * .util.type.Solution, optimization.function.fitness.Function, * optimization.function.space.Space) */ @Override public Solution<double[], C> mutate(Solution<double[], C> child, Function<double[], C> fitnessFunction, Space<double[]> space) { // Mutation of endogenous parameter Optional<SolutionParameter> parameters = child.getParameters(); if (parameters.isPresent() && Math.random() < 0.05) { double oldSigma = (double) parameters.get().get(ParameterName.SIGMA); double alpha = 1.0 + 1.0 / Math.sqrt(20); double newSigma = Math.random() >= 0.5 ? oldSigma * alpha : oldSigma / alpha; parameters.get().set(ParameterName.SIGMA, newSigma); } if (ParametricalDistribution.class.isAssignableFrom(this.distribution.getClass())) { ((ParametricalDistribution) this.distribution).setParameters(parameters); } Solution<double[], C> solution = GeneticMutator.super.mutate(child, fitnessFunction, space); return solution; } /* * (non-Javadoc) * @see * optimization.genetic.operator.GeneticMutator#mutate(java.lang.Object, * optimization.function.fitness.Function, * optimization.function.space.Space) */ @Override public double[] mutate(double[] origin, Function<double[], C> fitnessFunction, Space<double[]> space) { double[] result = new double[origin.length]; for (int i = 0; i < origin.length; i++) { double delta = distribution.nextRandom(); result[i] = delta + origin[i]; } return result; } /** * @return the distribution */ public Distribution getDistribution() { return distribution; } }
[ "game013@gmail.com" ]
game013@gmail.com
5e121a25da2dbaa52b43e4be2fb2a9931386bbfa
0912390024c0b9d11c85a48a462f1296260b5c55
/app/src/main/java/com/demoapp/android/comics/Connect.java
40b5ede3626cda11f4b6402cdfd18527ae6a398f
[]
no_license
yasir095/prjcom
33c5c8b502953ee72d10e20d0f7935fd540af64d
7f41175aa5430f13f7dd60e7e39503f7a3564365
refs/heads/master
2020-07-17T12:31:04.868426
2017-07-17T22:22:32
2017-07-17T22:22:32
94,318,440
0
0
null
null
null
null
UTF-8
Java
false
false
834
java
package com.demoapp.android.comics; import com.demoapp.android.comics.helper.Utils; import java.util.HashMap; import java.util.Map; import javax.inject.Inject; /** * Created by yasirmahmood on 17/07/2017. */ public class Connect { @Inject Config config; @Inject Utils utils; private ComicApp app; public Connect(ComicApp app) { ((ComicApp) app).getComponent().inject(this); } private Map<String, String> generateDefaultParams() { String ts = utils.getCurrentTimestamp(); HashMap<String, String> params = new HashMap<>(); params.put("apikey", config.getPublicApiKey()); params.put("ts", ts); params.put("hash", utils.md5(ts+config.getPrivateApiKey()+config.getPublicApiKey())); params.put("limit", "100"); return params; } }
[ "yasir.se@gmail.com" ]
yasir.se@gmail.com
385542916850e2e917aa962b3c8abb488088d437
75dd6abb91d1ea8639acf97bb53ae1a44b73a91e
/src/main/java/com/xq/tmall/tmall05/dao/UserMapper.java
04589505cb15b007b64416a66eba5fbe1b77bd0a
[ "Apache-2.0" ]
permissive
ZGM-zgm/Tmali
068476444d8767fd55666f7ae335236b9075892d
a5304bc67166dea9c3f56c507319b86be13d136a
refs/heads/master
2022-12-14T23:41:25.531539
2020-09-15T03:28:00
2020-09-15T03:28:00
293,762,502
0
0
null
null
null
null
UTF-8
Java
false
false
767
java
package com.xq.tmall.tmall05.dao; import com.xq.tmall.tmall05.entity.User; import com.xq.tmall.tmall05.util.OrderUtil; import com.xq.tmall.tmall05.util.PageUtil; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface UserMapper { Integer insertOne(@Param("user") User user); Integer updateOne(@Param("user") User user); List<User> select(@Param("user") User user, @Param("orderUtil") OrderUtil orderUtil, @Param("pageUtil") PageUtil pageUtil); User selectOne(@Param("user_id") Integer user_id); User selectByLogin(@Param("user_name") String user_name, @Param("user_password") String user_password); Integer selectTotal(@Param("user") User user); }
[ "2396657348@qq.com" ]
2396657348@qq.com
917c5cd7d86e5e191c405f759dca8b6f249e407a
9fce01d889bf907b87b618c97c4b83cd3a69155d
/gy/javaprog/_OOTPJava1/Feladatmegoldasok/13Szelekciok/Udvariassag/Udvariassag1.java
d968ed34240ea85f3bed5b81c431d9a2cd07b5d7
[]
no_license
8emi95/elte-ik-pt1
c235dea0f11f90f96487f232ff9122497c86d4a6
45c24fe8436c29054b7a8ffecb2f55dbd3cb3f42
refs/heads/master
2020-04-29T09:16:14.310592
2019-03-16T19:48:50
2019-03-16T19:48:50
176,018,106
0
0
null
null
null
null
ISO-8859-2
Java
false
false
1,099
java
/* * Feladatmegoldások/13. fejezet * Udvariassag1.java * * Angster Erzsébet: OO tervezés és programozás, Java I. kötet * 2001.02.01. */ import extra.*; public class Udvariassag1 { public static void main(String[] args) { final int AKTEV = 2001; int korZsofi = AKTEV-Console.readInt("Zsófi születési éve: "); int korKati = AKTEV-Console.readInt("Kati születési éve: "); int korJuli = AKTEV-Console.readInt("Juli születési éve: "); if (korZsofi >= korKati && korKati >= korJuli) System.out.println("Zsófi, Kati, Juli"); else if (korZsofi >= korJuli && korJuli >= korKati) System.out.println("Zsófi, Juli, Kati"); else if (korKati >= korZsofi && korZsofi >= korJuli) System.out.println("Kati, Zsófi, Juli"); else if (korKati >= korJuli && korJuli >= korZsofi) System.out.println("Kati, Juli, Zsófi"); else if (korJuli >= korZsofi && korZsofi >= korKati) System.out.println("Juli, Zsófi, Kati"); else //(korJuli >= korKati && korKati >= korZsofi) System.out.println("Juli, Kati, Zsófi"); } }
[ "8emi95@inf.elte.hu" ]
8emi95@inf.elte.hu
49c139e98e3f49225e57b27d81da29b9292c8ab2
a048507c1807397329a558e84a5b0f69e66437d3
/boot/boot/src/main/java/com/cimr/boot/utils/IdGener.java
b174f5b16da308ecbad9d2da9cf85d6ef84d1f4a
[]
no_license
jlf1997/learngit
0ffd6fec5c6e9ad10ff14ff838396e1ef53a06f3
d6d7eba1c0bf6c76f49608dd2537594af2cd4ee9
refs/heads/master
2021-01-17T07:10:30.004555
2018-11-08T09:15:13
2018-11-08T09:15:13
59,822,610
1
0
null
null
null
null
UTF-8
Java
false
false
1,112
java
package com.cimr.boot.utils; public class IdGener { private SnowflakeIdWorker idForRejectOrder; private SnowflakeIdWorker idForOrder; private SnowflakeIdWorker id; private IdGener(){ idForOrder = new SnowflakeIdWorker(0, 0); idForRejectOrder = new SnowflakeIdWorker(1, 0); id = new SnowflakeIdWorker(2, 0); } public static IdGener getInstance(){ return Singleton.INSTANCE.getInstance(); } private static enum Singleton{ INSTANCE; private IdGener singleton; //JVM会保证此方法绝对只调用一次 private Singleton(){ singleton = new IdGener(); } public IdGener getInstance(){ return singleton; } } /** * 获取订单编号 * @return */ public long getOrderId() { return idForOrder.nextId(); } /** * 获取退货单号 * @return */ public long getRejectOrderId() { return idForRejectOrder.nextId(); } public long getNormalId() { return id.nextId(); } }
[ "675866753@qq.com" ]
675866753@qq.com
3912c9bb97e52ed8adb77a185f423ed24d0f3ab7
92f377ccf3e18a03e6fea09bf81b813e4c6f0cdd
/OpenWeatherMap/src/main/java/com/example/demo/service/CityInterface.java
9303f7fc37763247a5ee0759d5a6245d454f7508
[]
no_license
milosboskovic1991/OpenWeatherMap
c531049f29b03a06092abaf2bf0a7760b608d8ad
d55d6e427d66604da047e0d800999bb405d1ae3b
refs/heads/master
2020-04-28T21:57:12.444565
2019-03-14T17:48:06
2019-03-14T17:48:06
175,600,176
0
0
null
null
null
null
UTF-8
Java
false
false
357
java
package com.example.demo.service; import java.util.List; import com.example.demo.entity.City; import com.example.demo.entity.dto.CityDto; public interface CityInterface { public List<CityDto> findAll(); public City getCityByName(String name); public List<City> getTemperatureForAllCities(List<City> cities); public void updateCityTemperature(); }
[ "milosboskovic1991@yahoo.com" ]
milosboskovic1991@yahoo.com
a16796f894dd12c2472f64d7d6be29a48a201d35
cbee4fba2eb0794f679de498a69e340f80f58de2
/app/src/main/java/com/gg/habittrain/SerialNumberHelper.java
e63898a08aa59660719aff97ff398e3869f8bdbd
[]
no_license
Andayoung/HabitTrain
335b3407661e45507c9d00357de21e474449f85d
79b9701722550b56b00e13471858482adfa5155d
refs/heads/master
2021-01-01T15:37:35.315713
2017-07-19T01:06:25
2017-07-19T01:06:25
96,086,801
0
0
null
null
null
null
UTF-8
Java
false
false
2,449
java
package com.gg.habittrain; import android.content.Context; import android.os.Environment; import android.util.Log; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; /** * Created by Administrator on 2017/6/22 0022. */ public class SerialNumberHelper { private Context context; public SerialNumberHelper() { } public SerialNumberHelper(Context context) { super(); this.context = context; } public void save2File(String text) { try { File path= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); if(!path.mkdirs()) { Log.e("licence", "Directory not created"); } File file=new File(path,"my.uu"); FileOutputStream output = new FileOutputStream(file); output.write(text.getBytes("utf-8")); output.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public String read4File() { StringBuilder sb = new StringBuilder(""); try { File path=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); if(!path.mkdirs()) { Log.e("licence", "Directory not created"); } File file=new File(path, "my.uu"); FileInputStream input = new FileInputStream(file); byte[] temp = new byte[1024]; int len = 0; while ((len = input.read(temp)) > 0) { sb.append(new String(temp, 0, len)); } input.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } public void deleteFile(){ File path= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); if(!path.mkdirs()) { Log.e("licence", "Directory not created"); } File file=new File(path, "my.uu"); if(file.isFile()&&file.exists()){ file.delete(); } } }
[ "zhoup324@163.com" ]
zhoup324@163.com
56d514349bd610e23c6b825f47481327d5d7740c
a491e10b5d37084a704678a7dc3cf72c66e221fc
/jpa basic/practice6/src/main/java/hello/jpa/domain/item/Book.java
01920a347c76e30c8a249a60179865cb47fa1452
[]
no_license
YeomJaeSeon/jpa
4a784210cdb78e0b71e4b591eb0ab29dceed0317
cc5747d539c3ee19293cfd43340157764fcf241c
refs/heads/master
2023-06-17T06:14:28.618269
2021-07-19T07:40:42
2021-07-19T07:40:42
371,958,152
0
0
null
null
null
null
UTF-8
Java
false
false
434
java
package hello.jpa.domain.item; import javax.persistence.Entity; @Entity public class Book extends Item{ private String author; private String isbn; public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } }
[ "a89541457@gmail.com" ]
a89541457@gmail.com
69be543911cc4fd86deff47cdb6ab662583e878a
b8958890c54183b82100fd5d91229ab952c63dae
/DoctorsSprBoot/src/main/java/org/corona/DoctorDao.java
87e7fb396fd0820ed9c4e56ea56a2fe33215b1c1
[]
no_license
darkknight77/eclipse-workspace
1250ddf1d0375c9139a961de4bcf56714646e56a
9ddf02b4a753eb9f1e7d3418249d11cbbb8ba933
refs/heads/master
2022-12-24T14:46:44.814828
2020-09-21T15:53:54
2020-09-21T15:53:54
238,225,943
0
0
null
2022-12-16T05:24:56
2020-02-04T14:29:35
JavaScript
UTF-8
Java
false
false
4,352
java
package org.corona; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManagerFactory; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.jboss.logging.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @Repository @Transactional public class DoctorDao { private static final Logger logger = Logger.getLogger(DoctorDao.class); @Autowired private EntityManagerFactory entityManagerFactory; @SuppressWarnings("unchecked") public List<DoctorModel> getDoctors() { List<DoctorModel> doctors = new ArrayList<DoctorModel>(); Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession(); /* * Session session = null; try { session = sessionFactory.openSession(); * session.beginTransaction(); doctors = * session.createQuery("From Doctors").list(); * System.out.println("Doctors are : " + doctors); * * } catch (Exception e) {} return doctors; */ return session.createQuery("FROM Doctors").list(); } @SuppressWarnings("unchecked") public List<DoctorModel> searchDoctors(String doctorName) { List<DoctorModel> doctorsList = new ArrayList<DoctorModel>(); String query = "SELECT d.* FROM Doctors d WHERE d.Dname like '%" + doctorName + "%' "; Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession(); List<Object[]> doctorObjects = session.createSQLQuery(query).list(); for (Object[] object : doctorObjects) { int id = ((BigInteger) object[0]).intValue(); String name = (String) object[1]; float salary = (float) object[2]; String specialization = (String) object[3]; DoctorModel doctor = new DoctorModel(id, name, salary, specialization); System.out.println(doctor); doctorsList.add(doctor); } logger.info(doctorsList); /* * Session session = null; try { * * session = sessionFactory.openSession(); session.beginTransaction(); String * query = "SELECT d.* FROM Doctors d WHERE d.Dname like '%" + doctorName + * "%' "; List<Object[]> doctorObjects = session.createSQLQuery(query).list(); * * for (Object[] object : doctorObjects) { * * int id = ((BigInteger) object[0]).intValue(); String name = (String) * object[1]; float salary = (float) object[2]; String specialization = (String) * object[3]; * * DoctorModel doctor = new DoctorModel(id, name, salary, specialization); * System.out.println(doctor); doctorsList.add(doctor); } * * logger.info(doctorsList); * * } catch (Exception e) { System.out.println("dao search doctors error"); * e.printStackTrace(); } * * return doctorsList; */ return doctorsList; } public DoctorModel getDoctor(int id) { DoctorModel doctor = new DoctorModel(); Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession(); doctor = (DoctorModel) session.get(DoctorModel.class, id); /* * Session session = null; try { * * session = sessionFactory.openSession(); session.beginTransaction(); doctor = * (DoctorModel) session.get(DoctorModel.class, id); } catch (Exception e) { * e.printStackTrace(); } * */ return doctor; } public void updateDoctor(DoctorModel doctor) { /* * Session session = null; * * try { session = sessionFactory.openSession(); session.beginTransaction(); * session.saveOrUpdate(doctor); session.getTransaction().commit(); } catch * (Exception e) { e.printStackTrace(); } */ Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession(); session.beginTransaction(); session.saveOrUpdate(doctor); session.getTransaction().commit(); } public void deleteDoctor(int id) { /* * Session session = null; try { session = sessionFactory.openSession(); * session.beginTransaction(); session.delete(doctor); * session.getTransaction().commit(); } catch (Exception e) { * e.printStackTrace(); } */ Session session = entityManagerFactory.unwrap(SessionFactory.class).openSession(); session.beginTransaction(); DoctorModel doctor=session.get(DoctorModel.class,id); session.delete(doctor); session.getTransaction().commit(); } }
[ "shaiklatheefmrf98@gmail.com" ]
shaiklatheefmrf98@gmail.com
7e594ea4ab997cfc5c7ae9f31dc2b9e65a41d997
c03b0bf06f5dd0236b0ffbc655bb317cdac265ea
/EmpLeaveMngmnt3/src/com/manager/ManagerLogin.java
dc7b841fbead503f93999a4c04ecbb26ee53a482
[]
no_license
mjay118/javatrainingg
de4a1d97f8cc0710b3ef9092592cc48a83612bc2
c4450ef020c12dfa717419afaf85e189784b36af
refs/heads/main
2023-06-22T00:38:50.335832
2021-02-10T19:26:15
2021-02-10T19:26:15
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,092
java
package com.manager; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletConfig; 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 javax.servlet.http.HttpSession; public class ManagerLogin extends HttpServlet { Connection con=null; PreparedStatement ps=null; public void init(ServletConfig config) { try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } String url = "jdbc:mysql://localhost:3306/empMngmnt"; String uname = "root"; String pass = "1234"; try { con = DriverManager.getConnection(url, uname, pass); System.out.println(con); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String email=request.getParameter("email"); String password=request.getParameter("password"); String sql="select * from manager where email=? and password=?"; try { ps=con.prepareStatement(sql); ps.setString(1, email); ps.setString(2, password); HttpSession hs=request.getSession(); ResultSet rs = ps.executeQuery(); if(rs.next()) { hs.setAttribute("semail", email); hs.setAttribute("id", rs.getInt(1)); hs.setAttribute("name", rs.getString(2)); response.sendRedirect("./manager_home.html?msg=Login Suceessful"); } else { response.sendRedirect("./manager_login.html?msg=Login UnSuceessful"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
[ "mrityunjaysinha0118@gmail.com" ]
mrityunjaysinha0118@gmail.com
41c340e9ea9343f42fd4684eb48a8a3d72810cfd
8126110d26aed96860e8b3694725faff02cea1dc
/MyWorld.java
059ddc2b44a6008a6d7c8f62fae1c59f7d97bccb
[]
no_license
buzhouke/mine-sweeping
d127491b1b6e9828b91d11148903f5a4bee30121
44edcba6099983c78ca80049edb7aa02be84a0b6
refs/heads/master
2022-11-23T07:17:51.491723
2020-07-27T13:54:05
2020-07-27T13:54:05
279,882,266
0
0
null
2020-07-15T14:02:19
2020-07-15T13:54:56
null
UTF-8
Java
false
false
1,554
java
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.util.*; /** * Write a description of class MyWorld here. * * @author (your name) * @version (a version number or a date) */ public class MyWorld extends World { /** * Constructor for objects of class MyWorld. * */ public static Thunder[][] MyBlock = new Thunder[30][20]; public static Easy easy = new Easy(false,50); public static Medium medium = new Medium(false,100); public static Hard hard = new Hard(false,150); public MyWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(800, 550, 1); setBackground("Background.png"); //System.out.println("win!!"); long start = System.currentTimeMillis(); for(int i = 0;i < 30;i++){ for(int j = 0;j < 20;j++){ Thunder a = new Thunder(i,j,false); addObject(a,i*25+38,j*25+38); MyBlock[i][j] = a; } } addObject(easy,200,230); addObject(medium,400,230); addObject(hard,600,230); addObject(new Flag(),15,535); addObject(new Help(),785,535); easy.isStarted = false; hard.isStarted = false; medium.isStarted = false; easy.getIt = false; medium.getIt = false; hard.getIt = false; } static Thunder[][] getClicked() { return MyBlock; } }
[ "1781738565@qq.com" ]
1781738565@qq.com
e7efad81032445f208ee3f2c1a1635f77bef69c1
48e835e6f176a8ac9ae3ca718e8922891f1e5a18
/benchmark/training/org/apache/hadoop/hdfs/TestDFSShell.java
9f0cff116fc63f26f965a29d58037701b220fdbd
[]
no_license
STAMP-project/dspot-experiments
f2c7a639d6616ae0adfc491b4cb4eefcb83d04e5
121487e65cdce6988081b67f21bbc6731354a47f
refs/heads/master
2023-02-07T14:40:12.919811
2019-11-06T07:17:09
2019-11-06T07:17:09
75,710,758
14
19
null
2023-01-26T23:57:41
2016-12-06T08:27:42
null
UTF-8
Java
false
false
129,329
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 DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_KEY; import DFSConfigKeys.DFS_PERMISSIONS_ENABLED_KEY; import DFSConfigKeys.DFS_PERMISSIONS_SUPERUSERGROUP_KEY; import FSDirectory.DOT_INODES_STRING; import FSDirectory.DOT_RESERVED_STRING; import FSInputChecker.LOG; import HdfsClientConfigKeys.DFS_NAMENODE_RPC_PORT_DEFAULT; import HdfsClientConfigKeys.Retry.WINDOW_BASE_KEY; import com.google.common.base.Supplier; import com.google.common.collect.Lists; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.security.Permission; import java.security.PrivilegedExceptionAction; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.TimeZone; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.lang3.RandomStringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.DistributedFileSystem; import org.apache.hadoop.fs.permission.AclEntry; import org.apache.hadoop.fs.permission.AclEntryScope; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.hdfs.server.datanode.FsDatasetTestUtils; import org.apache.hadoop.hdfs.server.namenode.AclTestHelpers; import org.apache.hadoop.hdfs.tools.DFSAdmin; import org.apache.hadoop.net.ServerSocketUtil; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.test.GenericTestUtils; import org.apache.hadoop.test.PathUtils; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.util.Time; import org.apache.hadoop.util.ToolRunner; import org.apache.log4j.Level; import org.hamcrest.CoreMatchers; import org.hamcrest.core.StringContains; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static java.lang.Thread.State.TIMED_WAITING; /** * This class tests commands from DFSShell. */ public class TestDFSShell { private static final Logger LOG = LoggerFactory.getLogger(TestDFSShell.class); private static final AtomicInteger counter = new AtomicInteger(); private final int SUCCESS = 0; private final int ERROR = 1; static final String TEST_ROOT_DIR = PathUtils.getTestDirName(TestDFSShell.class); private static final String RAW_A1 = "raw.a1"; private static final String TRUSTED_A1 = "trusted.a1"; private static final String USER_A1 = "user.a1"; private static final byte[] RAW_A1_VALUE = new byte[]{ 50, 50, 50 }; private static final byte[] TRUSTED_A1_VALUE = new byte[]{ 49, 49, 49 }; private static final byte[] USER_A1_VALUE = new byte[]{ 49, 50, 51 }; private static final int BLOCK_SIZE = 1024; private static MiniDFSCluster miniCluster; private static DistributedFileSystem dfs; @Rule public Timeout globalTimeout = new Timeout((30 * 1000));// 30s @Test(timeout = 30000) public void testZeroSizeFile() throws IOException { // create a zero size file final File f1 = new File(TestDFSShell.TEST_ROOT_DIR, "f1"); Assert.assertTrue((!(f1.exists()))); Assert.assertTrue(f1.createNewFile()); Assert.assertTrue(f1.exists()); Assert.assertTrue(f1.isFile()); Assert.assertEquals(0L, f1.length()); // copy to remote final Path root = TestDFSShell.mkdir(TestDFSShell.dfs, new Path("/testZeroSizeFile/zeroSizeFile")); final Path remotef = new Path(root, "dst"); TestDFSShell.show(((("copy local " + f1) + " to remote ") + remotef)); TestDFSShell.dfs.copyFromLocalFile(false, false, new Path(f1.getPath()), remotef); // getBlockSize() should not throw exception TestDFSShell.show(("Block size = " + (TestDFSShell.dfs.getFileStatus(remotef).getBlockSize()))); // copy back final File f2 = new File(TestDFSShell.TEST_ROOT_DIR, "f2"); Assert.assertTrue((!(f2.exists()))); TestDFSShell.dfs.copyToLocalFile(remotef, new Path(f2.getPath())); Assert.assertTrue(f2.exists()); Assert.assertTrue(f2.isFile()); Assert.assertEquals(0L, f2.length()); f1.delete(); f2.delete(); } @Test(timeout = 30000) public void testRecursiveRm() throws IOException { final Path parent = new Path("/testRecursiveRm", "parent"); final Path child = new Path(parent, "child"); TestDFSShell.dfs.mkdirs(child); try { TestDFSShell.dfs.delete(parent, false); Assert.fail("Should have failed because dir is not empty"); } catch (IOException e) { // should have thrown an exception } TestDFSShell.dfs.delete(parent, true); Assert.assertFalse(TestDFSShell.dfs.exists(parent)); } @Test(timeout = 30000) public void testDu() throws IOException { int replication = 2; PrintStream psBackup = System.out; ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream psOut = new PrintStream(out); System.setOut(psOut); FsShell shell = new FsShell(TestDFSShell.dfs.getConf()); try { final Path myPath = new Path("/testDu", "dir"); Assert.assertTrue(TestDFSShell.dfs.mkdirs(myPath)); Assert.assertTrue(TestDFSShell.dfs.exists(myPath)); final Path myFile = new Path(myPath, "file"); TestDFSShell.writeFile(TestDFSShell.dfs, myFile); Assert.assertTrue(TestDFSShell.dfs.exists(myFile)); final Path myFile2 = new Path(myPath, "file2"); TestDFSShell.writeFile(TestDFSShell.dfs, myFile2); Assert.assertTrue(TestDFSShell.dfs.exists(myFile2)); Long myFileLength = TestDFSShell.dfs.getFileStatus(myFile).getLen(); Long myFileDiskUsed = myFileLength * replication; Long myFile2Length = TestDFSShell.dfs.getFileStatus(myFile2).getLen(); Long myFile2DiskUsed = myFile2Length * replication; String[] args = new String[2]; args[0] = "-du"; args[1] = myPath.toString(); int val = -1; try { val = shell.run(args); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertTrue((val == 0)); String returnString = out.toString(); out.reset(); // Check if size matches as expected Assert.assertThat(returnString, StringContains.containsString(myFileLength.toString())); Assert.assertThat(returnString, StringContains.containsString(myFileDiskUsed.toString())); Assert.assertThat(returnString, StringContains.containsString(myFile2Length.toString())); Assert.assertThat(returnString, StringContains.containsString(myFile2DiskUsed.toString())); // Check that -du -s reports the state of the snapshot String snapshotName = "ss1"; Path snapshotPath = new Path(myPath, (".snapshot/" + snapshotName)); TestDFSShell.dfs.allowSnapshot(myPath); Assert.assertThat(TestDFSShell.dfs.createSnapshot(myPath, snapshotName), CoreMatchers.is(snapshotPath)); Assert.assertThat(TestDFSShell.dfs.delete(myFile, false), CoreMatchers.is(true)); Assert.assertThat(TestDFSShell.dfs.exists(myFile), CoreMatchers.is(false)); args = new String[3]; args[0] = "-du"; args[1] = "-s"; args[2] = snapshotPath.toString(); val = -1; try { val = shell.run(args); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertThat(val, CoreMatchers.is(0)); returnString = out.toString(); out.reset(); Long combinedLength = myFileLength + myFile2Length; Long combinedDiskUsed = myFileDiskUsed + myFile2DiskUsed; Assert.assertThat(returnString, StringContains.containsString(combinedLength.toString())); Assert.assertThat(returnString, StringContains.containsString(combinedDiskUsed.toString())); // Check if output is rendered properly with multiple input paths final Path myFile3 = new Path(myPath, "file3"); TestDFSShell.writeByte(TestDFSShell.dfs, myFile3); Assert.assertTrue(TestDFSShell.dfs.exists(myFile3)); args = new String[3]; args[0] = "-du"; args[1] = myFile3.toString(); args[2] = myFile2.toString(); val = -1; try { val = shell.run(args); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals("Return code should be 0.", 0, val); returnString = out.toString(); out.reset(); Assert.assertTrue(returnString.contains(("1 2 " + (myFile3.toString())))); Assert.assertTrue(returnString.contains(("25 50 " + (myFile2.toString())))); } finally { System.setOut(psBackup); } } @Test(timeout = 180000) public void testDuSnapshots() throws IOException { final int replication = 2; final PrintStream psBackup = System.out; final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream psOut = new PrintStream(out); final FsShell shell = new FsShell(TestDFSShell.dfs.getConf()); try { System.setOut(psOut); final Path parent = new Path("/testDuSnapshots"); final Path dir = new Path(parent, "dir"); TestDFSShell.mkdir(TestDFSShell.dfs, dir); final Path file = new Path(dir, "file"); TestDFSShell.writeFile(TestDFSShell.dfs, file); final Path file2 = new Path(dir, "file2"); TestDFSShell.writeFile(TestDFSShell.dfs, file2); final Long fileLength = TestDFSShell.dfs.getFileStatus(file).getLen(); final Long fileDiskUsed = fileLength * replication; final Long file2Length = TestDFSShell.dfs.getFileStatus(file2).getLen(); final Long file2DiskUsed = file2Length * replication; /* Construct dir as follows: /test/dir/file <- this will later be deleted after snapshot taken. /test/dir/newfile <- this will be created after snapshot taken. /test/dir/file2 Snapshot enabled on /test */ // test -du on /test/dir int ret = -1; try { ret = shell.run(new String[]{ "-du", dir.toString() }); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(0, ret); String returnString = out.toString(); TestDFSShell.LOG.info(("-du return is:\n" + returnString)); // Check if size matches as expected Assert.assertTrue(returnString.contains(fileLength.toString())); Assert.assertTrue(returnString.contains(fileDiskUsed.toString())); Assert.assertTrue(returnString.contains(file2Length.toString())); Assert.assertTrue(returnString.contains(file2DiskUsed.toString())); out.reset(); // take a snapshot, then remove file and add newFile final String snapshotName = "ss1"; final Path snapshotPath = new Path(parent, (".snapshot/" + snapshotName)); TestDFSShell.dfs.allowSnapshot(parent); Assert.assertThat(TestDFSShell.dfs.createSnapshot(parent, snapshotName), CoreMatchers.is(snapshotPath)); TestDFSShell.rmr(TestDFSShell.dfs, file); final Path newFile = new Path(dir, "newfile"); TestDFSShell.writeFile(TestDFSShell.dfs, newFile); final Long newFileLength = TestDFSShell.dfs.getFileStatus(newFile).getLen(); final Long newFileDiskUsed = newFileLength * replication; // test -du -s on /test ret = -1; try { ret = shell.run(new String[]{ "-du", "-s", parent.toString() }); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(0, ret); returnString = out.toString(); TestDFSShell.LOG.info(("-du -s return is:\n" + returnString)); Long combinedLength = (fileLength + file2Length) + newFileLength; Long combinedDiskUsed = (fileDiskUsed + file2DiskUsed) + newFileDiskUsed; Assert.assertTrue(returnString.contains(combinedLength.toString())); Assert.assertTrue(returnString.contains(combinedDiskUsed.toString())); out.reset(); // test -du on /test ret = -1; try { ret = shell.run(new String[]{ "-du", parent.toString() }); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(0, ret); returnString = out.toString(); TestDFSShell.LOG.info(("-du return is:\n" + returnString)); Assert.assertTrue(returnString.contains(combinedLength.toString())); Assert.assertTrue(returnString.contains(combinedDiskUsed.toString())); out.reset(); // test -du -s -x on /test ret = -1; try { ret = shell.run(new String[]{ "-du", "-s", "-x", parent.toString() }); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(0, ret); returnString = out.toString(); TestDFSShell.LOG.info(("-du -s -x return is:\n" + returnString)); Long exludeSnapshotLength = file2Length + newFileLength; Long excludeSnapshotDiskUsed = file2DiskUsed + newFileDiskUsed; Assert.assertTrue(returnString.contains(exludeSnapshotLength.toString())); Assert.assertTrue(returnString.contains(excludeSnapshotDiskUsed.toString())); out.reset(); // test -du -x on /test ret = -1; try { ret = shell.run(new String[]{ "-du", "-x", parent.toString() }); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(0, ret); returnString = out.toString(); TestDFSShell.LOG.info(("-du -x return is:\n" + returnString)); Assert.assertTrue(returnString.contains(exludeSnapshotLength.toString())); Assert.assertTrue(returnString.contains(excludeSnapshotDiskUsed.toString())); out.reset(); } finally { System.setOut(psBackup); } } @Test(timeout = 180000) public void testCountSnapshots() throws IOException { final PrintStream psBackup = System.out; final ByteArrayOutputStream out = new ByteArrayOutputStream(); final PrintStream psOut = new PrintStream(out); System.setOut(psOut); final FsShell shell = new FsShell(TestDFSShell.dfs.getConf()); try { final Path parent = new Path("/testCountSnapshots"); final Path dir = new Path(parent, "dir"); TestDFSShell.mkdir(TestDFSShell.dfs, dir); final Path file = new Path(dir, "file"); TestDFSShell.writeFile(TestDFSShell.dfs, file); final Path file2 = new Path(dir, "file2"); TestDFSShell.writeFile(TestDFSShell.dfs, file2); final long fileLength = TestDFSShell.dfs.getFileStatus(file).getLen(); final long file2Length = TestDFSShell.dfs.getFileStatus(file2).getLen(); final Path dir2 = new Path(parent, "dir2"); TestDFSShell.mkdir(TestDFSShell.dfs, dir2); /* Construct dir as follows: /test/dir/file <- this will later be deleted after snapshot taken. /test/dir/newfile <- this will be created after snapshot taken. /test/dir/file2 /test/dir2 <- this will later be deleted after snapshot taken. Snapshot enabled on /test */ // take a snapshot // then create /test/dir/newfile and remove /test/dir/file, /test/dir2 final String snapshotName = "s1"; final Path snapshotPath = new Path(parent, (".snapshot/" + snapshotName)); TestDFSShell.dfs.allowSnapshot(parent); Assert.assertThat(TestDFSShell.dfs.createSnapshot(parent, snapshotName), CoreMatchers.is(snapshotPath)); TestDFSShell.rmr(TestDFSShell.dfs, file); TestDFSShell.rmr(TestDFSShell.dfs, dir2); final Path newFile = new Path(dir, "new file"); TestDFSShell.writeFile(TestDFSShell.dfs, newFile); final Long newFileLength = TestDFSShell.dfs.getFileStatus(newFile).getLen(); // test -count on /test. Include header for easier debugging. int val = -1; try { val = shell.run(new String[]{ "-count", "-v", parent.toString() }); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(0, val); String returnString = out.toString(); TestDFSShell.LOG.info(("-count return is:\n" + returnString)); Scanner in = new Scanner(returnString); in.nextLine(); Assert.assertEquals(3, in.nextLong());// DIR_COUNT Assert.assertEquals(3, in.nextLong());// FILE_COUNT Assert.assertEquals(((fileLength + file2Length) + newFileLength), in.nextLong());// CONTENT_SIZE out.reset(); // test -count -x on /test. Include header for easier debugging. val = -1; try { val = shell.run(new String[]{ "-count", "-x", "-v", parent.toString() }); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(0, val); returnString = out.toString(); TestDFSShell.LOG.info(("-count -x return is:\n" + returnString)); in = new Scanner(returnString); in.nextLine(); Assert.assertEquals(2, in.nextLong());// DIR_COUNT Assert.assertEquals(2, in.nextLong());// FILE_COUNT Assert.assertEquals((file2Length + newFileLength), in.nextLong());// CONTENT_SIZE out.reset(); } finally { System.setOut(psBackup); } } @Test(timeout = 30000) public void testPut() throws IOException { // remove left over crc files: new File(TestDFSShell.TEST_ROOT_DIR, ".f1.crc").delete(); new File(TestDFSShell.TEST_ROOT_DIR, ".f2.crc").delete(); final File f1 = TestDFSShell.createLocalFile(new File(TestDFSShell.TEST_ROOT_DIR, "f1")); final File f2 = TestDFSShell.createLocalFile(new File(TestDFSShell.TEST_ROOT_DIR, "f2")); final Path root = TestDFSShell.mkdir(TestDFSShell.dfs, new Path("/testPut")); final Path dst = new Path(root, "dst"); TestDFSShell.show("begin"); final Thread copy2ndFileThread = new Thread() { @Override public void run() { try { TestDFSShell.show(((("copy local " + f2) + " to remote ") + dst)); TestDFSShell.dfs.copyFromLocalFile(false, false, new Path(f2.getPath()), dst); } catch (IOException ioe) { TestDFSShell.show(("good " + (StringUtils.stringifyException(ioe)))); return; } // should not be here, must got IOException Assert.assertTrue(false); } }; // use SecurityManager to pause the copying of f1 and begin copying f2 SecurityManager sm = System.getSecurityManager(); System.out.println(("SecurityManager = " + sm)); System.setSecurityManager(new SecurityManager() { private boolean firstTime = true; @Override public void checkPermission(Permission perm) { if (firstTime) { Thread t = Thread.currentThread(); if (!(t.toString().contains("DataNode"))) { String s = "" + (Arrays.asList(t.getStackTrace())); if (s.contains("FileUtil.copyContent")) { // pause at FileUtil.copyContent firstTime = false; copy2ndFileThread.start(); try { Thread.sleep(5000); } catch (InterruptedException e) { } } } } } }); TestDFSShell.show(((("copy local " + f1) + " to remote ") + dst)); TestDFSShell.dfs.copyFromLocalFile(false, false, new Path(f1.getPath()), dst); TestDFSShell.show("done"); try { copy2ndFileThread.join(); } catch (InterruptedException e) { } System.setSecurityManager(sm); // copy multiple files to destination directory final Path destmultiple = TestDFSShell.mkdir(TestDFSShell.dfs, new Path(root, "putmultiple")); Path[] srcs = new Path[2]; srcs[0] = new Path(f1.getPath()); srcs[1] = new Path(f2.getPath()); TestDFSShell.dfs.copyFromLocalFile(false, false, srcs, destmultiple); srcs[0] = new Path(destmultiple, "f1"); srcs[1] = new Path(destmultiple, "f2"); Assert.assertTrue(TestDFSShell.dfs.exists(srcs[0])); Assert.assertTrue(TestDFSShell.dfs.exists(srcs[1])); // move multiple files to destination directory final Path destmultiple2 = TestDFSShell.mkdir(TestDFSShell.dfs, new Path(root, "movemultiple")); srcs[0] = new Path(f1.getPath()); srcs[1] = new Path(f2.getPath()); TestDFSShell.dfs.moveFromLocalFile(srcs, destmultiple2); Assert.assertFalse(f1.exists()); Assert.assertFalse(f2.exists()); srcs[0] = new Path(destmultiple2, "f1"); srcs[1] = new Path(destmultiple2, "f2"); Assert.assertTrue(TestDFSShell.dfs.exists(srcs[0])); Assert.assertTrue(TestDFSShell.dfs.exists(srcs[1])); f1.delete(); f2.delete(); } /** * check command error outputs and exit statuses. */ @Test(timeout = 30000) public void testErrOutPut() throws Exception { PrintStream bak = null; try { Path root = new Path("/nonexistentfile"); bak = System.err; ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream tmp = new PrintStream(out); System.setErr(tmp); String[] argv = new String[2]; argv[0] = "-cat"; argv[1] = root.toUri().getPath(); int ret = ToolRunner.run(new FsShell(), argv); Assert.assertEquals(" -cat returned 1 ", 1, ret); String returned = out.toString(); Assert.assertTrue("cat does not print exceptions ", ((returned.lastIndexOf("Exception")) == (-1))); out.reset(); argv[0] = "-rm"; argv[1] = root.toString(); FsShell shell = new FsShell(TestDFSShell.dfs.getConf()); ret = ToolRunner.run(shell, argv); Assert.assertEquals(" -rm returned 1 ", 1, ret); returned = out.toString(); out.reset(); Assert.assertTrue("rm prints reasonable error ", ((returned.lastIndexOf("No such file or directory")) != (-1))); argv[0] = "-rmr"; argv[1] = root.toString(); ret = ToolRunner.run(shell, argv); Assert.assertEquals(" -rmr returned 1", 1, ret); returned = out.toString(); Assert.assertTrue("rmr prints reasonable error ", ((returned.lastIndexOf("No such file or directory")) != (-1))); out.reset(); argv[0] = "-du"; argv[1] = "/nonexistentfile"; ret = ToolRunner.run(shell, argv); returned = out.toString(); Assert.assertTrue(" -du prints reasonable error ", ((returned.lastIndexOf("No such file or directory")) != (-1))); out.reset(); argv[0] = "-dus"; argv[1] = "/nonexistentfile"; ret = ToolRunner.run(shell, argv); returned = out.toString(); Assert.assertTrue(" -dus prints reasonable error", ((returned.lastIndexOf("No such file or directory")) != (-1))); out.reset(); argv[0] = "-ls"; argv[1] = "/nonexistenfile"; ret = ToolRunner.run(shell, argv); returned = out.toString(); Assert.assertTrue(" -ls does not return Found 0 items", ((returned.lastIndexOf("Found 0")) == (-1))); out.reset(); argv[0] = "-ls"; argv[1] = "/nonexistentfile"; ret = ToolRunner.run(shell, argv); Assert.assertEquals(" -lsr should fail ", 1, ret); out.reset(); TestDFSShell.dfs.mkdirs(new Path("/testdir")); argv[0] = "-ls"; argv[1] = "/testdir"; ret = ToolRunner.run(shell, argv); returned = out.toString(); Assert.assertTrue(" -ls does not print out anything ", ((returned.lastIndexOf("Found 0")) == (-1))); out.reset(); argv[0] = "-ls"; argv[1] = "/user/nonxistant/*"; ret = ToolRunner.run(shell, argv); Assert.assertEquals(" -ls on nonexistent glob returns 1", 1, ret); out.reset(); argv[0] = "-mkdir"; argv[1] = "/testdir"; ret = ToolRunner.run(shell, argv); returned = out.toString(); Assert.assertEquals(" -mkdir returned 1 ", 1, ret); Assert.assertTrue(" -mkdir returned File exists", ((returned.lastIndexOf("File exists")) != (-1))); Path testFile = new Path("/testfile"); OutputStream outtmp = TestDFSShell.dfs.create(testFile); outtmp.write(testFile.toString().getBytes()); outtmp.close(); out.reset(); argv[0] = "-mkdir"; argv[1] = "/testfile"; ret = ToolRunner.run(shell, argv); returned = out.toString(); Assert.assertEquals(" -mkdir returned 1", 1, ret); Assert.assertTrue(" -mkdir returned this is a file ", ((returned.lastIndexOf("not a directory")) != (-1))); out.reset(); argv[0] = "-mkdir"; argv[1] = "/testParent/testChild"; ret = ToolRunner.run(shell, argv); returned = out.toString(); Assert.assertEquals(" -mkdir returned 1", 1, ret); Assert.assertTrue(" -mkdir returned there is No file or directory but has testChild in the path", ((returned.lastIndexOf("testChild")) == (-1))); out.reset(); argv = new String[3]; argv[0] = "-mv"; argv[1] = "/testfile"; argv[2] = "/no-such-dir/file"; ret = ToolRunner.run(shell, argv); Assert.assertEquals("mv failed to rename", 1, ret); out.reset(); argv = new String[3]; argv[0] = "-mv"; argv[1] = "/testfile"; argv[2] = "/testfiletest"; ret = ToolRunner.run(shell, argv); returned = out.toString(); Assert.assertTrue("no output from rename", ((returned.lastIndexOf("Renamed")) == (-1))); out.reset(); argv[0] = "-mv"; argv[1] = "/testfile"; argv[2] = "/testfiletmp"; ret = ToolRunner.run(shell, argv); returned = out.toString(); Assert.assertTrue(" unix like output", ((returned.lastIndexOf("No such file or")) != (-1))); out.reset(); argv = new String[1]; argv[0] = "-du"; TestDFSShell.dfs.mkdirs(TestDFSShell.dfs.getHomeDirectory()); ret = ToolRunner.run(shell, argv); returned = out.toString(); Assert.assertEquals(" no error ", 0, ret); Assert.assertTrue("empty path specified", ((returned.lastIndexOf("empty string")) == (-1))); out.reset(); argv = new String[3]; argv[0] = "-test"; argv[1] = "-d"; argv[2] = "/no/such/dir"; ret = ToolRunner.run(shell, argv); returned = out.toString(); Assert.assertEquals(" -test -d wrong result ", 1, ret); Assert.assertTrue(returned.isEmpty()); } finally { if (bak != null) { System.setErr(bak); } } } @Test public void testMoveWithTargetPortEmpty() throws Exception { Configuration conf = new HdfsConfiguration(); MiniDFSCluster cluster = null; try { cluster = new MiniDFSCluster.Builder(conf).format(true).numDataNodes(2).nameNodePort(ServerSocketUtil.waitForPort(DFS_NAMENODE_RPC_PORT_DEFAULT, 60)).waitSafeMode(true).build(); FileSystem srcFs = cluster.getFileSystem(); FsShell shell = new FsShell(); shell.setConf(conf); String[] argv = new String[2]; argv[0] = "-mkdir"; argv[1] = "/testfile"; ToolRunner.run(shell, argv); argv = new String[3]; argv[0] = "-mv"; argv[1] = (getUri()) + "/testfile"; argv[2] = ("hdfs://" + (getUri().getHost())) + "/testfile2"; int ret = ToolRunner.run(shell, argv); Assert.assertEquals("mv should have succeeded", 0, ret); } finally { if (cluster != null) { cluster.shutdown(); } } } @Test(timeout = 30000) public void testURIPaths() throws Exception { Configuration srcConf = new HdfsConfiguration(); Configuration dstConf = new HdfsConfiguration(); MiniDFSCluster srcCluster = null; MiniDFSCluster dstCluster = null; File bak = new File(PathUtils.getTestDir(getClass()), "testURIPaths"); bak.mkdirs(); try { srcCluster = new MiniDFSCluster.Builder(srcConf).numDataNodes(2).build(); dstConf.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, bak.getAbsolutePath()); dstCluster = new MiniDFSCluster.Builder(dstConf).numDataNodes(2).build(); FileSystem srcFs = srcCluster.getFileSystem(); FileSystem dstFs = dstCluster.getFileSystem(); FsShell shell = new FsShell(); shell.setConf(srcConf); // check for ls String[] argv = new String[2]; argv[0] = "-ls"; argv[1] = (getUri().toString()) + "/"; int ret = ToolRunner.run(shell, argv); Assert.assertEquals("ls works on remote uri ", 0, ret); // check for rm -r dstFs.mkdirs(new Path("/hadoopdir")); argv = new String[2]; argv[0] = "-rmr"; argv[1] = (getUri().toString()) + "/hadoopdir"; ret = ToolRunner.run(shell, argv); Assert.assertEquals(("-rmr works on remote uri " + (argv[1])), 0, ret); // check du argv[0] = "-du"; argv[1] = (getUri().toString()) + "/"; ret = ToolRunner.run(shell, argv); Assert.assertEquals("du works on remote uri ", 0, ret); // check put File furi = new File(TestDFSShell.TEST_ROOT_DIR, "furi"); TestDFSShell.createLocalFile(furi); argv = new String[3]; argv[0] = "-put"; argv[1] = furi.toURI().toString(); argv[2] = (getUri().toString()) + "/furi"; ret = ToolRunner.run(shell, argv); Assert.assertEquals(" put is working ", 0, ret); // check cp argv[0] = "-cp"; argv[1] = (getUri().toString()) + "/furi"; argv[2] = (getUri().toString()) + "/furi"; ret = ToolRunner.run(shell, argv); Assert.assertEquals(" cp is working ", 0, ret); Assert.assertTrue(srcFs.exists(new Path("/furi"))); // check cat argv = new String[2]; argv[0] = "-cat"; argv[1] = (getUri().toString()) + "/furi"; ret = ToolRunner.run(shell, argv); Assert.assertEquals(" cat is working ", 0, ret); // check chown dstFs.delete(new Path("/furi"), true); dstFs.delete(new Path("/hadoopdir"), true); String file = "/tmp/chownTest"; Path path = new Path(file); Path parent = new Path("/tmp"); Path root = new Path("/"); TestDFSShell.writeFile(dstFs, path); TestDFSShell.runCmd(shell, "-chgrp", "-R", "herbivores", ((getUri().toString()) + "/*")); confirmOwner(null, "herbivores", dstFs, parent, path); TestDFSShell.runCmd(shell, "-chown", "-R", ":reptiles", ((getUri().toString()) + "/")); confirmOwner(null, "reptiles", dstFs, root, parent, path); // check if default hdfs:/// works argv[0] = "-cat"; argv[1] = "hdfs:///furi"; ret = ToolRunner.run(shell, argv); Assert.assertEquals(" default works for cat", 0, ret); argv[0] = "-ls"; argv[1] = "hdfs:///"; ret = ToolRunner.run(shell, argv); Assert.assertEquals("default works for ls ", 0, ret); argv[0] = "-rmr"; argv[1] = "hdfs:///furi"; ret = ToolRunner.run(shell, argv); Assert.assertEquals("default works for rm/rmr", 0, ret); } finally { if (null != srcCluster) { srcCluster.shutdown(); } if (null != dstCluster) { dstCluster.shutdown(); } } } /** * Test that -head displays first kilobyte of the file to stdout. */ @Test(timeout = 30000) public void testHead() throws Exception { final int fileLen = 5 * (TestDFSShell.BLOCK_SIZE); // create a text file with multiple KB bytes (and multiple blocks) final Path testFile = new Path("testHead", "file1"); final String text = RandomStringUtils.randomAscii(fileLen); try (OutputStream pout = TestDFSShell.dfs.create(testFile)) { pout.write(text.getBytes()); } final ByteArrayOutputStream out = new ByteArrayOutputStream(); System.setOut(new PrintStream(out)); final String[] argv = new String[]{ "-head", testFile.toString() }; final int ret = ToolRunner.run(new FsShell(TestDFSShell.dfs.getConf()), argv); Assert.assertEquals((((Arrays.toString(argv)) + " returned ") + ret), 0, ret); Assert.assertEquals((("-head returned " + (out.size())) + " bytes data, expected 1KB"), 1024, out.size()); // tailed out last 1KB of the file content Assert.assertArrayEquals("Head output doesn't match input", text.substring(0, 1024).getBytes(), out.toByteArray()); out.reset(); } /** * Test that -tail displays last kilobyte of the file to stdout. */ @Test(timeout = 30000) public void testTail() throws Exception { final int fileLen = 5 * (TestDFSShell.BLOCK_SIZE); // create a text file with multiple KB bytes (and multiple blocks) final Path testFile = new Path("testTail", "file1"); final String text = RandomStringUtils.randomAscii(fileLen); try (OutputStream pout = TestDFSShell.dfs.create(testFile)) { pout.write(text.getBytes()); } final ByteArrayOutputStream out = new ByteArrayOutputStream(); System.setOut(new PrintStream(out)); final String[] argv = new String[]{ "-tail", testFile.toString() }; final int ret = ToolRunner.run(new FsShell(TestDFSShell.dfs.getConf()), argv); Assert.assertEquals((((Arrays.toString(argv)) + " returned ") + ret), 0, ret); Assert.assertEquals((("-tail returned " + (out.size())) + " bytes data, expected 1KB"), 1024, out.size()); // tailed out last 1KB of the file content Assert.assertArrayEquals("Tail output doesn't match input", text.substring((fileLen - 1024)).getBytes(), out.toByteArray()); out.reset(); } /** * Test that -tail -f outputs appended data as the file grows. */ @Test(timeout = 30000) public void testTailWithFresh() throws Exception { final Path testFile = new Path("testTailWithFresh", "file1"); TestDFSShell.dfs.create(testFile); final ByteArrayOutputStream out = new ByteArrayOutputStream(); System.setOut(new PrintStream(out)); final Thread tailer = new Thread() { @Override public void run() { final String[] argv = new String[]{ "-tail", "-f", testFile.toString() }; try { ToolRunner.run(new FsShell(TestDFSShell.dfs.getConf()), argv); } catch (Exception e) { TestDFSShell.LOG.error("Client that tails the test file fails", e); } finally { out.reset(); } } }; tailer.start(); // wait till the tailer is sleeping GenericTestUtils.waitFor(new Supplier<Boolean>() { @Override public Boolean get() { return (tailer.getState()) == (TIMED_WAITING); } }, 100, 10000); final String text = RandomStringUtils.randomAscii(((TestDFSShell.BLOCK_SIZE) / 2)); try (OutputStream pout = TestDFSShell.dfs.create(testFile)) { pout.write(text.getBytes()); } // The tailer should eventually show the file contents GenericTestUtils.waitFor(new Supplier<Boolean>() { @Override public Boolean get() { return Arrays.equals(text.getBytes(), out.toByteArray()); } }, 100, 10000); } @Test(timeout = 30000) public void testText() throws Exception { final Configuration conf = TestDFSShell.dfs.getConf(); textTest(new Path("/texttest").makeQualified(TestDFSShell.dfs.getUri(), TestDFSShell.dfs.getWorkingDirectory()), conf); final FileSystem lfs = FileSystem.getLocal(conf); textTest(new Path(TestDFSShell.TEST_ROOT_DIR, "texttest").makeQualified(getUri(), getWorkingDirectory()), conf); } @Test(timeout = 30000) public void testCopyToLocal() throws IOException { FsShell shell = new FsShell(TestDFSShell.dfs.getConf()); String root = TestDFSShell.createTree(TestDFSShell.dfs, "copyToLocal"); // Verify copying the tree { try { Assert.assertEquals(0, TestDFSShell.runCmd(shell, "-copyToLocal", (root + "*"), TestDFSShell.TEST_ROOT_DIR)); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } File localroot = new File(TestDFSShell.TEST_ROOT_DIR, "copyToLocal"); File localroot2 = new File(TestDFSShell.TEST_ROOT_DIR, "copyToLocal2"); File f1 = new File(localroot, "f1"); Assert.assertTrue("Copying failed.", f1.isFile()); File f2 = new File(localroot, "f2"); Assert.assertTrue("Copying failed.", f2.isFile()); File sub = new File(localroot, "sub"); Assert.assertTrue("Copying failed.", sub.isDirectory()); File f3 = new File(sub, "f3"); Assert.assertTrue("Copying failed.", f3.isFile()); File f4 = new File(sub, "f4"); Assert.assertTrue("Copying failed.", f4.isFile()); File f5 = new File(localroot2, "f1"); Assert.assertTrue("Copying failed.", f5.isFile()); f1.delete(); f2.delete(); f3.delete(); f4.delete(); f5.delete(); sub.delete(); } // Verify copying non existing sources do not create zero byte // destination files { String[] args = new String[]{ "-copyToLocal", "nosuchfile", TestDFSShell.TEST_ROOT_DIR }; try { Assert.assertEquals(1, shell.run(args)); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } File f6 = new File(TestDFSShell.TEST_ROOT_DIR, "nosuchfile"); Assert.assertTrue((!(f6.exists()))); } } @Test(timeout = 30000) public void testCount() throws Exception { FsShell shell = new FsShell(TestDFSShell.dfs.getConf()); String root = TestDFSShell.createTree(TestDFSShell.dfs, "count"); // Verify the counts TestDFSShell.runCount(root, 2, 4, shell); TestDFSShell.runCount((root + "2"), 2, 1, shell); TestDFSShell.runCount((root + "2/f1"), 0, 1, shell); TestDFSShell.runCount((root + "2/sub"), 1, 0, shell); final FileSystem localfs = FileSystem.getLocal(TestDFSShell.dfs.getConf()); Path localpath = new Path(TestDFSShell.TEST_ROOT_DIR, "testcount"); localpath = localpath.makeQualified(getUri(), getWorkingDirectory()); localfs.mkdirs(localpath); final String localstr = localpath.toString(); System.out.println(("localstr=" + localstr)); TestDFSShell.runCount(localstr, 1, 0, shell); Assert.assertEquals(0, TestDFSShell.runCmd(shell, "-count", root, localstr)); } @Test(timeout = 30000) public void testTotalSizeOfAllFiles() throws Exception { final Path root = new Path("/testTotalSizeOfAllFiles"); TestDFSShell.dfs.mkdirs(root); // create file under root FSDataOutputStream File1 = TestDFSShell.dfs.create(new Path(root, "File1")); File1.write("hi".getBytes()); File1.close(); // create file under sub-folder FSDataOutputStream File2 = TestDFSShell.dfs.create(new Path(root, "Folder1/File2")); File2.write("hi".getBytes()); File2.close(); // getUsed() should return total length of all the files in Filesystem Assert.assertEquals(4, TestDFSShell.dfs.getUsed(root)); } @Test(timeout = 30000) public void testFilePermissions() throws IOException { Configuration conf = new HdfsConfiguration(); // test chmod on local fs FileSystem fs = FileSystem.getLocal(conf); testChmod(conf, fs, new File(TestDFSShell.TEST_ROOT_DIR, "chmodTest").getAbsolutePath()); conf.set(DFS_PERMISSIONS_ENABLED_KEY, "true"); // test chmod on DFS fs = TestDFSShell.dfs; conf = TestDFSShell.dfs.getConf(); testChmod(conf, fs, "/tmp/chmodTest"); // test chown and chgrp on DFS: FsShell shell = new FsShell(); shell.setConf(conf); /* For dfs, I am the super user and I can change owner of any file to anything. "-R" option is already tested by chmod test above. */ String file = "/tmp/chownTest"; Path path = new Path(file); Path parent = new Path("/tmp"); Path root = new Path("/"); TestDFSShell.writeFile(fs, path); TestDFSShell.runCmd(shell, "-chgrp", "-R", "herbivores", "/*", "unknownFile*"); confirmOwner(null, "herbivores", fs, parent, path); TestDFSShell.runCmd(shell, "-chgrp", "mammals", file); confirmOwner(null, "mammals", fs, path); TestDFSShell.runCmd(shell, "-chown", "-R", ":reptiles", "/"); confirmOwner(null, "reptiles", fs, root, parent, path); TestDFSShell.runCmd(shell, "-chown", "python:", "/nonExistentFile", file); confirmOwner("python", "reptiles", fs, path); TestDFSShell.runCmd(shell, "-chown", "-R", "hadoop:toys", "unknownFile", "/"); confirmOwner("hadoop", "toys", fs, root, parent, path); // Test different characters in names TestDFSShell.runCmd(shell, "-chown", "hdfs.user", file); confirmOwner("hdfs.user", null, fs, path); TestDFSShell.runCmd(shell, "-chown", "_Hdfs.User-10:_hadoop.users--", file); confirmOwner("_Hdfs.User-10", "_hadoop.users--", fs, path); TestDFSShell.runCmd(shell, "-chown", "hdfs/hadoop-core@apache.org:asf-projects", file); confirmOwner("hdfs/hadoop-core@apache.org", "asf-projects", fs, path); TestDFSShell.runCmd(shell, "-chgrp", "hadoop-core@apache.org/100", file); confirmOwner(null, "hadoop-core@apache.org/100", fs, path); } /** * Tests various options of DFSShell. */ @Test(timeout = 120000) public void testDFSShell() throws Exception { /* This tests some properties of ChecksumFileSystem as well. Make sure that we create ChecksumDFS */ FsShell shell = new FsShell(TestDFSShell.dfs.getConf()); // First create a new directory with mkdirs Path myPath = new Path("/testDFSShell/mkdirs"); Assert.assertTrue(TestDFSShell.dfs.mkdirs(myPath)); Assert.assertTrue(TestDFSShell.dfs.exists(myPath)); Assert.assertTrue(TestDFSShell.dfs.mkdirs(myPath)); // Second, create a file in that directory. Path myFile = new Path("/testDFSShell/mkdirs/myFile"); TestDFSShell.writeFile(TestDFSShell.dfs, myFile); Assert.assertTrue(TestDFSShell.dfs.exists(myFile)); Path myFile2 = new Path("/testDFSShell/mkdirs/myFile2"); TestDFSShell.writeFile(TestDFSShell.dfs, myFile2); Assert.assertTrue(TestDFSShell.dfs.exists(myFile2)); // Verify that rm with a pattern { String[] args = new String[2]; args[0] = "-rm"; args[1] = "/testDFSShell/mkdirs/myFile*"; int val = -1; try { val = shell.run(args); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertTrue((val == 0)); Assert.assertFalse(TestDFSShell.dfs.exists(myFile)); Assert.assertFalse(TestDFSShell.dfs.exists(myFile2)); // re-create the files for other tests TestDFSShell.writeFile(TestDFSShell.dfs, myFile); Assert.assertTrue(TestDFSShell.dfs.exists(myFile)); TestDFSShell.writeFile(TestDFSShell.dfs, myFile2); Assert.assertTrue(TestDFSShell.dfs.exists(myFile2)); } // Verify that we can read the file { String[] args = new String[3]; args[0] = "-cat"; args[1] = "/testDFSShell/mkdirs/myFile"; args[2] = "/testDFSShell/mkdirs/myFile2"; int val = -1; try { val = shell.run(args); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run: " + (StringUtils.stringifyException(e)))); } Assert.assertTrue((val == 0)); } TestDFSShell.dfs.delete(myFile2, true); // Verify that we get an error while trying to read an nonexistent file { String[] args = new String[2]; args[0] = "-cat"; args[1] = "/testDFSShell/mkdirs/myFile1"; int val = -1; try { val = shell.run(args); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertTrue((val != 0)); } // Verify that we get an error while trying to delete an nonexistent file { String[] args = new String[2]; args[0] = "-rm"; args[1] = "/testDFSShell/mkdirs/myFile1"; int val = -1; try { val = shell.run(args); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertTrue((val != 0)); } // Verify that we succeed in removing the file we created { String[] args = new String[2]; args[0] = "-rm"; args[1] = "/testDFSShell/mkdirs/myFile"; int val = -1; try { val = shell.run(args); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertTrue((val == 0)); } // Verify touch/test { String[] args; int val; args = new String[3]; args[0] = "-test"; args[1] = "-e"; args[2] = "/testDFSShell/mkdirs/noFileHere"; val = -1; try { val = shell.run(args); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(1, val); args[1] = "-z"; val = -1; try { val = shell.run(args); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(1, val); args = new String[2]; args[0] = "-touchz"; args[1] = "/testDFSShell/mkdirs/isFileHere"; val = -1; try { val = shell.run(args); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(0, val); args = new String[2]; args[0] = "-touchz"; args[1] = "/testDFSShell/mkdirs/thisDirNotExists/isFileHere"; val = -1; try { val = shell.run(args); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(1, val); args = new String[3]; args[0] = "-test"; args[1] = "-e"; args[2] = "/testDFSShell/mkdirs/isFileHere"; val = -1; try { val = shell.run(args); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(0, val); args[1] = "-d"; val = -1; try { val = shell.run(args); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(1, val); args[1] = "-z"; val = -1; try { val = shell.run(args); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(0, val); } // Verify that cp from a directory to a subdirectory fails { String[] args = new String[2]; args[0] = "-mkdir"; args[1] = "/testDFSShell/dir1"; int val = -1; try { val = shell.run(args); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(0, val); // this should fail String[] args1 = new String[3]; args1[0] = "-cp"; args1[1] = "/testDFSShell/dir1"; args1[2] = "/testDFSShell/dir1/dir2"; val = 0; try { val = shell.run(args1); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(1, val); // this should succeed args1[0] = "-cp"; args1[1] = "/testDFSShell/dir1"; args1[2] = "/testDFSShell/dir1foo"; val = -1; try { val = shell.run(args1); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(0, val); // this should fail args1[0] = "-cp"; args1[1] = "/"; args1[2] = "/test"; val = 0; try { val = shell.run(args1); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(1, val); } // Verify -test -f negative case (missing file) { String[] args = new String[3]; args[0] = "-test"; args[1] = "-f"; args[2] = "/testDFSShell/mkdirs/noFileHere"; int val = -1; try { val = shell.run(args); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(1, val); } // Verify -test -f negative case (directory rather than file) { String[] args = new String[3]; args[0] = "-test"; args[1] = "-f"; args[2] = "/testDFSShell/mkdirs"; int val = -1; try { val = shell.run(args); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(1, val); } // Verify -test -f positive case { TestDFSShell.writeFile(TestDFSShell.dfs, myFile); Assert.assertTrue(TestDFSShell.dfs.exists(myFile)); String[] args = new String[3]; args[0] = "-test"; args[1] = "-f"; args[2] = myFile.toString(); int val = -1; try { val = shell.run(args); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(0, val); } // Verify -test -s negative case (missing file) { String[] args = new String[3]; args[0] = "-test"; args[1] = "-s"; args[2] = "/testDFSShell/mkdirs/noFileHere"; int val = -1; try { val = shell.run(args); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(1, val); } // Verify -test -s negative case (zero length file) { String[] args = new String[3]; args[0] = "-test"; args[1] = "-s"; args[2] = "/testDFSShell/mkdirs/isFileHere"; int val = -1; try { val = shell.run(args); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(1, val); } // Verify -test -s positive case (nonzero length file) { String[] args = new String[3]; args[0] = "-test"; args[1] = "-s"; args[2] = myFile.toString(); int val = -1; try { val = shell.run(args); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(0, val); } // Verify -test -w/-r { Path permDir = new Path("/testDFSShell/permDir"); Path permFile = new Path("/testDFSShell/permDir/permFile"); TestDFSShell.mkdir(TestDFSShell.dfs, permDir); TestDFSShell.writeFile(TestDFSShell.dfs, permFile); // Verify -test -w positive case (dir exists and can write) final String[] wargs = new String[3]; wargs[0] = "-test"; wargs[1] = "-w"; wargs[2] = permDir.toString(); int val = -1; try { val = shell.run(wargs); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(0, val); // Verify -test -r positive case (file exists and can read) final String[] rargs = new String[3]; rargs[0] = "-test"; rargs[1] = "-r"; rargs[2] = permFile.toString(); try { val = shell.run(rargs); } catch (Exception e) { System.err.println(("Exception raised from DFSShell.run " + (e.getLocalizedMessage()))); } Assert.assertEquals(0, val); // Verify -test -r negative case (file exists but cannot read) TestDFSShell.runCmd(shell, "-chmod", "600", permFile.toString()); UserGroupInformation smokeUser = UserGroupInformation.createUserForTesting("smokeUser", new String[]{ "hadoop" }); smokeUser.doAs(new PrivilegedExceptionAction<String>() { @Override public String run() throws Exception { FsShell shell = new FsShell(TestDFSShell.dfs.getConf()); int exitCode = shell.run(rargs); Assert.assertEquals(1, exitCode); return null; } }); // Verify -test -w negative case (dir exists but cannot write) TestDFSShell.runCmd(shell, "-chown", "-R", "not_allowed", permDir.toString()); TestDFSShell.runCmd(shell, "-chmod", "-R", "700", permDir.toString()); smokeUser.doAs(new PrivilegedExceptionAction<String>() { @Override public String run() throws Exception { FsShell shell = new FsShell(TestDFSShell.dfs.getConf()); int exitCode = shell.run(wargs); Assert.assertEquals(1, exitCode); return null; } }); // cleanup TestDFSShell.dfs.delete(permDir, true); } } static interface TestGetRunner { String run(int exitcode, String... options) throws IOException; } @Test(timeout = 30000) public void testRemoteException() throws Exception { UserGroupInformation tmpUGI = UserGroupInformation.createUserForTesting("tmpname", new String[]{ "mygroup" }); PrintStream bak = null; try { Path p = new Path("/foo"); TestDFSShell.dfs.mkdirs(p); TestDFSShell.dfs.setPermission(p, new FsPermission(((short) (448)))); bak = System.err; tmpUGI.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { FsShell fshell = new FsShell(TestDFSShell.dfs.getConf()); ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream tmp = new PrintStream(out); System.setErr(tmp); String[] args = new String[2]; args[0] = "-ls"; args[1] = "/foo"; int ret = ToolRunner.run(fshell, args); Assert.assertEquals("returned should be 1", 1, ret); String str = out.toString(); Assert.assertTrue("permission denied printed", ((str.indexOf("Permission denied")) != (-1))); out.reset(); return null; } }); } finally { if (bak != null) { System.setErr(bak); } } } @Test(timeout = 30000) public void testGet() throws IOException { GenericTestUtils.setLogLevel(FSInputChecker.LOG, Level.ALL); final String fname = "testGet.txt"; Path root = new Path("/test/get"); final Path remotef = new Path(root, fname); final Configuration conf = new HdfsConfiguration(); // Set short retry timeouts so this test runs faster conf.setInt(WINDOW_BASE_KEY, 10); TestDFSShell.TestGetRunner runner = new TestDFSShell.TestGetRunner() { private int count = 0; private final FsShell shell = new FsShell(conf); public String run(int exitcode, String... options) throws IOException { String dst = new File(TestDFSShell.TEST_ROOT_DIR, (fname + (++(count)))).getAbsolutePath(); String[] args = new String[(options.length) + 3]; args[0] = "-get"; args[((args.length) - 2)] = remotef.toString(); args[((args.length) - 1)] = dst; for (int i = 0; i < (options.length); i++) { args[(i + 1)] = options[i]; } TestDFSShell.show(("args=" + (Arrays.asList(args)))); try { Assert.assertEquals(exitcode, shell.run(args)); } catch (Exception e) { Assert.assertTrue(StringUtils.stringifyException(e), false); } return exitcode == 0 ? DFSTestUtil.readFile(new File(dst)) : null; } }; File localf = TestDFSShell.createLocalFile(new File(TestDFSShell.TEST_ROOT_DIR, fname)); MiniDFSCluster cluster = null; DistributedFileSystem dfs = null; try { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).format(true).build(); dfs = cluster.getFileSystem(); TestDFSShell.mkdir(dfs, root); dfs.copyFromLocalFile(false, false, new Path(localf.getPath()), remotef); String localfcontent = DFSTestUtil.readFile(localf); Assert.assertEquals(localfcontent, runner.run(0)); Assert.assertEquals(localfcontent, runner.run(0, "-ignoreCrc")); // find block files to modify later List<FsDatasetTestUtils.MaterializedReplica> replicas = TestDFSShell.getMaterializedReplicas(cluster); // Shut down miniCluster and then corrupt the block files by overwriting a // portion with junk data. We must shut down the miniCluster so that threads // in the data node do not hold locks on the block files while we try to // write into them. Particularly on Windows, the data node's use of the // FileChannel.transferTo method can cause block files to be memory mapped // in read-only mode during the transfer to a client, and this causes a // locking conflict. The call to shutdown the miniCluster blocks until all // DataXceiver threads exit, preventing this problem. dfs.close(); cluster.shutdown(); TestDFSShell.show(("replicas=" + replicas)); TestDFSShell.corrupt(replicas, localfcontent); // Start the miniCluster again, but do not reformat, so prior files remain. cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).format(false).build(); dfs = cluster.getFileSystem(); Assert.assertEquals(null, runner.run(1)); String corruptedcontent = runner.run(0, "-ignoreCrc"); Assert.assertEquals(localfcontent.substring(1), corruptedcontent.substring(1)); Assert.assertEquals(((localfcontent.charAt(0)) + 1), corruptedcontent.charAt(0)); } finally { if (null != dfs) { try { dfs.close(); } catch (Exception e) { } } if (null != cluster) { cluster.shutdown(); } localf.delete(); } } /** * Test -stat [format] <path>... prints statistics about the file/directory * at <path> in the specified format. */ @Test(timeout = 30000) public void testStat() throws Exception { final SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); fmt.setTimeZone(TimeZone.getTimeZone("UTC")); final Path testDir1 = new Path("testStat", "dir1"); TestDFSShell.dfs.mkdirs(testDir1); final Path testFile2 = new Path(testDir1, "file2"); DFSTestUtil.createFile(TestDFSShell.dfs, testFile2, (2 * (TestDFSShell.BLOCK_SIZE)), ((short) (3)), 0); final FileStatus status1 = TestDFSShell.dfs.getFileStatus(testDir1); final String mtime1 = fmt.format(new Date(status1.getModificationTime())); final String atime1 = fmt.format(new Date(status1.getAccessTime())); long now = Time.now(); TestDFSShell.dfs.setTimes(testFile2, (now + 3000), (now + 6000)); final FileStatus status2 = TestDFSShell.dfs.getFileStatus(testFile2); final String mtime2 = fmt.format(new Date(status2.getModificationTime())); final String atime2 = fmt.format(new Date(status2.getAccessTime())); final ByteArrayOutputStream out = new ByteArrayOutputStream(); System.setOut(new PrintStream(out)); TestDFSShell.doFsStat(TestDFSShell.dfs.getConf(), null); out.reset(); TestDFSShell.doFsStat(TestDFSShell.dfs.getConf(), null, testDir1); Assert.assertEquals(("Unexpected -stat output: " + out), out.toString(), String.format("%s%n", mtime1)); out.reset(); TestDFSShell.doFsStat(TestDFSShell.dfs.getConf(), null, testDir1, testFile2); Assert.assertEquals(("Unexpected -stat output: " + out), out.toString(), String.format("%s%n%s%n", mtime1, mtime2)); TestDFSShell.doFsStat(TestDFSShell.dfs.getConf(), "%F %u:%g %b %y %n"); out.reset(); TestDFSShell.doFsStat(TestDFSShell.dfs.getConf(), "%F %a %A %u:%g %b %y %n", testDir1); Assert.assertTrue(out.toString(), out.toString().contains(mtime1)); Assert.assertTrue(out.toString(), out.toString().contains("directory")); Assert.assertTrue(out.toString(), out.toString().contains(status1.getGroup())); Assert.assertTrue(out.toString(), out.toString().contains(status1.getPermission().toString())); int n = status1.getPermission().toShort(); int octal = (((((n >>> 9) & 1) * 1000) + (((n >>> 6) & 7) * 100)) + (((n >>> 3) & 7) * 10)) + (n & 7); Assert.assertTrue(out.toString(), out.toString().contains(String.valueOf(octal))); out.reset(); TestDFSShell.doFsStat(TestDFSShell.dfs.getConf(), "%F %a %A %u:%g %b %x %y %n", testDir1, testFile2); n = status2.getPermission().toShort(); octal = (((((n >>> 9) & 1) * 1000) + (((n >>> 6) & 7) * 100)) + (((n >>> 3) & 7) * 10)) + (n & 7); Assert.assertTrue(out.toString(), out.toString().contains(mtime1)); Assert.assertTrue(out.toString(), out.toString().contains(atime1)); Assert.assertTrue(out.toString(), out.toString().contains("regular file")); Assert.assertTrue(out.toString(), out.toString().contains(status2.getPermission().toString())); Assert.assertTrue(out.toString(), out.toString().contains(String.valueOf(octal))); Assert.assertTrue(out.toString(), out.toString().contains(mtime2)); Assert.assertTrue(out.toString(), out.toString().contains(atime2)); } @Test(timeout = 30000) public void testLsr() throws Exception { final Configuration conf = TestDFSShell.dfs.getConf(); final String root = TestDFSShell.createTree(TestDFSShell.dfs, "lsr"); TestDFSShell.dfs.mkdirs(new Path(root, "zzz")); TestDFSShell.runLsr(new FsShell(conf), root, 0); final Path sub = new Path(root, "sub"); TestDFSShell.dfs.setPermission(sub, new FsPermission(((short) (0)))); final UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); final String tmpusername = (ugi.getShortUserName()) + "1"; UserGroupInformation tmpUGI = UserGroupInformation.createUserForTesting(tmpusername, new String[]{ tmpusername }); String results = tmpUGI.doAs(new PrivilegedExceptionAction<String>() { @Override public String run() throws Exception { return TestDFSShell.runLsr(new FsShell(conf), root, 1); } }); Assert.assertTrue(results.contains("zzz")); } /** * default setting is file:// which is not a DFS * so DFSAdmin should throw and catch InvalidArgumentException * and return -1 exit code. * * @throws Exception * */ @Test(timeout = 30000) public void testInvalidShell() throws Exception { Configuration conf = new Configuration();// default FS (non-DFS) DFSAdmin admin = new DFSAdmin(); admin.setConf(conf); int res = admin.run(new String[]{ "-refreshNodes" }); Assert.assertEquals("expected to fail -1", res, (-1)); } // Preserve Copy Option is -ptopxa (timestamps, ownership, permission, XATTR, // ACLs) @Test(timeout = 120000) public void testCopyCommandsWithPreserveOption() throws Exception { FsShell shell = null; final String testdir = "/tmp/TestDFSShell-testCopyCommandsWithPreserveOption-" + (TestDFSShell.counter.getAndIncrement()); final Path hdfsTestDir = new Path(testdir); try { TestDFSShell.dfs.mkdirs(hdfsTestDir); Path src = new Path(hdfsTestDir, "srcfile"); TestDFSShell.dfs.create(src).close(); TestDFSShell.dfs.setAcl(src, Lists.newArrayList(AclTestHelpers.aclEntry(AclEntryScope.ACCESS, USER, ALL), AclTestHelpers.aclEntry(AclEntryScope.ACCESS, USER, "foo", ALL), AclTestHelpers.aclEntry(AclEntryScope.ACCESS, GROUP, READ_EXECUTE), AclTestHelpers.aclEntry(AclEntryScope.ACCESS, GROUP, "bar", READ_EXECUTE), AclTestHelpers.aclEntry(AclEntryScope.ACCESS, OTHER, EXECUTE))); FileStatus status = TestDFSShell.dfs.getFileStatus(src); final long mtime = status.getModificationTime(); final long atime = status.getAccessTime(); final String owner = status.getOwner(); final String group = status.getGroup(); final FsPermission perm = status.getPermission(); TestDFSShell.dfs.setXAttr(src, TestDFSShell.USER_A1, TestDFSShell.USER_A1_VALUE); TestDFSShell.dfs.setXAttr(src, TestDFSShell.TRUSTED_A1, TestDFSShell.TRUSTED_A1_VALUE); shell = new FsShell(TestDFSShell.dfs.getConf()); // -p Path target1 = new Path(hdfsTestDir, "targetfile1"); String[] argv = new String[]{ "-cp", "-p", src.toUri().toString(), target1.toUri().toString() }; int ret = ToolRunner.run(shell, argv); Assert.assertEquals("cp -p is not working", SUCCESS, ret); FileStatus targetStatus = TestDFSShell.dfs.getFileStatus(target1); Assert.assertEquals(mtime, targetStatus.getModificationTime()); Assert.assertEquals(atime, targetStatus.getAccessTime()); Assert.assertEquals(owner, targetStatus.getOwner()); Assert.assertEquals(group, targetStatus.getGroup()); FsPermission targetPerm = targetStatus.getPermission(); Assert.assertTrue(perm.equals(targetPerm)); Map<String, byte[]> xattrs = TestDFSShell.dfs.getXAttrs(target1); Assert.assertTrue(xattrs.isEmpty()); List<AclEntry> acls = TestDFSShell.dfs.getAclStatus(target1).getEntries(); Assert.assertTrue(acls.isEmpty()); Assert.assertFalse(targetStatus.hasAcl()); // -ptop Path target2 = new Path(hdfsTestDir, "targetfile2"); argv = new String[]{ "-cp", "-ptop", src.toUri().toString(), target2.toUri().toString() }; ret = ToolRunner.run(shell, argv); Assert.assertEquals("cp -ptop is not working", SUCCESS, ret); targetStatus = TestDFSShell.dfs.getFileStatus(target2); Assert.assertEquals(mtime, targetStatus.getModificationTime()); Assert.assertEquals(atime, targetStatus.getAccessTime()); Assert.assertEquals(owner, targetStatus.getOwner()); Assert.assertEquals(group, targetStatus.getGroup()); targetPerm = targetStatus.getPermission(); Assert.assertTrue(perm.equals(targetPerm)); xattrs = TestDFSShell.dfs.getXAttrs(target2); Assert.assertTrue(xattrs.isEmpty()); acls = TestDFSShell.dfs.getAclStatus(target2).getEntries(); Assert.assertTrue(acls.isEmpty()); Assert.assertFalse(targetStatus.hasAcl()); // -ptopx Path target3 = new Path(hdfsTestDir, "targetfile3"); argv = new String[]{ "-cp", "-ptopx", src.toUri().toString(), target3.toUri().toString() }; ret = ToolRunner.run(shell, argv); Assert.assertEquals("cp -ptopx is not working", SUCCESS, ret); targetStatus = TestDFSShell.dfs.getFileStatus(target3); Assert.assertEquals(mtime, targetStatus.getModificationTime()); Assert.assertEquals(atime, targetStatus.getAccessTime()); Assert.assertEquals(owner, targetStatus.getOwner()); Assert.assertEquals(group, targetStatus.getGroup()); targetPerm = targetStatus.getPermission(); Assert.assertTrue(perm.equals(targetPerm)); xattrs = TestDFSShell.dfs.getXAttrs(target3); Assert.assertEquals(xattrs.size(), 2); Assert.assertArrayEquals(TestDFSShell.USER_A1_VALUE, xattrs.get(TestDFSShell.USER_A1)); Assert.assertArrayEquals(TestDFSShell.TRUSTED_A1_VALUE, xattrs.get(TestDFSShell.TRUSTED_A1)); acls = TestDFSShell.dfs.getAclStatus(target3).getEntries(); Assert.assertTrue(acls.isEmpty()); Assert.assertFalse(targetStatus.hasAcl()); // -ptopa Path target4 = new Path(hdfsTestDir, "targetfile4"); argv = new String[]{ "-cp", "-ptopa", src.toUri().toString(), target4.toUri().toString() }; ret = ToolRunner.run(shell, argv); Assert.assertEquals("cp -ptopa is not working", SUCCESS, ret); targetStatus = TestDFSShell.dfs.getFileStatus(target4); Assert.assertEquals(mtime, targetStatus.getModificationTime()); Assert.assertEquals(atime, targetStatus.getAccessTime()); Assert.assertEquals(owner, targetStatus.getOwner()); Assert.assertEquals(group, targetStatus.getGroup()); targetPerm = targetStatus.getPermission(); Assert.assertTrue(perm.equals(targetPerm)); xattrs = TestDFSShell.dfs.getXAttrs(target4); Assert.assertTrue(xattrs.isEmpty()); acls = TestDFSShell.dfs.getAclStatus(target4).getEntries(); Assert.assertFalse(acls.isEmpty()); Assert.assertTrue(targetStatus.hasAcl()); Assert.assertEquals(TestDFSShell.dfs.getAclStatus(src), TestDFSShell.dfs.getAclStatus(target4)); // -ptoa (verify -pa option will preserve permissions also) Path target5 = new Path(hdfsTestDir, "targetfile5"); argv = new String[]{ "-cp", "-ptoa", src.toUri().toString(), target5.toUri().toString() }; ret = ToolRunner.run(shell, argv); Assert.assertEquals("cp -ptoa is not working", SUCCESS, ret); targetStatus = TestDFSShell.dfs.getFileStatus(target5); Assert.assertEquals(mtime, targetStatus.getModificationTime()); Assert.assertEquals(atime, targetStatus.getAccessTime()); Assert.assertEquals(owner, targetStatus.getOwner()); Assert.assertEquals(group, targetStatus.getGroup()); targetPerm = targetStatus.getPermission(); Assert.assertTrue(perm.equals(targetPerm)); xattrs = TestDFSShell.dfs.getXAttrs(target5); Assert.assertTrue(xattrs.isEmpty()); acls = TestDFSShell.dfs.getAclStatus(target5).getEntries(); Assert.assertFalse(acls.isEmpty()); Assert.assertTrue(targetStatus.hasAcl()); Assert.assertEquals(TestDFSShell.dfs.getAclStatus(src), TestDFSShell.dfs.getAclStatus(target5)); } finally { if (null != shell) { shell.close(); } } } @Test(timeout = 120000) public void testCopyCommandsWithRawXAttrs() throws Exception { FsShell shell = null; final String testdir = "/tmp/TestDFSShell-testCopyCommandsWithRawXAttrs-" + (TestDFSShell.counter.getAndIncrement()); final Path hdfsTestDir = new Path(testdir); final Path rawHdfsTestDir = new Path(("/.reserved/raw" + testdir)); try { TestDFSShell.dfs.mkdirs(hdfsTestDir); final Path src = new Path(hdfsTestDir, "srcfile"); final String rawSrcBase = "/.reserved/raw" + testdir; final Path rawSrc = new Path(rawSrcBase, "srcfile"); TestDFSShell.dfs.create(src).close(); final Path srcDir = new Path(hdfsTestDir, "srcdir"); final Path rawSrcDir = new Path(("/.reserved/raw" + testdir), "srcdir"); TestDFSShell.dfs.mkdirs(srcDir); final Path srcDirFile = new Path(srcDir, "srcfile"); final Path rawSrcDirFile = new Path(("/.reserved/raw" + srcDirFile)); TestDFSShell.dfs.create(srcDirFile).close(); final Path[] paths = new org.apache.hadoop.fs.Path[]{ rawSrc, rawSrcDir, rawSrcDirFile }; final String[] xattrNames = new String[]{ TestDFSShell.USER_A1, TestDFSShell.RAW_A1 }; final byte[][] xattrVals = new byte[][]{ TestDFSShell.USER_A1_VALUE, TestDFSShell.RAW_A1_VALUE }; for (int i = 0; i < (paths.length); i++) { for (int j = 0; j < (xattrNames.length); j++) { TestDFSShell.dfs.setXAttr(paths[i], xattrNames[j], xattrVals[j]); } } shell = new FsShell(TestDFSShell.dfs.getConf()); /* Check that a file as the source path works ok. */ doTestCopyCommandsWithRawXAttrs(shell, TestDFSShell.dfs, src, hdfsTestDir, false); doTestCopyCommandsWithRawXAttrs(shell, TestDFSShell.dfs, rawSrc, hdfsTestDir, false); doTestCopyCommandsWithRawXAttrs(shell, TestDFSShell.dfs, src, rawHdfsTestDir, false); doTestCopyCommandsWithRawXAttrs(shell, TestDFSShell.dfs, rawSrc, rawHdfsTestDir, true); /* Use a relative /.reserved/raw path. */ final Path savedWd = TestDFSShell.dfs.getWorkingDirectory(); try { TestDFSShell.dfs.setWorkingDirectory(new Path(rawSrcBase)); final Path relRawSrc = new Path("../srcfile"); final Path relRawHdfsTestDir = new Path(".."); doTestCopyCommandsWithRawXAttrs(shell, TestDFSShell.dfs, relRawSrc, relRawHdfsTestDir, true); } finally { TestDFSShell.dfs.setWorkingDirectory(savedWd); } /* Check that a directory as the source path works ok. */ doTestCopyCommandsWithRawXAttrs(shell, TestDFSShell.dfs, srcDir, hdfsTestDir, false); doTestCopyCommandsWithRawXAttrs(shell, TestDFSShell.dfs, rawSrcDir, hdfsTestDir, false); doTestCopyCommandsWithRawXAttrs(shell, TestDFSShell.dfs, srcDir, rawHdfsTestDir, false); doTestCopyCommandsWithRawXAttrs(shell, TestDFSShell.dfs, rawSrcDir, rawHdfsTestDir, true); /* Use relative in an absolute path. */ final String relRawSrcDir = ("./.reserved/../.reserved/raw/../raw" + testdir) + "/srcdir"; final String relRawDstDir = "./.reserved/../.reserved/raw/../raw" + testdir; doTestCopyCommandsWithRawXAttrs(shell, TestDFSShell.dfs, new Path(relRawSrcDir), new Path(relRawDstDir), true); } finally { if (null != shell) { shell.close(); } TestDFSShell.dfs.delete(hdfsTestDir, true); } } // verify cp -ptopxa option will preserve directory attributes. @Test(timeout = 120000) public void testCopyCommandsToDirectoryWithPreserveOption() throws Exception { FsShell shell = null; final String testdir = "/tmp/TestDFSShell-testCopyCommandsToDirectoryWithPreserveOption-" + (TestDFSShell.counter.getAndIncrement()); final Path hdfsTestDir = new Path(testdir); try { TestDFSShell.dfs.mkdirs(hdfsTestDir); Path srcDir = new Path(hdfsTestDir, "srcDir"); TestDFSShell.dfs.mkdirs(srcDir); TestDFSShell.dfs.setAcl(srcDir, Lists.newArrayList(AclTestHelpers.aclEntry(AclEntryScope.ACCESS, USER, ALL), AclTestHelpers.aclEntry(AclEntryScope.ACCESS, USER, "foo", ALL), AclTestHelpers.aclEntry(AclEntryScope.ACCESS, GROUP, READ_EXECUTE), AclTestHelpers.aclEntry(AclEntryScope.DEFAULT, GROUP, "bar", READ_EXECUTE), AclTestHelpers.aclEntry(AclEntryScope.ACCESS, OTHER, EXECUTE))); // set sticky bit TestDFSShell.dfs.setPermission(srcDir, new FsPermission(ALL, READ_EXECUTE, EXECUTE, true)); // Create a file in srcDir to check if modification time of // srcDir to be preserved after copying the file. // If cp -p command is to preserve modification time and then copy child // (srcFile), modification time will not be preserved. Path srcFile = new Path(srcDir, "srcFile"); TestDFSShell.dfs.create(srcFile).close(); FileStatus status = TestDFSShell.dfs.getFileStatus(srcDir); final long mtime = status.getModificationTime(); final long atime = status.getAccessTime(); final String owner = status.getOwner(); final String group = status.getGroup(); final FsPermission perm = status.getPermission(); TestDFSShell.dfs.setXAttr(srcDir, TestDFSShell.USER_A1, TestDFSShell.USER_A1_VALUE); TestDFSShell.dfs.setXAttr(srcDir, TestDFSShell.TRUSTED_A1, TestDFSShell.TRUSTED_A1_VALUE); shell = new FsShell(TestDFSShell.dfs.getConf()); // -p Path targetDir1 = new Path(hdfsTestDir, "targetDir1"); String[] argv = new String[]{ "-cp", "-p", srcDir.toUri().toString(), targetDir1.toUri().toString() }; int ret = ToolRunner.run(shell, argv); Assert.assertEquals("cp -p is not working", SUCCESS, ret); FileStatus targetStatus = TestDFSShell.dfs.getFileStatus(targetDir1); Assert.assertEquals(mtime, targetStatus.getModificationTime()); Assert.assertEquals(atime, targetStatus.getAccessTime()); Assert.assertEquals(owner, targetStatus.getOwner()); Assert.assertEquals(group, targetStatus.getGroup()); FsPermission targetPerm = targetStatus.getPermission(); Assert.assertTrue(perm.equals(targetPerm)); Map<String, byte[]> xattrs = TestDFSShell.dfs.getXAttrs(targetDir1); Assert.assertTrue(xattrs.isEmpty()); List<AclEntry> acls = TestDFSShell.dfs.getAclStatus(targetDir1).getEntries(); Assert.assertTrue(acls.isEmpty()); Assert.assertFalse(targetStatus.hasAcl()); // -ptop Path targetDir2 = new Path(hdfsTestDir, "targetDir2"); argv = new String[]{ "-cp", "-ptop", srcDir.toUri().toString(), targetDir2.toUri().toString() }; ret = ToolRunner.run(shell, argv); Assert.assertEquals("cp -ptop is not working", SUCCESS, ret); targetStatus = TestDFSShell.dfs.getFileStatus(targetDir2); Assert.assertEquals(mtime, targetStatus.getModificationTime()); Assert.assertEquals(atime, targetStatus.getAccessTime()); Assert.assertEquals(owner, targetStatus.getOwner()); Assert.assertEquals(group, targetStatus.getGroup()); targetPerm = targetStatus.getPermission(); Assert.assertTrue(perm.equals(targetPerm)); xattrs = TestDFSShell.dfs.getXAttrs(targetDir2); Assert.assertTrue(xattrs.isEmpty()); acls = TestDFSShell.dfs.getAclStatus(targetDir2).getEntries(); Assert.assertTrue(acls.isEmpty()); Assert.assertFalse(targetStatus.hasAcl()); // -ptopx Path targetDir3 = new Path(hdfsTestDir, "targetDir3"); argv = new String[]{ "-cp", "-ptopx", srcDir.toUri().toString(), targetDir3.toUri().toString() }; ret = ToolRunner.run(shell, argv); Assert.assertEquals("cp -ptopx is not working", SUCCESS, ret); targetStatus = TestDFSShell.dfs.getFileStatus(targetDir3); Assert.assertEquals(mtime, targetStatus.getModificationTime()); Assert.assertEquals(atime, targetStatus.getAccessTime()); Assert.assertEquals(owner, targetStatus.getOwner()); Assert.assertEquals(group, targetStatus.getGroup()); targetPerm = targetStatus.getPermission(); Assert.assertTrue(perm.equals(targetPerm)); xattrs = TestDFSShell.dfs.getXAttrs(targetDir3); Assert.assertEquals(xattrs.size(), 2); Assert.assertArrayEquals(TestDFSShell.USER_A1_VALUE, xattrs.get(TestDFSShell.USER_A1)); Assert.assertArrayEquals(TestDFSShell.TRUSTED_A1_VALUE, xattrs.get(TestDFSShell.TRUSTED_A1)); acls = TestDFSShell.dfs.getAclStatus(targetDir3).getEntries(); Assert.assertTrue(acls.isEmpty()); Assert.assertFalse(targetStatus.hasAcl()); // -ptopa Path targetDir4 = new Path(hdfsTestDir, "targetDir4"); argv = new String[]{ "-cp", "-ptopa", srcDir.toUri().toString(), targetDir4.toUri().toString() }; ret = ToolRunner.run(shell, argv); Assert.assertEquals("cp -ptopa is not working", SUCCESS, ret); targetStatus = TestDFSShell.dfs.getFileStatus(targetDir4); Assert.assertEquals(mtime, targetStatus.getModificationTime()); Assert.assertEquals(atime, targetStatus.getAccessTime()); Assert.assertEquals(owner, targetStatus.getOwner()); Assert.assertEquals(group, targetStatus.getGroup()); targetPerm = targetStatus.getPermission(); Assert.assertTrue(perm.equals(targetPerm)); xattrs = TestDFSShell.dfs.getXAttrs(targetDir4); Assert.assertTrue(xattrs.isEmpty()); acls = TestDFSShell.dfs.getAclStatus(targetDir4).getEntries(); Assert.assertFalse(acls.isEmpty()); Assert.assertTrue(targetStatus.hasAcl()); Assert.assertEquals(TestDFSShell.dfs.getAclStatus(srcDir), TestDFSShell.dfs.getAclStatus(targetDir4)); // -ptoa (verify -pa option will preserve permissions also) Path targetDir5 = new Path(hdfsTestDir, "targetDir5"); argv = new String[]{ "-cp", "-ptoa", srcDir.toUri().toString(), targetDir5.toUri().toString() }; ret = ToolRunner.run(shell, argv); Assert.assertEquals("cp -ptoa is not working", SUCCESS, ret); targetStatus = TestDFSShell.dfs.getFileStatus(targetDir5); Assert.assertEquals(mtime, targetStatus.getModificationTime()); Assert.assertEquals(atime, targetStatus.getAccessTime()); Assert.assertEquals(owner, targetStatus.getOwner()); Assert.assertEquals(group, targetStatus.getGroup()); targetPerm = targetStatus.getPermission(); Assert.assertTrue(perm.equals(targetPerm)); xattrs = TestDFSShell.dfs.getXAttrs(targetDir5); Assert.assertTrue(xattrs.isEmpty()); acls = TestDFSShell.dfs.getAclStatus(targetDir5).getEntries(); Assert.assertFalse(acls.isEmpty()); Assert.assertTrue(targetStatus.hasAcl()); Assert.assertEquals(TestDFSShell.dfs.getAclStatus(srcDir), TestDFSShell.dfs.getAclStatus(targetDir5)); } finally { if (shell != null) { shell.close(); } } } // Verify cp -pa option will preserve both ACL and sticky bit. @Test(timeout = 120000) public void testCopyCommandsPreserveAclAndStickyBit() throws Exception { FsShell shell = null; final String testdir = "/tmp/TestDFSShell-testCopyCommandsPreserveAclAndStickyBit-" + (TestDFSShell.counter.getAndIncrement()); final Path hdfsTestDir = new Path(testdir); try { TestDFSShell.dfs.mkdirs(hdfsTestDir); Path src = new Path(hdfsTestDir, "srcfile"); TestDFSShell.dfs.create(src).close(); TestDFSShell.dfs.setAcl(src, Lists.newArrayList(AclTestHelpers.aclEntry(AclEntryScope.ACCESS, USER, ALL), AclTestHelpers.aclEntry(AclEntryScope.ACCESS, USER, "foo", ALL), AclTestHelpers.aclEntry(AclEntryScope.ACCESS, GROUP, READ_EXECUTE), AclTestHelpers.aclEntry(AclEntryScope.ACCESS, GROUP, "bar", READ_EXECUTE), AclTestHelpers.aclEntry(AclEntryScope.ACCESS, OTHER, EXECUTE))); // set sticky bit TestDFSShell.dfs.setPermission(src, new FsPermission(ALL, READ_EXECUTE, EXECUTE, true)); FileStatus status = TestDFSShell.dfs.getFileStatus(src); final long mtime = status.getModificationTime(); final long atime = status.getAccessTime(); final String owner = status.getOwner(); final String group = status.getGroup(); final FsPermission perm = status.getPermission(); shell = new FsShell(TestDFSShell.dfs.getConf()); // -p preserves sticky bit and doesn't preserve ACL Path target1 = new Path(hdfsTestDir, "targetfile1"); String[] argv = new String[]{ "-cp", "-p", src.toUri().toString(), target1.toUri().toString() }; int ret = ToolRunner.run(shell, argv); Assert.assertEquals("cp is not working", SUCCESS, ret); FileStatus targetStatus = TestDFSShell.dfs.getFileStatus(target1); Assert.assertEquals(mtime, targetStatus.getModificationTime()); Assert.assertEquals(atime, targetStatus.getAccessTime()); Assert.assertEquals(owner, targetStatus.getOwner()); Assert.assertEquals(group, targetStatus.getGroup()); FsPermission targetPerm = targetStatus.getPermission(); Assert.assertTrue(perm.equals(targetPerm)); List<AclEntry> acls = TestDFSShell.dfs.getAclStatus(target1).getEntries(); Assert.assertTrue(acls.isEmpty()); Assert.assertFalse(targetStatus.hasAcl()); // -ptopa preserves both sticky bit and ACL Path target2 = new Path(hdfsTestDir, "targetfile2"); argv = new String[]{ "-cp", "-ptopa", src.toUri().toString(), target2.toUri().toString() }; ret = ToolRunner.run(shell, argv); Assert.assertEquals("cp -ptopa is not working", SUCCESS, ret); targetStatus = TestDFSShell.dfs.getFileStatus(target2); Assert.assertEquals(mtime, targetStatus.getModificationTime()); Assert.assertEquals(atime, targetStatus.getAccessTime()); Assert.assertEquals(owner, targetStatus.getOwner()); Assert.assertEquals(group, targetStatus.getGroup()); targetPerm = targetStatus.getPermission(); Assert.assertTrue(perm.equals(targetPerm)); acls = TestDFSShell.dfs.getAclStatus(target2).getEntries(); Assert.assertFalse(acls.isEmpty()); Assert.assertTrue(targetStatus.hasAcl()); Assert.assertEquals(TestDFSShell.dfs.getAclStatus(src), TestDFSShell.dfs.getAclStatus(target2)); } finally { if (null != shell) { shell.close(); } } } // force Copy Option is -f @Test(timeout = 30000) public void testCopyCommandsWithForceOption() throws Exception { FsShell shell = null; final File localFile = new File(TestDFSShell.TEST_ROOT_DIR, "testFileForPut"); final String localfilepath = new Path(localFile.getAbsolutePath()).toUri().toString(); final String testdir = "/tmp/TestDFSShell-testCopyCommandsWithForceOption-" + (TestDFSShell.counter.getAndIncrement()); final Path hdfsTestDir = new Path(testdir); try { TestDFSShell.dfs.mkdirs(hdfsTestDir); localFile.createNewFile(); TestDFSShell.writeFile(TestDFSShell.dfs, new Path(testdir, "testFileForPut")); shell = new FsShell(); // Tests for put String[] argv = new String[]{ "-put", "-f", localfilepath, testdir }; int res = ToolRunner.run(shell, argv); Assert.assertEquals("put -f is not working", SUCCESS, res); argv = new String[]{ "-put", localfilepath, testdir }; res = ToolRunner.run(shell, argv); Assert.assertEquals("put command itself is able to overwrite the file", ERROR, res); // Tests for copyFromLocal argv = new String[]{ "-copyFromLocal", "-f", localfilepath, testdir }; res = ToolRunner.run(shell, argv); Assert.assertEquals("copyFromLocal -f is not working", SUCCESS, res); argv = new String[]{ "-copyFromLocal", localfilepath, testdir }; res = ToolRunner.run(shell, argv); Assert.assertEquals("copyFromLocal command itself is able to overwrite the file", ERROR, res); // Tests for cp argv = new String[]{ "-cp", "-f", localfilepath, testdir }; res = ToolRunner.run(shell, argv); Assert.assertEquals("cp -f is not working", SUCCESS, res); argv = new String[]{ "-cp", localfilepath, testdir }; res = ToolRunner.run(shell, argv); Assert.assertEquals("cp command itself is able to overwrite the file", ERROR, res); } finally { if (null != shell) shell.close(); if (localFile.exists()) localFile.delete(); } } /* [refs HDFS-5033] return a "Permission Denied" message instead of "No such file or Directory" when trying to put/copyFromLocal a file that doesn't have read access */ @Test(timeout = 30000) public void testCopyFromLocalWithPermissionDenied() throws Exception { FsShell shell = null; PrintStream bak = null; final File localFile = new File(TestDFSShell.TEST_ROOT_DIR, "testFileWithNoReadPermissions"); final String localfilepath = new Path(localFile.getAbsolutePath()).toUri().toString(); final String testdir = "/tmp/TestDFSShell-CopyFromLocalWithPermissionDenied-" + (TestDFSShell.counter.getAndIncrement()); final Path hdfsTestDir = new Path(testdir); try { TestDFSShell.dfs.mkdirs(hdfsTestDir); localFile.createNewFile(); localFile.setReadable(false); TestDFSShell.writeFile(TestDFSShell.dfs, new Path(testdir, "testFileForPut")); shell = new FsShell(); // capture system error messages, snarfed from testErrOutPut() bak = System.err; ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream tmp = new PrintStream(out); System.setErr(tmp); // Tests for put String[] argv = new String[]{ "-put", localfilepath, testdir }; int res = ToolRunner.run(shell, argv); Assert.assertEquals("put is working", ERROR, res); String returned = out.toString(); Assert.assertTrue(" outputs Permission denied error message", ((returned.lastIndexOf("Permission denied")) != (-1))); // Tests for copyFromLocal argv = new String[]{ "-copyFromLocal", localfilepath, testdir }; res = ToolRunner.run(shell, argv); Assert.assertEquals("copyFromLocal -f is working", ERROR, res); returned = out.toString(); Assert.assertTrue(" outputs Permission denied error message", ((returned.lastIndexOf("Permission denied")) != (-1))); } finally { if (bak != null) { System.setErr(bak); } if (null != shell) shell.close(); if (localFile.exists()) localFile.delete(); TestDFSShell.dfs.delete(hdfsTestDir, true); } } /** * Test -setrep with a replication factor that is too low. We have to test * this here because the mini-miniCluster used with testHDFSConf.xml uses a * replication factor of 1 (for good reason). */ @Test(timeout = 30000) public void testSetrepLow() throws Exception { Configuration conf = new Configuration(); conf.setInt(DFS_NAMENODE_REPLICATION_MIN_KEY, 2); MiniDFSCluster.Builder builder = new MiniDFSCluster.Builder(conf); MiniDFSCluster cluster = builder.numDataNodes(2).format(true).build(); FsShell shell = new FsShell(conf); cluster.waitActive(); final String testdir = "/tmp/TestDFSShell-testSetrepLow"; final Path hdfsFile = new Path(testdir, "testFileForSetrepLow"); final PrintStream origOut = System.out; final PrintStream origErr = System.err; try { final FileSystem fs = cluster.getFileSystem(); Assert.assertTrue("Unable to create test directory", fs.mkdirs(new Path(testdir))); fs.create(hdfsFile, true).close(); // Capture the command output so we can examine it final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final PrintStream capture = new PrintStream(bao); System.setOut(capture); System.setErr(capture); final String[] argv = new String[]{ "-setrep", "1", hdfsFile.toString() }; try { Assert.assertEquals("Command did not return the expected exit code", 1, shell.run(argv)); } finally { System.setOut(origOut); System.setErr(origErr); } Assert.assertTrue(("Error message is not the expected error message" + (bao.toString())), bao.toString().startsWith(("setrep: Requested replication factor of 1 is less than " + ("the required minimum of 2 for /tmp/TestDFSShell-" + "testSetrepLow/testFileForSetrepLow")))); } finally { shell.close(); cluster.shutdown(); } } // setrep for file and directory. @Test(timeout = 30000) public void testSetrep() throws Exception { FsShell shell = null; final String testdir1 = "/tmp/TestDFSShell-testSetrep-" + (TestDFSShell.counter.getAndIncrement()); final String testdir2 = testdir1 + "/nestedDir"; final Path hdfsFile1 = new Path(testdir1, "testFileForSetrep"); final Path hdfsFile2 = new Path(testdir2, "testFileForSetrep"); final Short oldRepFactor = new Short(((short) (2))); final Short newRepFactor = new Short(((short) (3))); try { String[] argv; Assert.assertThat(TestDFSShell.dfs.mkdirs(new Path(testdir2)), CoreMatchers.is(true)); shell = new FsShell(TestDFSShell.dfs.getConf()); TestDFSShell.dfs.create(hdfsFile1, true).close(); TestDFSShell.dfs.create(hdfsFile2, true).close(); // Tests for setrep on a file. argv = new String[]{ "-setrep", newRepFactor.toString(), hdfsFile1.toString() }; Assert.assertThat(shell.run(argv), CoreMatchers.is(SUCCESS)); Assert.assertThat(TestDFSShell.dfs.getFileStatus(hdfsFile1).getReplication(), CoreMatchers.is(newRepFactor)); Assert.assertThat(TestDFSShell.dfs.getFileStatus(hdfsFile2).getReplication(), CoreMatchers.is(oldRepFactor)); // Tests for setrep // Tests for setrep on a directory and make sure it is applied recursively. argv = new String[]{ "-setrep", newRepFactor.toString(), testdir1 }; Assert.assertThat(shell.run(argv), CoreMatchers.is(SUCCESS)); Assert.assertThat(TestDFSShell.dfs.getFileStatus(hdfsFile1).getReplication(), CoreMatchers.is(newRepFactor)); Assert.assertThat(TestDFSShell.dfs.getFileStatus(hdfsFile2).getReplication(), CoreMatchers.is(newRepFactor)); } finally { if (shell != null) { shell.close(); } } } @Test(timeout = 300000) public void testAppendToFile() throws Exception { final int inputFileLength = 1024 * 1024; File testRoot = new File(TestDFSShell.TEST_ROOT_DIR, "testAppendtoFileDir"); testRoot.mkdirs(); File file1 = new File(testRoot, "file1"); File file2 = new File(testRoot, "file2"); TestDFSShell.createLocalFileWithRandomData(inputFileLength, file1); TestDFSShell.createLocalFileWithRandomData(inputFileLength, file2); Configuration conf = new HdfsConfiguration(); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).build(); cluster.waitActive(); try { FileSystem dfs = cluster.getFileSystem(); Assert.assertTrue(("Not a HDFS: " + (getUri())), (dfs instanceof DistributedFileSystem)); // Run appendToFile once, make sure that the target file is // created and is of the right size. Path remoteFile = new Path("/remoteFile"); FsShell shell = new FsShell(); shell.setConf(conf); String[] argv = new String[]{ "-appendToFile", file1.toString(), file2.toString(), remoteFile.toString() }; int res = ToolRunner.run(shell, argv); Assert.assertThat(res, CoreMatchers.is(0)); Assert.assertThat(dfs.getFileStatus(remoteFile).getLen(), CoreMatchers.is((((long) (inputFileLength)) * 2))); // Run the command once again and make sure that the target file // size has been doubled. res = ToolRunner.run(shell, argv); Assert.assertThat(res, CoreMatchers.is(0)); Assert.assertThat(dfs.getFileStatus(remoteFile).getLen(), CoreMatchers.is((((long) (inputFileLength)) * 4))); } finally { cluster.shutdown(); } } @Test(timeout = 300000) public void testAppendToFileBadArgs() throws Exception { final int inputFileLength = 1024 * 1024; File testRoot = new File(TestDFSShell.TEST_ROOT_DIR, "testAppendToFileBadArgsDir"); testRoot.mkdirs(); File file1 = new File(testRoot, "file1"); TestDFSShell.createLocalFileWithRandomData(inputFileLength, file1); // Run appendToFile with insufficient arguments. FsShell shell = new FsShell(); shell.setConf(TestDFSShell.dfs.getConf()); String[] argv = new String[]{ "-appendToFile", file1.toString() }; int res = ToolRunner.run(shell, argv); Assert.assertThat(res, CoreMatchers.not(0)); // Mix stdin with other input files. Must fail. Path remoteFile = new Path("/remoteFile"); argv = new String[]{ "-appendToFile", file1.toString(), "-", remoteFile.toString() }; res = ToolRunner.run(shell, argv); Assert.assertThat(res, CoreMatchers.not(0)); } @Test(timeout = 30000) public void testSetXAttrPermission() throws Exception { UserGroupInformation user = UserGroupInformation.createUserForTesting("user", new String[]{ "mygroup" }); PrintStream bak = null; try { Path p = new Path("/foo"); TestDFSShell.dfs.mkdirs(p); bak = System.err; final FsShell fshell = new FsShell(TestDFSShell.dfs.getConf()); final ByteArrayOutputStream out = new ByteArrayOutputStream(); System.setErr(new PrintStream(out)); // No permission to write xattr TestDFSShell.dfs.setPermission(p, new FsPermission(((short) (448)))); user.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { int ret = ToolRunner.run(fshell, new String[]{ "-setfattr", "-n", "user.a1", "-v", "1234", "/foo" }); Assert.assertEquals("Returned should be 1", 1, ret); String str = out.toString(); Assert.assertTrue("Permission denied printed", ((str.indexOf("Permission denied")) != (-1))); out.reset(); return null; } }); int ret = ToolRunner.run(fshell, new String[]{ "-setfattr", "-n", "user.a1", "-v", "1234", "/foo" }); Assert.assertEquals("Returned should be 0", 0, ret); out.reset(); // No permission to read and remove TestDFSShell.dfs.setPermission(p, new FsPermission(((short) (488)))); user.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { // Read int ret = ToolRunner.run(fshell, new String[]{ "-getfattr", "-n", "user.a1", "/foo" }); Assert.assertEquals("Returned should be 1", 1, ret); String str = out.toString(); Assert.assertTrue("Permission denied printed", ((str.indexOf("Permission denied")) != (-1))); out.reset(); // Remove ret = ToolRunner.run(fshell, new String[]{ "-setfattr", "-x", "user.a1", "/foo" }); Assert.assertEquals("Returned should be 1", 1, ret); str = out.toString(); Assert.assertTrue("Permission denied printed", ((str.indexOf("Permission denied")) != (-1))); out.reset(); return null; } }); } finally { if (bak != null) { System.setErr(bak); } } } /* HDFS-6413 xattr names erroneously handled as case-insensitive */ @Test(timeout = 30000) public void testSetXAttrCaseSensitivity() throws Exception { PrintStream bak = null; try { Path p = new Path("/mydir"); TestDFSShell.dfs.mkdirs(p); bak = System.err; final FsShell fshell = new FsShell(TestDFSShell.dfs.getConf()); final ByteArrayOutputStream out = new ByteArrayOutputStream(); System.setOut(new PrintStream(out)); doSetXattr(out, fshell, new String[]{ "-setfattr", "-n", "User.Foo", "/mydir" }, new String[]{ "-getfattr", "-d", "/mydir" }, new String[]{ "user.Foo" }, new String[]{ }); doSetXattr(out, fshell, new String[]{ "-setfattr", "-n", "user.FOO", "/mydir" }, new String[]{ "-getfattr", "-d", "/mydir" }, new String[]{ "user.Foo", "user.FOO" }, new String[]{ }); doSetXattr(out, fshell, new String[]{ "-setfattr", "-n", "USER.foo", "/mydir" }, new String[]{ "-getfattr", "-d", "/mydir" }, new String[]{ "user.Foo", "user.FOO", "user.foo" }, new String[]{ }); doSetXattr(out, fshell, new String[]{ "-setfattr", "-n", "USER.fOo", "-v", "myval", "/mydir" }, new String[]{ "-getfattr", "-d", "/mydir" }, new String[]{ "user.Foo", "user.FOO", "user.foo", "user.fOo=\"myval\"" }, new String[]{ "user.Foo=", "user.FOO=", "user.foo=" }); doSetXattr(out, fshell, new String[]{ "-setfattr", "-x", "useR.foo", "/mydir" }, new String[]{ "-getfattr", "-d", "/mydir" }, new String[]{ "user.Foo", "user.FOO" }, new String[]{ "foo" }); doSetXattr(out, fshell, new String[]{ "-setfattr", "-x", "USER.FOO", "/mydir" }, new String[]{ "-getfattr", "-d", "/mydir" }, new String[]{ "user.Foo" }, new String[]{ "FOO" }); doSetXattr(out, fshell, new String[]{ "-setfattr", "-x", "useR.Foo", "/mydir" }, new String[]{ "-getfattr", "-n", "User.Foo", "/mydir" }, new String[]{ }, new String[]{ "Foo" }); } finally { if (bak != null) { System.setOut(bak); } } } /** * Test to make sure that user namespace xattrs can be set only if path has * access and for sticky directorries, only owner/privileged user can write. * Trusted namespace xattrs can be set only with privileged users. * * As user1: Create a directory (/foo) as user1, chown it to user1 (and * user1's group), grant rwx to "other". * * As user2: Set an xattr (should pass with path access). * * As user1: Set an xattr (should pass). * * As user2: Read the xattr (should pass). Remove the xattr (should pass with * path access). * * As user1: Read the xattr (should pass). Remove the xattr (should pass). * * As user1: Change permissions only to owner * * As User2: Set an Xattr (Should fail set with no path access) Remove an * Xattr (Should fail with no path access) * * As SuperUser: Set an Xattr with Trusted (Should pass) */ @Test(timeout = 30000) public void testSetXAttrPermissionAsDifferentOwner() throws Exception { final String root = "/testSetXAttrPermissionAsDifferentOwner"; final String USER1 = "user1"; final String GROUP1 = "supergroup"; final UserGroupInformation user1 = UserGroupInformation.createUserForTesting(USER1, new String[]{ GROUP1 }); final UserGroupInformation user2 = UserGroupInformation.createUserForTesting("user2", new String[]{ "mygroup2" }); final UserGroupInformation SUPERUSER = UserGroupInformation.getCurrentUser(); PrintStream bak = null; try { TestDFSShell.dfs.mkdirs(new Path(root)); TestDFSShell.dfs.setOwner(new Path(root), USER1, GROUP1); bak = System.err; final FsShell fshell = new FsShell(TestDFSShell.dfs.getConf()); final ByteArrayOutputStream out = new ByteArrayOutputStream(); System.setErr(new PrintStream(out)); // Test 1. Let user1 be owner for /foo user1.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { final int ret = ToolRunner.run(fshell, new String[]{ "-mkdir", root + "/foo" }); Assert.assertEquals("Return should be 0", 0, ret); out.reset(); return null; } }); // Test 2. Give access to others user1.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { // Give access to "other" final int ret = ToolRunner.run(fshell, new String[]{ "-chmod", "707", root + "/foo" }); Assert.assertEquals("Return should be 0", 0, ret); out.reset(); return null; } }); // Test 3. Should be allowed to write xattr if there is a path access to // user (user2). user2.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { final int ret = ToolRunner.run(fshell, new String[]{ "-setfattr", "-n", "user.a1", "-v", "1234", root + "/foo" }); Assert.assertEquals("Returned should be 0", 0, ret); out.reset(); return null; } }); // Test 4. There should be permission to write xattr for // the owning user with write permissions. user1.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { final int ret = ToolRunner.run(fshell, new String[]{ "-setfattr", "-n", "user.a1", "-v", "1234", root + "/foo" }); Assert.assertEquals("Returned should be 0", 0, ret); out.reset(); return null; } }); // Test 5. There should be permission to read non-owning user (user2) if // there is path access to that user and also can remove. user2.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { // Read int ret = ToolRunner.run(fshell, new String[]{ "-getfattr", "-n", "user.a1", root + "/foo" }); Assert.assertEquals("Returned should be 0", 0, ret); out.reset(); // Remove ret = ToolRunner.run(fshell, new String[]{ "-setfattr", "-x", "user.a1", root + "/foo" }); Assert.assertEquals("Returned should be 0", 0, ret); out.reset(); return null; } }); // Test 6. There should be permission to read/remove for // the owning user with path access. user1.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { return null; } }); // Test 7. Change permission to have path access only to owner(user1) user1.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { // Give access to "other" final int ret = ToolRunner.run(fshell, new String[]{ "-chmod", "700", root + "/foo" }); Assert.assertEquals("Return should be 0", 0, ret); out.reset(); return null; } }); // Test 8. There should be no permissions to set for // the non-owning user with no path access. user2.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { // set int ret = ToolRunner.run(fshell, new String[]{ "-setfattr", "-n", "user.a2", root + "/foo" }); Assert.assertEquals("Returned should be 1", 1, ret); final String str = out.toString(); Assert.assertTrue("Permission denied printed", ((str.indexOf("Permission denied")) != (-1))); out.reset(); return null; } }); // Test 9. There should be no permissions to remove for // the non-owning user with no path access. user2.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { // set int ret = ToolRunner.run(fshell, new String[]{ "-setfattr", "-x", "user.a2", root + "/foo" }); Assert.assertEquals("Returned should be 1", 1, ret); final String str = out.toString(); Assert.assertTrue("Permission denied printed", ((str.indexOf("Permission denied")) != (-1))); out.reset(); return null; } }); // Test 10. Superuser should be allowed to set with trusted namespace SUPERUSER.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { // set int ret = ToolRunner.run(fshell, new String[]{ "-setfattr", "-n", "trusted.a3", root + "/foo" }); Assert.assertEquals("Returned should be 0", 0, ret); out.reset(); return null; } }); } finally { if (bak != null) { System.setErr(bak); } } } /* 1. Test that CLI throws an exception and returns non-0 when user does not have permission to read an xattr. 2. Test that CLI throws an exception and returns non-0 when a non-existent xattr is requested. */ @Test(timeout = 120000) public void testGetFAttrErrors() throws Exception { final UserGroupInformation user = UserGroupInformation.createUserForTesting("user", new String[]{ "mygroup" }); PrintStream bakErr = null; try { final Path p = new Path("/testGetFAttrErrors"); TestDFSShell.dfs.mkdirs(p); bakErr = System.err; final FsShell fshell = new FsShell(TestDFSShell.dfs.getConf()); final ByteArrayOutputStream out = new ByteArrayOutputStream(); System.setErr(new PrintStream(out)); // No permission for "other". TestDFSShell.dfs.setPermission(p, new FsPermission(((short) (448)))); { final int ret = ToolRunner.run(fshell, new String[]{ "-setfattr", "-n", "user.a1", "-v", "1234", p.toString() }); Assert.assertEquals("Returned should be 0", 0, ret); out.reset(); } user.doAs(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { int ret = ToolRunner.run(fshell, new String[]{ "-getfattr", "-n", "user.a1", p.toString() }); String str = out.toString(); Assert.assertTrue("xattr value was incorrectly returned", ((str.indexOf("1234")) == (-1))); out.reset(); return null; } }); { final int ret = ToolRunner.run(fshell, new String[]{ "-getfattr", "-n", "user.nonexistent", p.toString() }); String str = out.toString(); Assert.assertTrue("xattr value was incorrectly returned", ((str.indexOf("getfattr: At least one of the attributes provided was not found")) >= 0)); out.reset(); } } finally { if (bakErr != null) { System.setErr(bakErr); } } } /** * Test that the server trash configuration is respected when * the client configuration is not set. */ @Test(timeout = 30000) public void testServerConfigRespected() throws Exception { deleteFileUsingTrash(true, false); } /** * Test that server trash configuration is respected even when the * client configuration is set. */ @Test(timeout = 30000) public void testServerConfigRespectedWithClient() throws Exception { deleteFileUsingTrash(true, true); } /** * Test that the client trash configuration is respected when * the server configuration is not set. */ @Test(timeout = 30000) public void testClientConfigRespected() throws Exception { deleteFileUsingTrash(false, true); } /** * Test that trash is disabled by default. */ @Test(timeout = 30000) public void testNoTrashConfig() throws Exception { deleteFileUsingTrash(false, false); } @Test(timeout = 30000) public void testListReserved() throws IOException { Configuration conf = new HdfsConfiguration(); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build(); FileSystem fs = cluster.getFileSystem(); FsShell shell = new FsShell(); shell.setConf(conf); FileStatus test = fs.getFileStatus(new Path("/.reserved")); Assert.assertEquals(DOT_RESERVED_STRING, test.getPath().getName()); // Listing /.reserved/ should show 2 items: raw and .inodes FileStatus[] stats = fs.listStatus(new Path("/.reserved")); Assert.assertEquals(2, stats.length); Assert.assertEquals(DOT_INODES_STRING, stats[0].getPath().getName()); Assert.assertEquals(conf.get(DFS_PERMISSIONS_SUPERUSERGROUP_KEY), stats[0].getGroup()); Assert.assertEquals("raw", stats[1].getPath().getName()); Assert.assertEquals(conf.get(DFS_PERMISSIONS_SUPERUSERGROUP_KEY), stats[1].getGroup()); // Listing / should not show /.reserved stats = fs.listStatus(new Path("/")); Assert.assertEquals(0, stats.length); // runCmd prints error into System.err, thus verify from there. PrintStream syserr = System.err; final ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); System.setErr(ps); try { TestDFSShell.runCmd(shell, "-ls", "/.reserved"); Assert.assertEquals(0, baos.toString().length()); TestDFSShell.runCmd(shell, "-ls", "/.reserved/raw/.reserved"); Assert.assertTrue(baos.toString().contains("No such file or directory")); } finally { System.setErr(syserr); cluster.shutdown(); } } @Test(timeout = 30000) public void testMkdirReserved() throws IOException { try { TestDFSShell.dfs.mkdirs(new Path("/.reserved")); Assert.fail("Can't mkdir /.reserved"); } catch (Exception e) { // Expected, HadoopIllegalArgumentException thrown from remote Assert.assertTrue(e.getMessage().contains("\".reserved\" is reserved")); } } @Test(timeout = 30000) public void testRmReserved() throws IOException { try { TestDFSShell.dfs.delete(new Path("/.reserved"), true); Assert.fail("Can't delete /.reserved"); } catch (Exception e) { // Expected, InvalidPathException thrown from remote Assert.assertTrue(e.getMessage().contains("Invalid path name /.reserved")); } } // (timeout = 30000) @Test public void testCopyReserved() throws IOException { final File localFile = new File(TestDFSShell.TEST_ROOT_DIR, "testFileForPut"); localFile.createNewFile(); final String localfilepath = new Path(localFile.getAbsolutePath()).toUri().toString(); try { TestDFSShell.dfs.copyFromLocalFile(new Path(localfilepath), new Path("/.reserved")); Assert.fail("Can't copyFromLocal to /.reserved"); } catch (Exception e) { // Expected, InvalidPathException thrown from remote Assert.assertTrue(e.getMessage().contains("Invalid path name /.reserved")); } final String testdir = GenericTestUtils.getTempPath("TestDFSShell-testCopyReserved"); final Path hdfsTestDir = new Path(testdir); TestDFSShell.writeFile(TestDFSShell.dfs, new Path(testdir, "testFileForPut")); final Path src = new Path(hdfsTestDir, "srcfile"); TestDFSShell.dfs.create(src).close(); Assert.assertTrue(TestDFSShell.dfs.exists(src)); // runCmd prints error into System.err, thus verify from there. PrintStream syserr = System.err; final ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); System.setErr(ps); try { FsShell shell = new FsShell(TestDFSShell.dfs.getConf()); TestDFSShell.runCmd(shell, "-cp", src.toString(), "/.reserved"); Assert.assertTrue(baos.toString().contains("Invalid path name /.reserved")); } finally { System.setErr(syserr); } } @Test(timeout = 30000) public void testChmodReserved() throws IOException { // runCmd prints error into System.err, thus verify from there. PrintStream syserr = System.err; final ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); System.setErr(ps); try { FsShell shell = new FsShell(TestDFSShell.dfs.getConf()); TestDFSShell.runCmd(shell, "-chmod", "777", "/.reserved"); Assert.assertTrue(baos.toString().contains("Invalid path name /.reserved")); } finally { System.setErr(syserr); } } @Test(timeout = 30000) public void testChownReserved() throws IOException { // runCmd prints error into System.err, thus verify from there. PrintStream syserr = System.err; final ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); System.setErr(ps); try { FsShell shell = new FsShell(TestDFSShell.dfs.getConf()); TestDFSShell.runCmd(shell, "-chown", "user1", "/.reserved"); Assert.assertTrue(baos.toString().contains("Invalid path name /.reserved")); } finally { System.setErr(syserr); } } @Test(timeout = 30000) public void testSymLinkReserved() throws IOException { try { TestDFSShell.dfs.createSymlink(new Path("/.reserved"), new Path("/rl1"), false); Assert.fail("Can't create symlink to /.reserved"); } catch (Exception e) { // Expected, InvalidPathException thrown from remote Assert.assertTrue(e.getMessage().contains("Invalid target name: /.reserved")); } } @Test(timeout = 30000) public void testSnapshotReserved() throws IOException { final Path reserved = new Path("/.reserved"); try { TestDFSShell.dfs.allowSnapshot(reserved); Assert.fail("Can't allow snapshot on /.reserved"); } catch (FileNotFoundException e) { Assert.assertTrue(e.getMessage().contains("Directory does not exist")); } try { TestDFSShell.dfs.createSnapshot(reserved, "snap"); Assert.fail("Can't create snapshot on /.reserved"); } catch (FileNotFoundException e) { Assert.assertTrue(e.getMessage().contains("Directory/File does not exist")); } } }
[ "benjamin.danglot@inria.fr" ]
benjamin.danglot@inria.fr
170f33b50662aa0883eec71a3bad48e94fdbe3ec
de2d2b955407d06269115dfb1558793967392f02
/bai10_session_cookie_trong_spring/bai_tap/create_product_cart/src/main/java/vn/codegym/controller/ProductController.java
fef78f3ad03b25d4777d083791081145c86e4d15
[]
no_license
khoa110298/NguyenKhoa_C0920G1_Module4
89ff3f29c10e395bee58da68ddde48b26c39fc48
cb26b558ed4b89043c1739b3a08669b82b1a0218
refs/heads/master
2023-02-21T01:02:45.837677
2021-01-28T08:06:54
2021-01-28T08:06:54
325,424,265
0
0
null
null
null
null
UTF-8
Java
false
false
782
java
package vn.codegym.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import vn.codegym.service.ProductService; @Controller @RequestMapping("/product") public class ProductController { @Autowired ProductService productService; @GetMapping({"", "/list"}) public String listProduct(Model model) { model.addAttribute("productList", productService.findAll()); return "/list"; } @GetMapping("{id}/view") public String formView(@PathVariable("id") Integer id, Model model) { model.addAttribute("product", productService.findById(id)); return "view"; } }
[ "nguyenkhoa15011998@gmail.com" ]
nguyenkhoa15011998@gmail.com
7a83cd283621432fe6b5fa50e64b06ff009d6846
df2cc5237efd95c9893cddc1dc345bde80b2319e
/ly-order/src/main/java/com/leyou/order/mapper/OrderDetailMapper.java
8038ace9f38660113c441139389a35417436e58b
[]
no_license
risero/leyou
2a32b0d396fac69f74a8c05d4108aa089ec51dd0
60eceb32a156c071c175690673d6b6bc4ea925f7
refs/heads/master
2022-12-22T06:13:20.020488
2019-05-24T00:57:29
2019-05-24T00:57:29
165,045,801
1
0
null
null
null
null
UTF-8
Java
false
false
188
java
package com.leyou.order.mapper; import com.leyou.common.mapper.BaseMapper; import com.leyou.order.pojo.OrderDetail; public interface OrderDetailMapper extends BaseMapper<OrderDetail>{ }
[ "risero/2628668412@qq.com" ]
risero/2628668412@qq.com
1c67d19f5fb281bb1d8df680763fdabc6e0e16f7
7541281283cc008353e48c5dc92c0b5ed87d77e1
/src/com/ricky/chinaairpollution/PreferenceConnector.java
11c86548dce658f16f02ef1150daff14b1eb5d71
[]
no_license
orickyp/China-Air-Pollution
b1a242879b841399f97de6cc69df2bf35fe458f5
5f91dd8338d15cf6cd990e7f8772fac02d9ea084
refs/heads/master
2021-01-13T02:08:02.000105
2014-01-29T10:19:57
2014-01-29T10:19:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,914
java
package com.ricky.chinaairpollution; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public class PreferenceConnector{ public static final int MODE = Context.MODE_PRIVATE; public static void writeBoolean(Context context, String key, boolean value) { getEditor(context).putBoolean(key, value).commit(); } public static boolean readBoolean(Context context, String key, boolean defValue) { return getPreferences(context).getBoolean(key, defValue); } public static void writeInteger(Context context, String key, int value) { getEditor(context).putInt(key, value).commit(); } public static int readInteger(Context context, String key, int defValue) { return getPreferences(context).getInt(key, defValue); } public static void writeString(Context context, String key, String value) { getEditor(context).putString(key, value).commit(); } public static String readString(Context context, String key, String defValue) { return getPreferences(context).getString(key, defValue); } public static void writeFloat(Context context, String key, float value) { getEditor(context).putFloat(key, value).commit(); } public static float readFloat(Context context, String key, float defValue) { return getPreferences(context).getFloat(key, defValue); } public static void writeLong(Context context, String key, long value) { getEditor(context).putLong(key, value).commit(); } public static long readLong(Context context, String key, long defValue) { return getPreferences(context).getLong(key, defValue); } public static SharedPreferences getPreferences(Context context) { return context.getSharedPreferences(Constants.PREF_NAME, MODE); } public static Editor getEditor(Context context) { return getPreferences(context).edit(); } }
[ "onesimus.ricky.personal@gmail.com" ]
onesimus.ricky.personal@gmail.com
cb7bb5cd8670369f7e79d39d916bc5d1db3867d7
221da31486cdaeab91b1ed4962ac4f693954e18d
/MyApplication/app/src/main/java/com/example/myapplication/MainActivity.java
5ddbc03e698c11f22a330c76181efcdcfde25f03
[]
no_license
Ralpinn/AudioRecord
abe57a2621130a39456a613f97f74db9262ef953
a10ce04c94e9070a30910f2ce8cd042d2634e0bf
refs/heads/master
2023-01-14T17:52:49.299257
2020-11-17T12:00:07
2020-11-17T12:00:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,528
java
package com.example.myapplication; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.LinearLayout; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentTransaction; import com.google.android.material.bottomnavigation.BottomNavigationView; public class MainActivity extends AppCompatActivity { BottomNavigationView bottomNavigationView; MenuItem menuItem; LinearLayout linearSearch; Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); linearSearch = findViewById(R.id.linearSreach); toolbar = findViewById(R.id.toolbar); bottomNavigationView = findViewById(R.id.bottom_nav); displayFragment(R.id.mnuInfo); bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { displayFragment(item.getItemId()); return true; } }); // setSupportActionBar(toolbar); } private void displayFragment(int itemId) { Fragment fragment = null; switch (itemId){ case R.id.mnuHome: toolbar.setVisibility(View.GONE); linearSearch.setVisibility(View.VISIBLE); fragment = new HomeFragment(); if(menuItem != null) { menuItem.setVisible(false); } break; case R.id.mnuAccount: toolbar.setVisibility(View.GONE); linearSearch.setVisibility(View.VISIBLE); fragment = new AccountFragment(); break; case R.id.mnuInfo: toolbar.setVisibility(View.VISIBLE); linearSearch.setVisibility(View.GONE); setSupportActionBar(toolbar); fragment = InfoFragment.newInstance("name", "name"); break; } FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.replace(R.id.content,fragment); ft.commit(); } }
[ "you@example.com" ]
you@example.com
303c2b97d1013d842bbd225559415b11095886cc
75c4712ae3f946db0c9196ee8307748231487e4b
/src/main/java/com/alipay/api/domain/KoubeiMarketingToolIsvMerchantQueryModel.java
0f773e5bf9216a7d9e588200b03071dc4e620e31
[ "Apache-2.0" ]
permissive
yuanbaoMarvin/alipay-sdk-java-all
70a72a969f464d79c79d09af8b6b01fa177ac1be
25f3003d820dbd0b73739d8e32a6093468d9ed92
refs/heads/master
2023-06-03T16:54:25.138471
2021-06-25T14:48:21
2021-06-25T14:48:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
819
java
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * ISV查询商户列表接口 * * @author auto create * @since 1.0, 2017-08-04 15:15:46 */ public class KoubeiMarketingToolIsvMerchantQueryModel extends AlipayObject { private static final long serialVersionUID = 5542822888334852492L; /** * 页码 */ @ApiField("page_num") private String pageNum; /** * 每页大小 */ @ApiField("page_size") private String pageSize; public String getPageNum() { return this.pageNum; } public void setPageNum(String pageNum) { this.pageNum = pageNum; } public String getPageSize() { return this.pageSize; } public void setPageSize(String pageSize) { this.pageSize = pageSize; } }
[ "ben.zy@antfin.com" ]
ben.zy@antfin.com
ceb3d5852e71bbb9ba82fe162a120f896bc7d745
7466500a4bb756a067fcf8d16efdc8b5f5e9beb5
/app/src/main/java/com/example/lamlethanhthe/studyhelper/MapsModules/DirectionFinderListener.java
a125db2c7bfd6fe5caf4b15b6fa6bb3a963193e5
[]
no_license
lltthe/studyhelper
9fe27579616b835caae206fd60c2218803343bdb
4491e8392109a844ec64a0cd7c0638e5bff80832
refs/heads/master
2020-03-18T19:31:53.109900
2018-05-28T12:55:10
2018-05-28T12:55:10
135,159,891
0
0
null
null
null
null
UTF-8
Java
false
false
269
java
package com.example.lamlethanhthe.studyhelper.MapsModules; import java.util.List; /** * Created by Mai Thanh Hiep on 4/3/2016. */ public interface DirectionFinderListener { void onDirectionFinderStart(); void onDirectionFinderSuccess(List<Route> route); }
[ "lltthe@apcs.vn" ]
lltthe@apcs.vn
a5515901793bce040e912fa219b6cc3cdb160947
a1826c2ed9c12cfc395fb1a14c1a2e1f097155cb
/domain-20180129/src/main/java/com/aliyun/domain20180129/models/QueryFailingReasonListForQualificationRequest.java
75067eb1303101c6acbd1c845b288db382f3fcff
[ "Apache-2.0" ]
permissive
aliyun/alibabacloud-java-sdk
83a6036a33c7278bca6f1bafccb0180940d58b0b
008923f156adf2e4f4785a0419f60640273854ec
refs/heads/master
2023-09-01T04:10:33.640756
2023-09-01T02:40:45
2023-09-01T02:40:45
288,968,318
40
45
null
2023-06-13T02:47:13
2020-08-20T09:51:08
Java
UTF-8
Java
false
false
1,933
java
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.domain20180129.models; import com.aliyun.tea.*; public class QueryFailingReasonListForQualificationRequest extends TeaModel { @NameInMap("InstanceId") public String instanceId; @NameInMap("Lang") public String lang; @NameInMap("Limit") public Integer limit; @NameInMap("QualificationType") public String qualificationType; @NameInMap("UserClientIp") public String userClientIp; public static QueryFailingReasonListForQualificationRequest build(java.util.Map<String, ?> map) throws Exception { QueryFailingReasonListForQualificationRequest self = new QueryFailingReasonListForQualificationRequest(); return TeaModel.build(map, self); } public QueryFailingReasonListForQualificationRequest setInstanceId(String instanceId) { this.instanceId = instanceId; return this; } public String getInstanceId() { return this.instanceId; } public QueryFailingReasonListForQualificationRequest setLang(String lang) { this.lang = lang; return this; } public String getLang() { return this.lang; } public QueryFailingReasonListForQualificationRequest setLimit(Integer limit) { this.limit = limit; return this; } public Integer getLimit() { return this.limit; } public QueryFailingReasonListForQualificationRequest setQualificationType(String qualificationType) { this.qualificationType = qualificationType; return this; } public String getQualificationType() { return this.qualificationType; } public QueryFailingReasonListForQualificationRequest setUserClientIp(String userClientIp) { this.userClientIp = userClientIp; return this; } public String getUserClientIp() { return this.userClientIp; } }
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
8ee5071eb8efea1c0e6c0e75b255d92a8d9b43c8
0426e3ca5c4ab793305cfdfc648c914305f3ab6a
/app/src/test/java/com/example/fyl/androidtest/ExampleUnitTest.java
fdb586792a6805e0f6c011d877cf7a9d90b0ef0e
[]
no_license
fuyanli/VersionTest
a400eb50e000bee738aa0cd6b2e3f1172fed25f3
76875ee8e995aca9745c548903b8df17263ff234
refs/heads/master
2021-01-13T03:34:07.934510
2016-12-25T08:52:45
2016-12-25T08:52:45
77,313,105
0
0
null
null
null
null
UTF-8
Java
false
false
405
java
package com.example.fyl.androidtest; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
[ "1289525342@qq.com" ]
1289525342@qq.com
aa7d863199460ca7e99ebe4e7c8124ea82f81de3
4abcad5139f329a9182d5aded385ad6228a531ea
/src/main/java/project/model/Accounts.java
e2ee0e5d70c7083eae3f544ae0a065cc2442e062
[]
no_license
phongltth1807075/ProjectSpringPrivate
2e30bf0ce6c2fe758d2acd681ad31ef86b244ae2
f6a3a35a47bb8df907057c353071740d9ab0387d
refs/heads/master
2022-12-06T20:54:20.192598
2020-09-08T10:15:48
2020-09-08T10:15:48
293,818,134
0
0
null
null
null
null
UTF-8
Java
false
false
3,914
java
package project.model; import javax.persistence.*; import java.util.List; @Entity public class Accounts { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int accountId; private String accountName; private String phoneNumber; private String email; private String address; private long createdAt; private long updatedAt; private long deletedAt; private int gender; private long birthday; private int status; private String password; private String token; @OneToOne(mappedBy = "accounts") private Product product; @ManyToMany(cascade = CascadeType.MERGE,fetch = FetchType.EAGER) @JoinTable(name = "account_role", joinColumns = @JoinColumn(name = "accountId"), inverseJoinColumns = @JoinColumn(name = "roleId") ) private List<Roles> rolesList; public Accounts() { } public Accounts(String accountName, String phoneNumber, String email, String address, long createdAt, long updatedAt, long deletedAt, int gender, long birthday, int status, String password, String token, Product product, List<Roles> rolesList) { this.accountName = accountName; this.phoneNumber = phoneNumber; this.email = email; this.address = address; this.createdAt = createdAt; this.updatedAt = updatedAt; this.deletedAt = deletedAt; this.gender = gender; this.birthday = birthday; this.status = status; this.password = password; this.token = token; this.product = product; this.rolesList = rolesList; } public int getAccountId() { return accountId; } public void setAccountId(int accountId) { this.accountId = accountId; } public String getAccountName() { return accountName; } public void setAccountName(String accountName) { this.accountName = accountName; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public long getCreatedAt() { return createdAt; } public void setCreatedAt(long createdAt) { this.createdAt = createdAt; } public long getUpdatedAt() { return updatedAt; } public void setUpdatedAt(long updatedAt) { this.updatedAt = updatedAt; } public long getDeletedAt() { return deletedAt; } public void setDeletedAt(long deletedAt) { this.deletedAt = deletedAt; } public int getGender() { return gender; } public void setGender(int gender) { this.gender = gender; } public long getBirthday() { return birthday; } public void setBirthday(long birthday) { this.birthday = birthday; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } public List<Roles> getRolesList() { return rolesList; } public void setRolesList(List<Roles> rolesList) { this.rolesList = rolesList; } }
[ "phongltth1807075@fpt.edu.vn" ]
phongltth1807075@fpt.edu.vn
f315a7919a1d0aa835dba113c77429ee6b4c7f89
7c5eda5713c05ea19cb6c536aa3589114848a68d
/Casestudy01/src/test/java/c3/Runner.java
d1477fd58304e79d54cfde276f330aca4f683b6f
[]
no_license
sushmavn05/sush
679805e731e77d545fddb0cf88c653eea184d0c9
ac97f376094d34c357c0b93a8146492eec7b000a
refs/heads/master
2020-05-17T22:44:03.284715
2019-04-29T06:15:30
2019-04-29T06:15:30
184,010,999
0
0
null
null
null
null
UTF-8
Java
false
false
146
java
package c3; import org.junit.runner.RunWith; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) public class Runner { }
[ "Training_C2a.05.01@CDC2-D-4V8RX52.dir.svc.accenture.com" ]
Training_C2a.05.01@CDC2-D-4V8RX52.dir.svc.accenture.com
e06cb45b32521d61b221f7a8f3835d45d9b84772
69f98f9c73035e458b315bed2c1d43cc21f34e63
/app/src/main/java/net/gringrid/siso/fragments/Sitter03GenderChildrenFragment.java
c6a3c07014b3366d1faac1bfe75e1efc8628d09d
[]
no_license
GrinGrid/siso
31a80a392749d9a31796b330371b44aedca56b81
c36f246bec74f057806d07e7c0ed759dadc98653
refs/heads/master
2020-04-12T10:38:08.301944
2017-01-03T13:23:59
2017-01-03T13:23:59
63,205,105
0
0
null
null
null
null
UTF-8
Java
false
false
4,566
java
package net.gringrid.siso.fragments; import android.os.Bundle; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import net.gringrid.siso.BaseActivity; import net.gringrid.siso.R; import net.gringrid.siso.models.User; import net.gringrid.siso.util.SharedData; import net.gringrid.siso.util.SisoUtil; import net.gringrid.siso.views.SisoPicker; import net.gringrid.siso.views.SisoToggleButton; /** * 구직정보 등록 > 기본정보 > 성별, 자녀정보 */ public class Sitter03GenderChildrenFragment extends InputBaseFragment{ SisoToggleButton id_tg_btn_woman; SisoToggleButton id_tg_btn_man; int mRadioGender[] = new int[]{R.id.id_tg_btn_woman, R.id.id_tg_btn_man}; private TextView id_tv_next_btn; private SisoPicker id_pk_daughter; private SisoPicker id_pk_son; public Sitter03GenderChildrenFragment() { // Required empty public constructor } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_sitter03_gender_children, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { id_tv_next_btn = (TextView)view.findViewById(R.id.id_tv_next_btn); id_tv_next_btn.setOnClickListener(this); id_tg_btn_woman = (SisoToggleButton)view.findViewById(R.id.id_tg_btn_woman); id_tg_btn_man = (SisoToggleButton)view.findViewById(R.id.id_tg_btn_man); id_tg_btn_man.setOnClickListener(this); id_tg_btn_woman.setOnClickListener(this); id_pk_daughter = (SisoPicker)view.findViewById(R.id.id_pk_daughter); id_pk_son = (SisoPicker)view.findViewById(R.id.id_pk_son); loadData(); super.onViewCreated(view, savedInstanceState); } @Override public void onClick(View v) { Log.d(TAG, "onClick: sitter2"); switch (v.getId()){ case R.id.id_tv_next_btn: if(!isValidInput()) return; saveData(); moveNext(); break; case R.id.id_tg_btn_woman: SisoUtil.selectRadio(mRadioGender, R.id.id_tg_btn_woman, getView()); break; case R.id.id_tg_btn_man: SisoUtil.selectRadio(mRadioGender, R.id.id_tg_btn_man, getView()); break; } } @Override protected void loadData() { if(mUser.sitterInfo==null) return; if(!TextUtils.isEmpty(mUser.sitterInfo.gender)){ if(mUser.sitterInfo.gender.equals(User.GENDER_WOMAN)){ id_tg_btn_woman.setChecked(true); }else if(mUser.sitterInfo.gender.equals(User.GENDER_MAN)){ id_tg_btn_man.setChecked(true); } } if(!TextUtils.isEmpty(mUser.sitterInfo.daughters)){ id_pk_daughter.setIndex(Integer.parseInt(mUser.sitterInfo.daughters)); } if(!TextUtils.isEmpty(mUser.sitterInfo.sons)) { id_pk_son.setIndex(Integer.parseInt(mUser.sitterInfo.sons)); } } @Override protected boolean isValidInput() { if(!SisoUtil.isRadioGroupSelected(mRadioGender, getView())){ SisoUtil.showErrorMsg(getContext(), R.string.invalid_gender_select); return false; } return true; } @Override protected void saveData() { int gender = SisoUtil.getRadioValue(mRadioGender, getView()); int daughterNum = id_pk_daughter.getCurrentIndex(); int sonNum = id_pk_son.getCurrentIndex(); mUser.sitterInfo.gender = String.valueOf(gender); mUser.sitterInfo.daughters = String.valueOf(daughterNum); mUser.sitterInfo.sons = String.valueOf(sonNum); Log.d(TAG, "onClick: mUser.sitterInfo : "+mUser.sitterInfo.toString()); SharedData.getInstance(getContext()).setObjectData(SharedData.USER, mUser); } @Override protected void moveNext() { CommonSkillFragment fragment = new CommonSkillFragment(); ((BaseActivity) getActivity()).setFragment(fragment, R.string.sitter_basic_title); } }
[ "choijiho.korea@gmail.com" ]
choijiho.korea@gmail.com
b89ba8308d7921966930d03268708462ed2a7c02
2d323b2fd7f40217d5c8bb8eb12614dcb4c0284f
/src/main/java/com/kudl/sidekick/pattern/observer/Observer.java
c9719d15e440b5b0d6f7d6c0595b4941062edf73
[]
no_license
kudl/sidekick
a3105f7b8fb39112f44019cfbbc9139c206d6622
813f5df8be6cce2a2f08746af2208af745320968
refs/heads/main
2023-03-30T01:11:18.721251
2021-04-10T15:13:31
2021-04-10T15:13:31
309,612,768
0
0
null
null
null
null
UTF-8
Java
false
false
144
java
package com.kudl.sidekick.pattern.observer; public interface Observer { // Observer == Subscriber == Listener void update(String message); }
[ "yoocm1229@naver.com" ]
yoocm1229@naver.com
07e6de543872b7b3d8acb468c0e127a3b83ce097
e033c5750927060bcb30caa19e5f896f3de6dbd6
/event-hook-example/src/main/java/com/nexse/swat/liferay/examples/hook/example2/GlobalPreEventAction.java
bb34cbadf756ca5174fcc213759c51e54a1a1fef
[]
no_license
ganeshvidyayug/liferay-playground
53c4c97f3b948a2373375c2a578554a0c80d2718
ecb3c915c1dd9d30878cbe8d1cf30e3c33d86d50
refs/heads/master
2020-04-19T16:13:55.150153
2012-09-26T14:50:57
2012-09-26T14:50:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
925
java
package com.nexse.swat.liferay.examples.hook.example2; import com.liferay.portal.kernel.events.Action; import com.liferay.portal.kernel.events.ActionException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class GlobalPreEventAction extends Action { private static final Log log = LogFactoryUtil.getLog(GlobalPreEventAction.class); @Override public void run(HttpServletRequest request, HttpServletResponse response) throws ActionException { final String answer = request.getHeader("answer"); log.info("answer=" + answer); if ("42".equals(answer)) { log.info("the answer is correct, you shall pass"); } else { throw new ActionException("the answer is incorrect, you shall not pass"); } } }
[ "mirko.caserta@gmail.com" ]
mirko.caserta@gmail.com
e932db581214e87c402aaa769690215c9738ad3c
a562cb15829e9e1097fa7ed062316863d4bdd198
/app/src/main/java/com/lidan/keylor/musicmaster/domain/Usecase.java
30c6f8fdbf743445d7532456a116fa1d80933cc7
[]
no_license
keylorsdu/MusicMaster
1971cfed77613082bb68ffdedd5e037daea50dc2
dd7bafd88b2399dcb08a955cbce7ebdce5560be3
refs/heads/master
2021-01-21T02:27:58.068917
2015-08-22T10:11:23
2015-08-22T10:11:23
38,816,770
0
0
null
null
null
null
UTF-8
Java
false
false
144
java
package com.lidan.keylor.musicmaster.domain; /** * Created by keylorlidan on 2015/8/16. */ public interface Usecase { void execute(); }
[ "sdukeylor@gmail.com" ]
sdukeylor@gmail.com