blob_id stringlengths 40 40 | __id__ int64 225 39,780B | directory_id stringlengths 40 40 | path stringlengths 6 313 | content_id stringlengths 40 40 | detected_licenses list | license_type stringclasses 2
values | repo_name stringlengths 6 132 | repo_url stringlengths 25 151 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 70 | visit_date timestamp[ns] | revision_date timestamp[ns] | committer_date timestamp[ns] | github_id int64 7.28k 689M ⌀ | star_events_count int64 0 131k | fork_events_count int64 0 48k | gha_license_id stringclasses 23
values | gha_fork bool 2
classes | gha_event_created_at timestamp[ns] | gha_created_at timestamp[ns] | gha_updated_at timestamp[ns] | gha_pushed_at timestamp[ns] | gha_size int64 0 40.4M ⌀ | gha_stargazers_count int32 0 112k ⌀ | gha_forks_count int32 0 39.4k ⌀ | gha_open_issues_count int32 0 11k ⌀ | gha_language stringlengths 1 21 ⌀ | gha_archived bool 2
classes | gha_disabled bool 1
class | content stringlengths 7 4.37M | src_encoding stringlengths 3 16 | language stringclasses 1
value | length_bytes int64 7 4.37M | extension stringclasses 24
values | filename stringlengths 4 174 | language_id stringclasses 1
value | entities list | contaminating_dataset stringclasses 0
values | malware_signatures list | redacted_content stringlengths 7 4.37M | redacted_length_bytes int64 7 4.37M | alphanum_fraction float32 0.25 0.94 | alpha_fraction float32 0.25 0.94 | num_lines int32 1 84k | avg_line_length float32 0.76 99.9 | std_line_length float32 0 220 | max_line_length int32 5 998 | is_vendor bool 2
classes | is_generated bool 1
class | max_hex_length int32 0 319 | hex_fraction float32 0 0.38 | max_unicode_length int32 0 408 | unicode_fraction float32 0 0.36 | max_base64_length int32 0 506 | base64_fraction float32 0 0.5 | avg_csv_sep_count float32 0 4 | is_autogen_header bool 1
class | is_empty_html bool 1
class | shard stringclasses 16
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dc8fff8f1547137fb487075eaa7d723b3ce35c64 | 6,399,501,322,264 | eca03b1207a216553ea5c7d411e299b2559a50b6 | /app/src/main/java/com/apoorv/sharedpreferences/storage/SessionManager.java | 8ed7eac07949f64012261ec5e45b758e47c080d1 | [] | no_license | devapoorva/SharedPreferences | https://github.com/devapoorva/SharedPreferences | e9f443f09fede1d02c887463e0621ac781d91e4c | 3535e882d9dad23c340cd5c52f064a37707daa25 | refs/heads/master | 2023-05-26T01:20:01.419000 | 2019-11-26T10:16:54 | 2019-11-26T10:16:54 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.apoorv.sharedpreferences.storage;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by Apoorv Vardhman on 26-11-2019
*
* @Email : apoorv.vardhman@gmail.com
* @Author : developerapoorv.xyz
* @Linkedin : https://in.linkedin.com/in/apoorv-vardhman
* Contact : +91 8434014444
*/
public class SessionManager {
private Context context;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private static final String EMAIL = "Email";
private static final String PASSWORD = "password";
private static final String NAME = "name";
public SessionManager(Context context) {
this.context = context;
sharedPreferences = context.getSharedPreferences("user_sesion",Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
public void register(String email,String password,String name)
{
editor.putString(NAME,name);
editor.putString(EMAIL,email);
editor.putString(PASSWORD,password);
editor.apply();
}
public String getEmail()
{
return sharedPreferences.getString(EMAIL,"");
}
public String getPassword()
{
return sharedPreferences.getString(PASSWORD,"");
}
public String getName()
{
return sharedPreferences.getString(NAME,"");
}
public void clearData()
{
editor.clear();
editor.commit();
editor.apply();
}
}
| UTF-8 | Java | 1,501 | java | SessionManager.java | Java | [
{
"context": "roid.content.SharedPreferences;\n\n/**\n * Created by Apoorv Vardhman on 26-11-2019\n *\n * @Email : apoorv.vardhman@gma",
"end": 155,
"score": 0.9998981952667236,
"start": 140,
"tag": "NAME",
"value": "Apoorv Vardhman"
},
{
"context": "d by Apoorv Vardhman on 26-11-20... | null | [] | package com.apoorv.sharedpreferences.storage;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by <NAME> on 26-11-2019
*
* @Email : <EMAIL>
* @Author : developerapoorv.xyz
* @Linkedin : https://in.linkedin.com/in/apoorv-vardhman
* Contact : +91 8434014444
*/
public class SessionManager {
private Context context;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private static final String EMAIL = "Email";
private static final String PASSWORD = "<PASSWORD>";
private static final String NAME = "name";
public SessionManager(Context context) {
this.context = context;
sharedPreferences = context.getSharedPreferences("user_sesion",Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
public void register(String email,String password,String name)
{
editor.putString(NAME,name);
editor.putString(EMAIL,email);
editor.putString(PASSWORD,<PASSWORD>);
editor.apply();
}
public String getEmail()
{
return sharedPreferences.getString(EMAIL,"");
}
public String getPassword()
{
return sharedPreferences.getString(PASSWORD,"");
}
public String getName()
{
return sharedPreferences.getString(NAME,"");
}
public void clearData()
{
editor.clear();
editor.commit();
editor.apply();
}
}
| 1,478 | 0.666223 | 0.652898 | 62 | 23.209677 | 21.869951 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 8 |
1d2de162c24cd04c0288213e10194c88ee2ec4a1 | 4,045,859,220,606 | 6a597baf199abf73d0e9e04fb8a6fd8f1e4b86c7 | /src/main/java/io/protostuff/runtime/DefaultIdStrategy.java | ff2e5f07b8b8e932e8dd6fbe4ab90f9fac7a2153 | [] | no_license | MrWhyWu/kingShow | https://github.com/MrWhyWu/kingShow | 63645e25ca8a26429268cd5e96f6a4c9f88ec001 | b6daaeafd5a887e8229fee287169ab1de208e547 | refs/heads/master | 2022-05-15T00:30:22.586000 | 2022-05-06T07:51:46 | 2022-05-06T07:51:46 | 150,571,946 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /* 1: */ package io.protostuff.runtime;
/* 2: */
/* 3: */ import io.protostuff.CollectionSchema.MessageFactories;
/* 4: */ import io.protostuff.CollectionSchema.MessageFactory;
/* 5: */ import io.protostuff.Input;
/* 6: */ import io.protostuff.MapSchema.MessageFactories;
/* 7: */ import io.protostuff.MapSchema.MessageFactory;
/* 8: */ import io.protostuff.Message;
/* 9: */ import io.protostuff.Output;
/* 10: */ import io.protostuff.Pipe.Schema;
/* 11: */ import io.protostuff.ProtostuffException;
/* 12: */ import io.protostuff.Schema;
/* 13: */ import java.io.IOException;
/* 14: */ import java.lang.reflect.Modifier;
/* 15: */ import java.util.Collection;
/* 16: */ import java.util.Map;
/* 17: */ import java.util.concurrent.ConcurrentHashMap;
/* 18: */
/* 19: */ public final class DefaultIdStrategy
/* 20: */ extends IdStrategy
/* 21: */ {
/* 22: 36 */ final ConcurrentHashMap<String, HasSchema<?>> pojoMapping = new ConcurrentHashMap();
/* 23: 38 */ final ConcurrentHashMap<String, EnumIO<?>> enumMapping = new ConcurrentHashMap();
/* 24: 40 */ final ConcurrentHashMap<String, CollectionSchema.MessageFactory> collectionMapping = new ConcurrentHashMap();
/* 25: 42 */ final ConcurrentHashMap<String, MapSchema.MessageFactory> mapMapping = new ConcurrentHashMap();
/* 26: 44 */ final ConcurrentHashMap<String, HasDelegate<?>> delegateMapping = new ConcurrentHashMap();
/* 27: */
/* 28: */ public DefaultIdStrategy()
/* 29: */ {
/* 30: 48 */ super(DEFAULT_FLAGS, null, 0);
/* 31: */ }
/* 32: */
/* 33: */ public DefaultIdStrategy(IdStrategy primaryGroup, int groupId)
/* 34: */ {
/* 35: 53 */ super(DEFAULT_FLAGS, primaryGroup, groupId);
/* 36: */ }
/* 37: */
/* 38: */ public DefaultIdStrategy(int flags, IdStrategy primaryGroup, int groupId)
/* 39: */ {
/* 40: 58 */ super(flags, primaryGroup, groupId);
/* 41: */ }
/* 42: */
/* 43: */ public <T> boolean registerPojo(Class<T> typeClass, Schema<T> schema)
/* 44: */ {
/* 45: 67 */ assert ((typeClass != null) && (schema != null));
/* 46: */
/* 47: 69 */ HasSchema<?> last = (HasSchema)this.pojoMapping.putIfAbsent(typeClass.getName(), new Registered(schema, this));
/* 48: */
/* 49: */
/* 50: 72 */ return (last == null) || (((last instanceof Registered)) && (((Registered)last).schema == schema));
/* 51: */ }
/* 52: */
/* 53: */ public <T> boolean registerPojo(Class<T> typeClass)
/* 54: */ {
/* 55: 82 */ assert (typeClass != null);
/* 56: */
/* 57: 84 */ HasSchema<?> last = (HasSchema)this.pojoMapping.putIfAbsent(typeClass.getName(), new LazyRegister(typeClass, this));
/* 58: */
/* 59: */
/* 60: 87 */ return (last == null) || ((last instanceof LazyRegister));
/* 61: */ }
/* 62: */
/* 63: */ public <T extends Enum<T>> boolean registerEnum(Class<T> enumClass)
/* 64: */ {
/* 65: 95 */ return null == this.enumMapping.putIfAbsent(enumClass.getName(),
/* 66: 96 */ EnumIO.newEnumIO(enumClass, this));
/* 67: */ }
/* 68: */
/* 69: */ public <T> boolean registerDelegate(Delegate<T> delegate)
/* 70: */ {
/* 71:104 */ return null == this.delegateMapping.putIfAbsent(delegate.typeClass()
/* 72:105 */ .getName(), new HasDelegate(delegate, this));
/* 73: */ }
/* 74: */
/* 75: */ public boolean registerCollection(CollectionSchema.MessageFactory factory)
/* 76: */ {
/* 77:113 */ return null == this.collectionMapping.putIfAbsent(factory.typeClass()
/* 78:114 */ .getName(), factory);
/* 79: */ }
/* 80: */
/* 81: */ public boolean registerMap(MapSchema.MessageFactory factory)
/* 82: */ {
/* 83:122 */ return null == this.mapMapping.putIfAbsent(factory.typeClass().getName(), factory);
/* 84: */ }
/* 85: */
/* 86: */ public <T> boolean map(Class<? super T> baseClass, Class<T> typeClass)
/* 87: */ {
/* 88:131 */ assert ((baseClass != null) && (typeClass != null));
/* 89:133 */ if ((typeClass.isInterface()) ||
/* 90:134 */ (Modifier.isAbstract(typeClass.getModifiers()))) {
/* 91:136 */ throw new IllegalArgumentException(typeClass + " cannot be an interface/abstract class.");
/* 92: */ }
/* 93:140 */ HasSchema<?> last = (HasSchema)this.pojoMapping.putIfAbsent(baseClass.getName(), new Mapped(baseClass, typeClass, this));
/* 94: */
/* 95: */
/* 96:143 */ return (last == null) || (((last instanceof Mapped)) && (((Mapped)last).typeClass == typeClass));
/* 97: */ }
/* 98: */
/* 99: */ public boolean isDelegateRegistered(Class<?> typeClass)
/* 100: */ {
/* 101:150 */ return this.delegateMapping.containsKey(typeClass.getName());
/* 102: */ }
/* 103: */
/* 104: */ public <T> HasDelegate<T> getDelegateWrapper(Class<? super T> typeClass)
/* 105: */ {
/* 106:157 */ return (HasDelegate)this.delegateMapping.get(typeClass.getName());
/* 107: */ }
/* 108: */
/* 109: */ public <T> Delegate<T> getDelegate(Class<? super T> typeClass)
/* 110: */ {
/* 111:165 */ HasDelegate<T> last = (HasDelegate)this.delegateMapping.get(typeClass.getName());
/* 112:166 */ return last == null ? null : last.delegate;
/* 113: */ }
/* 114: */
/* 115: */ public boolean isRegistered(Class<?> typeClass)
/* 116: */ {
/* 117:172 */ HasSchema<?> last = (HasSchema)this.pojoMapping.get(typeClass.getName());
/* 118:173 */ return (last != null) && (!(last instanceof Lazy));
/* 119: */ }
/* 120: */
/* 121: */ private <T> HasSchema<T> getSchemaWrapper(String className, boolean load)
/* 122: */ {
/* 123:179 */ HasSchema<T> hs = (HasSchema)this.pojoMapping.get(className);
/* 124:180 */ if (hs == null)
/* 125: */ {
/* 126:182 */ if (!load) {
/* 127:183 */ return null;
/* 128: */ }
/* 129:185 */ Class<T> typeClass = RuntimeEnv.loadClass(className);
/* 130: */
/* 131:187 */ hs = new Lazy(typeClass, this);
/* 132:188 */ HasSchema<T> last = (HasSchema)this.pojoMapping.putIfAbsent(typeClass
/* 133:189 */ .getName(), hs);
/* 134:190 */ if (last != null) {
/* 135:191 */ hs = last;
/* 136: */ }
/* 137: */ }
/* 138:194 */ return hs;
/* 139: */ }
/* 140: */
/* 141: */ public <T> HasSchema<T> getSchemaWrapper(Class<T> typeClass, boolean create)
/* 142: */ {
/* 143:201 */ HasSchema<T> hs = (HasSchema)this.pojoMapping.get(typeClass.getName());
/* 144:202 */ if ((hs == null) && (create))
/* 145: */ {
/* 146:204 */ hs = new Lazy(typeClass, this);
/* 147:205 */ HasSchema<T> last = (HasSchema)this.pojoMapping.putIfAbsent(typeClass
/* 148:206 */ .getName(), hs);
/* 149:207 */ if (last != null) {
/* 150:208 */ hs = last;
/* 151: */ }
/* 152: */ }
/* 153:211 */ return hs;
/* 154: */ }
/* 155: */
/* 156: */ private EnumIO<? extends Enum<?>> getEnumIO(String className, boolean load)
/* 157: */ {
/* 158:216 */ EnumIO<?> eio = (EnumIO)this.enumMapping.get(className);
/* 159:217 */ if (eio == null)
/* 160: */ {
/* 161:219 */ if (!load) {
/* 162:220 */ return null;
/* 163: */ }
/* 164:222 */ Class<?> enumClass = RuntimeEnv.loadClass(className);
/* 165: */
/* 166:224 */ eio = EnumIO.newEnumIO(enumClass, this);
/* 167: */
/* 168:226 */ EnumIO<?> existing = (EnumIO)this.enumMapping.putIfAbsent(enumClass
/* 169:227 */ .getName(), eio);
/* 170:228 */ if (existing != null) {
/* 171:229 */ eio = existing;
/* 172: */ }
/* 173: */ }
/* 174:232 */ return eio;
/* 175: */ }
/* 176: */
/* 177: */ protected EnumIO<? extends Enum<?>> getEnumIO(Class<?> enumClass)
/* 178: */ {
/* 179:238 */ EnumIO<?> eio = (EnumIO)this.enumMapping.get(enumClass.getName());
/* 180:239 */ if (eio == null)
/* 181: */ {
/* 182:241 */ eio = EnumIO.newEnumIO(enumClass, this);
/* 183: */
/* 184:243 */ EnumIO<?> existing = (EnumIO)this.enumMapping.putIfAbsent(enumClass
/* 185:244 */ .getName(), eio);
/* 186:245 */ if (existing != null) {
/* 187:246 */ eio = existing;
/* 188: */ }
/* 189: */ }
/* 190:249 */ return eio;
/* 191: */ }
/* 192: */
/* 193: */ protected CollectionSchema.MessageFactory getCollectionFactory(Class<?> clazz)
/* 194: */ {
/* 195:256 */ String className = clazz.getName();
/* 196: */
/* 197:258 */ CollectionSchema.MessageFactory factory = (CollectionSchema.MessageFactory)this.collectionMapping.get(className);
/* 198:259 */ if (factory == null) {
/* 199:261 */ if (className.startsWith("java.util"))
/* 200: */ {
/* 201:263 */ factory = CollectionSchema.MessageFactories.valueOf(clazz
/* 202:264 */ .getSimpleName());
/* 203: */ }
/* 204: */ else
/* 205: */ {
/* 206:268 */ factory = new RuntimeCollectionFactory(clazz);
/* 207: */
/* 208:270 */ CollectionSchema.MessageFactory f = (CollectionSchema.MessageFactory)this.collectionMapping.putIfAbsent(className, factory);
/* 209:271 */ if (f != null) {
/* 210:272 */ factory = f;
/* 211: */ }
/* 212: */ }
/* 213: */ }
/* 214:276 */ return factory;
/* 215: */ }
/* 216: */
/* 217: */ protected MapSchema.MessageFactory getMapFactory(Class<?> clazz)
/* 218: */ {
/* 219:282 */ String className = clazz.getName();
/* 220:283 */ MapSchema.MessageFactory factory = (MapSchema.MessageFactory)this.mapMapping.get(className);
/* 221:284 */ if (factory == null) {
/* 222:286 */ if (className.startsWith("java.util"))
/* 223: */ {
/* 224:288 */ factory = MapSchema.MessageFactories.valueOf(clazz
/* 225:289 */ .getSimpleName());
/* 226: */ }
/* 227: */ else
/* 228: */ {
/* 229:293 */ factory = new RuntimeMapFactory(clazz);
/* 230:294 */ MapSchema.MessageFactory f = (MapSchema.MessageFactory)this.mapMapping.putIfAbsent(className, factory);
/* 231:296 */ if (f != null) {
/* 232:297 */ factory = f;
/* 233: */ }
/* 234: */ }
/* 235: */ }
/* 236:301 */ return factory;
/* 237: */ }
/* 238: */
/* 239: */ protected void writeCollectionIdTo(Output output, int fieldNumber, Class<?> clazz)
/* 240: */ throws IOException
/* 241: */ {
/* 242:309 */ CollectionSchema.MessageFactory factory = (CollectionSchema.MessageFactory)this.collectionMapping.get(clazz);
/* 243:310 */ if ((factory == null) && (clazz.getName().startsWith("java.util"))) {
/* 244:315 */ output.writeString(fieldNumber, clazz.getSimpleName(), false);
/* 245: */ } else {
/* 246:319 */ output.writeString(fieldNumber, clazz.getName(), false);
/* 247: */ }
/* 248: */ }
/* 249: */
/* 250: */ protected void transferCollectionId(Input input, Output output, int fieldNumber)
/* 251: */ throws IOException
/* 252: */ {
/* 253:327 */ input.transferByteRangeTo(output, true, fieldNumber, false);
/* 254: */ }
/* 255: */
/* 256: */ protected CollectionSchema.MessageFactory resolveCollectionFrom(Input input)
/* 257: */ throws IOException
/* 258: */ {
/* 259:334 */ String className = input.readString();
/* 260: */
/* 261:336 */ CollectionSchema.MessageFactory factory = (CollectionSchema.MessageFactory)this.collectionMapping.get(className);
/* 262:337 */ if (factory == null) {
/* 263:339 */ if (className.indexOf('.') == -1)
/* 264: */ {
/* 265:341 */ factory = CollectionSchema.MessageFactories.valueOf(className);
/* 266: */ }
/* 267: */ else
/* 268: */ {
/* 269:346 */ factory = new RuntimeCollectionFactory(RuntimeEnv.loadClass(className));
/* 270: */
/* 271:348 */ CollectionSchema.MessageFactory f = (CollectionSchema.MessageFactory)this.collectionMapping.putIfAbsent(className, factory);
/* 272:349 */ if (f != null) {
/* 273:350 */ factory = f;
/* 274: */ }
/* 275: */ }
/* 276: */ }
/* 277:354 */ return factory;
/* 278: */ }
/* 279: */
/* 280: */ protected void writeMapIdTo(Output output, int fieldNumber, Class<?> clazz)
/* 281: */ throws IOException
/* 282: */ {
/* 283:361 */ MapSchema.MessageFactory factory = (MapSchema.MessageFactory)this.mapMapping.get(clazz);
/* 284:362 */ if ((factory == null) && (clazz.getName().startsWith("java.util"))) {
/* 285:367 */ output.writeString(fieldNumber, clazz.getSimpleName(), false);
/* 286: */ } else {
/* 287:371 */ output.writeString(fieldNumber, clazz.getName(), false);
/* 288: */ }
/* 289: */ }
/* 290: */
/* 291: */ protected void transferMapId(Input input, Output output, int fieldNumber)
/* 292: */ throws IOException
/* 293: */ {
/* 294:379 */ input.transferByteRangeTo(output, true, fieldNumber, false);
/* 295: */ }
/* 296: */
/* 297: */ protected MapSchema.MessageFactory resolveMapFrom(Input input)
/* 298: */ throws IOException
/* 299: */ {
/* 300:386 */ String className = input.readString();
/* 301:387 */ MapSchema.MessageFactory factory = (MapSchema.MessageFactory)this.mapMapping.get(className);
/* 302:388 */ if (factory == null) {
/* 303:390 */ if (className.indexOf('.') == -1)
/* 304: */ {
/* 305:392 */ factory = MapSchema.MessageFactories.valueOf(className);
/* 306: */ }
/* 307: */ else
/* 308: */ {
/* 309:396 */ factory = new RuntimeMapFactory(RuntimeEnv.loadClass(className));
/* 310:397 */ MapSchema.MessageFactory f = (MapSchema.MessageFactory)this.mapMapping.putIfAbsent(className, factory);
/* 311:399 */ if (f != null) {
/* 312:400 */ factory = f;
/* 313: */ }
/* 314: */ }
/* 315: */ }
/* 316:404 */ return factory;
/* 317: */ }
/* 318: */
/* 319: */ protected void writeEnumIdTo(Output output, int fieldNumber, Class<?> clazz)
/* 320: */ throws IOException
/* 321: */ {
/* 322:411 */ output.writeString(fieldNumber, clazz.getName(), false);
/* 323: */ }
/* 324: */
/* 325: */ protected void transferEnumId(Input input, Output output, int fieldNumber)
/* 326: */ throws IOException
/* 327: */ {
/* 328:418 */ input.transferByteRangeTo(output, true, fieldNumber, false);
/* 329: */ }
/* 330: */
/* 331: */ protected EnumIO<?> resolveEnumFrom(Input input)
/* 332: */ throws IOException
/* 333: */ {
/* 334:424 */ return getEnumIO(input.readString(), true);
/* 335: */ }
/* 336: */
/* 337: */ protected <T> HasDelegate<T> tryWriteDelegateIdTo(Output output, int fieldNumber, Class<T> clazz)
/* 338: */ throws IOException
/* 339: */ {
/* 340:432 */ HasDelegate<T> hd = (HasDelegate)this.delegateMapping.get(clazz
/* 341:433 */ .getName());
/* 342:434 */ if (hd == null) {
/* 343:435 */ return null;
/* 344: */ }
/* 345:437 */ output.writeString(fieldNumber, clazz.getName(), false);
/* 346: */
/* 347:439 */ return hd;
/* 348: */ }
/* 349: */
/* 350: */ protected <T> HasDelegate<T> transferDelegateId(Input input, Output output, int fieldNumber)
/* 351: */ throws IOException
/* 352: */ {
/* 353:447 */ String className = input.readString();
/* 354: */
/* 355: */
/* 356:450 */ HasDelegate<T> hd = (HasDelegate)this.delegateMapping.get(className);
/* 357:451 */ if (hd == null) {
/* 358:452 */ throw new IdStrategy.UnknownTypeException("delegate: " + className + " (Outdated registry)");
/* 359: */ }
/* 360:455 */ output.writeString(fieldNumber, className, false);
/* 361: */
/* 362:457 */ return hd;
/* 363: */ }
/* 364: */
/* 365: */ protected <T> HasDelegate<T> resolveDelegateFrom(Input input)
/* 366: */ throws IOException
/* 367: */ {
/* 368:465 */ String className = input.readString();
/* 369: */
/* 370: */
/* 371:468 */ HasDelegate<T> hd = (HasDelegate)this.delegateMapping.get(className);
/* 372:469 */ if (hd == null) {
/* 373:470 */ throw new IdStrategy.UnknownTypeException("delegate: " + className + " (Outdated registry)");
/* 374: */ }
/* 375:473 */ return hd;
/* 376: */ }
/* 377: */
/* 378: */ protected <T> HasSchema<T> tryWritePojoIdTo(Output output, int fieldNumber, Class<T> clazz, boolean registered)
/* 379: */ throws IOException
/* 380: */ {
/* 381:480 */ HasSchema<T> hs = getSchemaWrapper(clazz, false);
/* 382:481 */ if ((hs == null) || ((registered) && ((hs instanceof Lazy)))) {
/* 383:482 */ return null;
/* 384: */ }
/* 385:484 */ output.writeString(fieldNumber, clazz.getName(), false);
/* 386: */
/* 387:486 */ return hs;
/* 388: */ }
/* 389: */
/* 390: */ protected <T> HasSchema<T> writePojoIdTo(Output output, int fieldNumber, Class<T> clazz)
/* 391: */ throws IOException
/* 392: */ {
/* 393:493 */ output.writeString(fieldNumber, clazz.getName(), false);
/* 394: */
/* 395: */
/* 396:496 */ return getSchemaWrapper(clazz, true);
/* 397: */ }
/* 398: */
/* 399: */ protected <T> HasSchema<T> transferPojoId(Input input, Output output, int fieldNumber)
/* 400: */ throws IOException
/* 401: */ {
/* 402:503 */ String className = input.readString();
/* 403: */
/* 404:505 */ HasSchema<T> wrapper = getSchemaWrapper(className, 0 != (0x2 & this.flags));
/* 405:507 */ if (wrapper == null) {
/* 406:509 */ throw new ProtostuffException("polymorphic pojo not registered: " + className);
/* 407: */ }
/* 408:513 */ output.writeString(fieldNumber, className, false);
/* 409: */
/* 410:515 */ return wrapper;
/* 411: */ }
/* 412: */
/* 413: */ protected <T> HasSchema<T> resolvePojoFrom(Input input, int fieldNumber)
/* 414: */ throws IOException
/* 415: */ {
/* 416:522 */ String className = input.readString();
/* 417: */
/* 418:524 */ HasSchema<T> wrapper = getSchemaWrapper(className, 0 != (0x2 & this.flags));
/* 419:526 */ if (wrapper == null) {
/* 420:527 */ throw new ProtostuffException("polymorphic pojo not registered: " + className);
/* 421: */ }
/* 422:530 */ return wrapper;
/* 423: */ }
/* 424: */
/* 425: */ protected <T> Schema<T> writeMessageIdTo(Output output, int fieldNumber, Message<T> message)
/* 426: */ throws IOException
/* 427: */ {
/* 428:537 */ output.writeString(fieldNumber, message.getClass().getName(), false);
/* 429: */
/* 430:539 */ return message.cachedSchema();
/* 431: */ }
/* 432: */
/* 433: */ protected void writeArrayIdTo(Output output, Class<?> componentType)
/* 434: */ throws IOException
/* 435: */ {
/* 436:546 */ output.writeString(15, componentType
/* 437:547 */ .getName(), false);
/* 438: */ }
/* 439: */
/* 440: */ protected void transferArrayId(Input input, Output output, int fieldNumber, boolean mapped)
/* 441: */ throws IOException
/* 442: */ {
/* 443:554 */ input.transferByteRangeTo(output, true, fieldNumber, false);
/* 444: */ }
/* 445: */
/* 446: */ protected Class<?> resolveArrayComponentTypeFrom(Input input, boolean mapped)
/* 447: */ throws IOException
/* 448: */ {
/* 449:561 */ return resolveClass(input.readString());
/* 450: */ }
/* 451: */
/* 452: */ static Class<?> resolveClass(String className)
/* 453: */ {
/* 454:567 */ RuntimeFieldFactory<Object> inline = RuntimeFieldFactory.getInline(className);
/* 455:569 */ if (inline == null) {
/* 456:570 */ return RuntimeEnv.loadClass(className);
/* 457: */ }
/* 458:572 */ if (className.indexOf('.') != -1) {
/* 459:573 */ return inline.typeClass();
/* 460: */ }
/* 461:575 */ switch (inline.id)
/* 462: */ {
/* 463: */ case 1:
/* 464:578 */ return Boolean.TYPE;
/* 465: */ case 2:
/* 466:580 */ return Byte.TYPE;
/* 467: */ case 3:
/* 468:582 */ return Character.TYPE;
/* 469: */ case 4:
/* 470:584 */ return Short.TYPE;
/* 471: */ case 5:
/* 472:586 */ return Integer.TYPE;
/* 473: */ case 6:
/* 474:588 */ return Long.TYPE;
/* 475: */ case 7:
/* 476:590 */ return Float.TYPE;
/* 477: */ case 8:
/* 478:592 */ return Double.TYPE;
/* 479: */ }
/* 480:594 */ throw new RuntimeException("Should never happen.");
/* 481: */ }
/* 482: */
/* 483: */ protected void writeClassIdTo(Output output, Class<?> componentType, boolean array)
/* 484: */ throws IOException
/* 485: */ {
/* 486:602 */ int id = array ? 20 : 18;
/* 487: */
/* 488: */
/* 489:605 */ output.writeString(id, componentType.getName(), false);
/* 490: */ }
/* 491: */
/* 492: */ protected void transferClassId(Input input, Output output, int fieldNumber, boolean mapped, boolean array)
/* 493: */ throws IOException
/* 494: */ {
/* 495:612 */ input.transferByteRangeTo(output, true, fieldNumber, false);
/* 496: */ }
/* 497: */
/* 498: */ protected Class<?> resolveClassFrom(Input input, boolean mapped, boolean array)
/* 499: */ throws IOException
/* 500: */ {
/* 501:619 */ return resolveClass(input.readString());
/* 502: */ }
/* 503: */
/* 504: */ static final class RuntimeCollectionFactory
/* 505: */ implements CollectionSchema.MessageFactory
/* 506: */ {
/* 507: */ final Class<?> collectionClass;
/* 508: */ final RuntimeEnv.Instantiator<?> instantiator;
/* 509: */
/* 510: */ public RuntimeCollectionFactory(Class<?> collectionClass)
/* 511: */ {
/* 512:631 */ this.collectionClass = collectionClass;
/* 513:632 */ this.instantiator = RuntimeEnv.newInstantiator(collectionClass);
/* 514: */ }
/* 515: */
/* 516: */ public <V> Collection<V> newMessage()
/* 517: */ {
/* 518:639 */ return (Collection)this.instantiator.newInstance();
/* 519: */ }
/* 520: */
/* 521: */ public Class<?> typeClass()
/* 522: */ {
/* 523:645 */ return this.collectionClass;
/* 524: */ }
/* 525: */ }
/* 526: */
/* 527: */ static final class RuntimeMapFactory
/* 528: */ implements MapSchema.MessageFactory
/* 529: */ {
/* 530: */ final Class<?> mapClass;
/* 531: */ final RuntimeEnv.Instantiator<?> instantiator;
/* 532: */
/* 533: */ public RuntimeMapFactory(Class<?> mapClass)
/* 534: */ {
/* 535:657 */ this.mapClass = mapClass;
/* 536:658 */ this.instantiator = RuntimeEnv.newInstantiator(mapClass);
/* 537: */ }
/* 538: */
/* 539: */ public <K, V> Map<K, V> newMessage()
/* 540: */ {
/* 541:665 */ return (Map)this.instantiator.newInstance();
/* 542: */ }
/* 543: */
/* 544: */ public Class<?> typeClass()
/* 545: */ {
/* 546:671 */ return this.mapClass;
/* 547: */ }
/* 548: */ }
/* 549: */
/* 550: */ static final class Lazy<T>
/* 551: */ extends HasSchema<T>
/* 552: */ {
/* 553: */ final Class<T> typeClass;
/* 554: */ private volatile Schema<T> schema;
/* 555: */ private volatile Pipe.Schema<T> pipeSchema;
/* 556: */
/* 557: */ Lazy(Class<T> typeClass, IdStrategy strategy)
/* 558: */ {
/* 559:684 */ super();
/* 560:685 */ this.typeClass = typeClass;
/* 561: */ }
/* 562: */
/* 563: */ public Schema<T> getSchema()
/* 564: */ {
/* 565:692 */ Schema<T> schema = this.schema;
/* 566:693 */ if (schema == null) {
/* 567:695 */ synchronized (this)
/* 568: */ {
/* 569:697 */ if ((schema = this.schema) == null) {
/* 570:699 */ if (Message.class.isAssignableFrom(this.typeClass))
/* 571: */ {
/* 572:702 */ Message<T> m = (Message)IdStrategy.createMessageInstance(this.typeClass);
/* 573:703 */ this.schema = (schema = m.cachedSchema());
/* 574: */ }
/* 575: */ else
/* 576: */ {
/* 577:709 */ this.schema = (schema = this.strategy.newSchema(this.typeClass));
/* 578: */ }
/* 579: */ }
/* 580: */ }
/* 581: */ }
/* 582:715 */ return schema;
/* 583: */ }
/* 584: */
/* 585: */ public Pipe.Schema<T> getPipeSchema()
/* 586: */ {
/* 587:721 */ Pipe.Schema<T> pipeSchema = this.pipeSchema;
/* 588:722 */ if (pipeSchema == null) {
/* 589:724 */ synchronized (this)
/* 590: */ {
/* 591:726 */ if ((pipeSchema = this.pipeSchema) == null) {
/* 592:729 */ this.pipeSchema = (pipeSchema = RuntimeSchema.resolvePipeSchema(getSchema(), this.typeClass, true));
/* 593: */ }
/* 594: */ }
/* 595: */ }
/* 596:733 */ return pipeSchema;
/* 597: */ }
/* 598: */ }
/* 599: */
/* 600: */ static final class Mapped<T>
/* 601: */ extends HasSchema<T>
/* 602: */ {
/* 603: */ final Class<? super T> baseClass;
/* 604: */ final Class<T> typeClass;
/* 605: */ private volatile HasSchema<T> wrapper;
/* 606: */
/* 607: */ Mapped(Class<? super T> baseClass, Class<T> typeClass, IdStrategy strategy)
/* 608: */ {
/* 609:747 */ super();
/* 610:748 */ this.baseClass = baseClass;
/* 611:749 */ this.typeClass = typeClass;
/* 612: */ }
/* 613: */
/* 614: */ public Schema<T> getSchema()
/* 615: */ {
/* 616:755 */ HasSchema<T> wrapper = this.wrapper;
/* 617:756 */ if (wrapper == null) {
/* 618:758 */ synchronized (this)
/* 619: */ {
/* 620:760 */ if ((wrapper = this.wrapper) == null) {
/* 621:762 */ this.wrapper = (wrapper = this.strategy.getSchemaWrapper(this.typeClass, true));
/* 622: */ }
/* 623: */ }
/* 624: */ }
/* 625:768 */ return wrapper.getSchema();
/* 626: */ }
/* 627: */
/* 628: */ public Pipe.Schema<T> getPipeSchema()
/* 629: */ {
/* 630:774 */ HasSchema<T> wrapper = this.wrapper;
/* 631:775 */ if (wrapper == null) {
/* 632:777 */ synchronized (this)
/* 633: */ {
/* 634:779 */ if ((wrapper = this.wrapper) == null) {
/* 635:781 */ this.wrapper = (wrapper = this.strategy.getSchemaWrapper(this.typeClass, true));
/* 636: */ }
/* 637: */ }
/* 638: */ }
/* 639:787 */ return wrapper.getPipeSchema();
/* 640: */ }
/* 641: */ }
/* 642: */
/* 643: */ static final class LazyRegister<T>
/* 644: */ extends HasSchema<T>
/* 645: */ {
/* 646: */ final Class<T> typeClass;
/* 647: */ private volatile Schema<T> schema;
/* 648: */ private volatile Pipe.Schema<T> pipeSchema;
/* 649: */
/* 650: */ LazyRegister(Class<T> typeClass, IdStrategy strategy)
/* 651: */ {
/* 652:800 */ super();
/* 653:801 */ this.typeClass = typeClass;
/* 654: */ }
/* 655: */
/* 656: */ public Schema<T> getSchema()
/* 657: */ {
/* 658:807 */ Schema<T> schema = this.schema;
/* 659:808 */ if (schema == null) {
/* 660:810 */ synchronized (this)
/* 661: */ {
/* 662:812 */ if ((schema = this.schema) == null) {
/* 663:815 */ this.schema = (schema = this.strategy.newSchema(this.typeClass));
/* 664: */ }
/* 665: */ }
/* 666: */ }
/* 667:820 */ return schema;
/* 668: */ }
/* 669: */
/* 670: */ public Pipe.Schema<T> getPipeSchema()
/* 671: */ {
/* 672:826 */ Pipe.Schema<T> pipeSchema = this.pipeSchema;
/* 673:827 */ if (pipeSchema == null) {
/* 674:829 */ synchronized (this)
/* 675: */ {
/* 676:831 */ if ((pipeSchema = this.pipeSchema) == null) {
/* 677:834 */ this.pipeSchema = (pipeSchema = RuntimeSchema.resolvePipeSchema(getSchema(), this.typeClass, true));
/* 678: */ }
/* 679: */ }
/* 680: */ }
/* 681:839 */ return pipeSchema;
/* 682: */ }
/* 683: */ }
/* 684: */
/* 685: */ static final class Registered<T>
/* 686: */ extends HasSchema<T>
/* 687: */ {
/* 688: */ final Schema<T> schema;
/* 689: */ private volatile Pipe.Schema<T> pipeSchema;
/* 690: */
/* 691: */ Registered(Schema<T> schema, IdStrategy strategy)
/* 692: */ {
/* 693:850 */ super();
/* 694:851 */ this.schema = schema;
/* 695: */ }
/* 696: */
/* 697: */ public Schema<T> getSchema()
/* 698: */ {
/* 699:857 */ return this.schema;
/* 700: */ }
/* 701: */
/* 702: */ public Pipe.Schema<T> getPipeSchema()
/* 703: */ {
/* 704:863 */ Pipe.Schema<T> pipeSchema = this.pipeSchema;
/* 705:864 */ if (pipeSchema == null) {
/* 706:866 */ synchronized (this)
/* 707: */ {
/* 708:868 */ if ((pipeSchema = this.pipeSchema) == null) {
/* 709:871 */ this.pipeSchema = (pipeSchema = RuntimeSchema.resolvePipeSchema(this.schema, this.schema.typeClass(), true));
/* 710: */ }
/* 711: */ }
/* 712: */ }
/* 713:876 */ return pipeSchema;
/* 714: */ }
/* 715: */ }
/* 716: */ }
/* Location: C:\Users\LX\Desktop\新建文件夹 (2)\
* Qualified Name: io.protostuff.runtime.DefaultIdStrategy
* JD-Core Version: 0.7.0.1
*/ | UTF-8 | Java | 31,484 | java | DefaultIdStrategy.java | Java | [] | null | [] | /* 1: */ package io.protostuff.runtime;
/* 2: */
/* 3: */ import io.protostuff.CollectionSchema.MessageFactories;
/* 4: */ import io.protostuff.CollectionSchema.MessageFactory;
/* 5: */ import io.protostuff.Input;
/* 6: */ import io.protostuff.MapSchema.MessageFactories;
/* 7: */ import io.protostuff.MapSchema.MessageFactory;
/* 8: */ import io.protostuff.Message;
/* 9: */ import io.protostuff.Output;
/* 10: */ import io.protostuff.Pipe.Schema;
/* 11: */ import io.protostuff.ProtostuffException;
/* 12: */ import io.protostuff.Schema;
/* 13: */ import java.io.IOException;
/* 14: */ import java.lang.reflect.Modifier;
/* 15: */ import java.util.Collection;
/* 16: */ import java.util.Map;
/* 17: */ import java.util.concurrent.ConcurrentHashMap;
/* 18: */
/* 19: */ public final class DefaultIdStrategy
/* 20: */ extends IdStrategy
/* 21: */ {
/* 22: 36 */ final ConcurrentHashMap<String, HasSchema<?>> pojoMapping = new ConcurrentHashMap();
/* 23: 38 */ final ConcurrentHashMap<String, EnumIO<?>> enumMapping = new ConcurrentHashMap();
/* 24: 40 */ final ConcurrentHashMap<String, CollectionSchema.MessageFactory> collectionMapping = new ConcurrentHashMap();
/* 25: 42 */ final ConcurrentHashMap<String, MapSchema.MessageFactory> mapMapping = new ConcurrentHashMap();
/* 26: 44 */ final ConcurrentHashMap<String, HasDelegate<?>> delegateMapping = new ConcurrentHashMap();
/* 27: */
/* 28: */ public DefaultIdStrategy()
/* 29: */ {
/* 30: 48 */ super(DEFAULT_FLAGS, null, 0);
/* 31: */ }
/* 32: */
/* 33: */ public DefaultIdStrategy(IdStrategy primaryGroup, int groupId)
/* 34: */ {
/* 35: 53 */ super(DEFAULT_FLAGS, primaryGroup, groupId);
/* 36: */ }
/* 37: */
/* 38: */ public DefaultIdStrategy(int flags, IdStrategy primaryGroup, int groupId)
/* 39: */ {
/* 40: 58 */ super(flags, primaryGroup, groupId);
/* 41: */ }
/* 42: */
/* 43: */ public <T> boolean registerPojo(Class<T> typeClass, Schema<T> schema)
/* 44: */ {
/* 45: 67 */ assert ((typeClass != null) && (schema != null));
/* 46: */
/* 47: 69 */ HasSchema<?> last = (HasSchema)this.pojoMapping.putIfAbsent(typeClass.getName(), new Registered(schema, this));
/* 48: */
/* 49: */
/* 50: 72 */ return (last == null) || (((last instanceof Registered)) && (((Registered)last).schema == schema));
/* 51: */ }
/* 52: */
/* 53: */ public <T> boolean registerPojo(Class<T> typeClass)
/* 54: */ {
/* 55: 82 */ assert (typeClass != null);
/* 56: */
/* 57: 84 */ HasSchema<?> last = (HasSchema)this.pojoMapping.putIfAbsent(typeClass.getName(), new LazyRegister(typeClass, this));
/* 58: */
/* 59: */
/* 60: 87 */ return (last == null) || ((last instanceof LazyRegister));
/* 61: */ }
/* 62: */
/* 63: */ public <T extends Enum<T>> boolean registerEnum(Class<T> enumClass)
/* 64: */ {
/* 65: 95 */ return null == this.enumMapping.putIfAbsent(enumClass.getName(),
/* 66: 96 */ EnumIO.newEnumIO(enumClass, this));
/* 67: */ }
/* 68: */
/* 69: */ public <T> boolean registerDelegate(Delegate<T> delegate)
/* 70: */ {
/* 71:104 */ return null == this.delegateMapping.putIfAbsent(delegate.typeClass()
/* 72:105 */ .getName(), new HasDelegate(delegate, this));
/* 73: */ }
/* 74: */
/* 75: */ public boolean registerCollection(CollectionSchema.MessageFactory factory)
/* 76: */ {
/* 77:113 */ return null == this.collectionMapping.putIfAbsent(factory.typeClass()
/* 78:114 */ .getName(), factory);
/* 79: */ }
/* 80: */
/* 81: */ public boolean registerMap(MapSchema.MessageFactory factory)
/* 82: */ {
/* 83:122 */ return null == this.mapMapping.putIfAbsent(factory.typeClass().getName(), factory);
/* 84: */ }
/* 85: */
/* 86: */ public <T> boolean map(Class<? super T> baseClass, Class<T> typeClass)
/* 87: */ {
/* 88:131 */ assert ((baseClass != null) && (typeClass != null));
/* 89:133 */ if ((typeClass.isInterface()) ||
/* 90:134 */ (Modifier.isAbstract(typeClass.getModifiers()))) {
/* 91:136 */ throw new IllegalArgumentException(typeClass + " cannot be an interface/abstract class.");
/* 92: */ }
/* 93:140 */ HasSchema<?> last = (HasSchema)this.pojoMapping.putIfAbsent(baseClass.getName(), new Mapped(baseClass, typeClass, this));
/* 94: */
/* 95: */
/* 96:143 */ return (last == null) || (((last instanceof Mapped)) && (((Mapped)last).typeClass == typeClass));
/* 97: */ }
/* 98: */
/* 99: */ public boolean isDelegateRegistered(Class<?> typeClass)
/* 100: */ {
/* 101:150 */ return this.delegateMapping.containsKey(typeClass.getName());
/* 102: */ }
/* 103: */
/* 104: */ public <T> HasDelegate<T> getDelegateWrapper(Class<? super T> typeClass)
/* 105: */ {
/* 106:157 */ return (HasDelegate)this.delegateMapping.get(typeClass.getName());
/* 107: */ }
/* 108: */
/* 109: */ public <T> Delegate<T> getDelegate(Class<? super T> typeClass)
/* 110: */ {
/* 111:165 */ HasDelegate<T> last = (HasDelegate)this.delegateMapping.get(typeClass.getName());
/* 112:166 */ return last == null ? null : last.delegate;
/* 113: */ }
/* 114: */
/* 115: */ public boolean isRegistered(Class<?> typeClass)
/* 116: */ {
/* 117:172 */ HasSchema<?> last = (HasSchema)this.pojoMapping.get(typeClass.getName());
/* 118:173 */ return (last != null) && (!(last instanceof Lazy));
/* 119: */ }
/* 120: */
/* 121: */ private <T> HasSchema<T> getSchemaWrapper(String className, boolean load)
/* 122: */ {
/* 123:179 */ HasSchema<T> hs = (HasSchema)this.pojoMapping.get(className);
/* 124:180 */ if (hs == null)
/* 125: */ {
/* 126:182 */ if (!load) {
/* 127:183 */ return null;
/* 128: */ }
/* 129:185 */ Class<T> typeClass = RuntimeEnv.loadClass(className);
/* 130: */
/* 131:187 */ hs = new Lazy(typeClass, this);
/* 132:188 */ HasSchema<T> last = (HasSchema)this.pojoMapping.putIfAbsent(typeClass
/* 133:189 */ .getName(), hs);
/* 134:190 */ if (last != null) {
/* 135:191 */ hs = last;
/* 136: */ }
/* 137: */ }
/* 138:194 */ return hs;
/* 139: */ }
/* 140: */
/* 141: */ public <T> HasSchema<T> getSchemaWrapper(Class<T> typeClass, boolean create)
/* 142: */ {
/* 143:201 */ HasSchema<T> hs = (HasSchema)this.pojoMapping.get(typeClass.getName());
/* 144:202 */ if ((hs == null) && (create))
/* 145: */ {
/* 146:204 */ hs = new Lazy(typeClass, this);
/* 147:205 */ HasSchema<T> last = (HasSchema)this.pojoMapping.putIfAbsent(typeClass
/* 148:206 */ .getName(), hs);
/* 149:207 */ if (last != null) {
/* 150:208 */ hs = last;
/* 151: */ }
/* 152: */ }
/* 153:211 */ return hs;
/* 154: */ }
/* 155: */
/* 156: */ private EnumIO<? extends Enum<?>> getEnumIO(String className, boolean load)
/* 157: */ {
/* 158:216 */ EnumIO<?> eio = (EnumIO)this.enumMapping.get(className);
/* 159:217 */ if (eio == null)
/* 160: */ {
/* 161:219 */ if (!load) {
/* 162:220 */ return null;
/* 163: */ }
/* 164:222 */ Class<?> enumClass = RuntimeEnv.loadClass(className);
/* 165: */
/* 166:224 */ eio = EnumIO.newEnumIO(enumClass, this);
/* 167: */
/* 168:226 */ EnumIO<?> existing = (EnumIO)this.enumMapping.putIfAbsent(enumClass
/* 169:227 */ .getName(), eio);
/* 170:228 */ if (existing != null) {
/* 171:229 */ eio = existing;
/* 172: */ }
/* 173: */ }
/* 174:232 */ return eio;
/* 175: */ }
/* 176: */
/* 177: */ protected EnumIO<? extends Enum<?>> getEnumIO(Class<?> enumClass)
/* 178: */ {
/* 179:238 */ EnumIO<?> eio = (EnumIO)this.enumMapping.get(enumClass.getName());
/* 180:239 */ if (eio == null)
/* 181: */ {
/* 182:241 */ eio = EnumIO.newEnumIO(enumClass, this);
/* 183: */
/* 184:243 */ EnumIO<?> existing = (EnumIO)this.enumMapping.putIfAbsent(enumClass
/* 185:244 */ .getName(), eio);
/* 186:245 */ if (existing != null) {
/* 187:246 */ eio = existing;
/* 188: */ }
/* 189: */ }
/* 190:249 */ return eio;
/* 191: */ }
/* 192: */
/* 193: */ protected CollectionSchema.MessageFactory getCollectionFactory(Class<?> clazz)
/* 194: */ {
/* 195:256 */ String className = clazz.getName();
/* 196: */
/* 197:258 */ CollectionSchema.MessageFactory factory = (CollectionSchema.MessageFactory)this.collectionMapping.get(className);
/* 198:259 */ if (factory == null) {
/* 199:261 */ if (className.startsWith("java.util"))
/* 200: */ {
/* 201:263 */ factory = CollectionSchema.MessageFactories.valueOf(clazz
/* 202:264 */ .getSimpleName());
/* 203: */ }
/* 204: */ else
/* 205: */ {
/* 206:268 */ factory = new RuntimeCollectionFactory(clazz);
/* 207: */
/* 208:270 */ CollectionSchema.MessageFactory f = (CollectionSchema.MessageFactory)this.collectionMapping.putIfAbsent(className, factory);
/* 209:271 */ if (f != null) {
/* 210:272 */ factory = f;
/* 211: */ }
/* 212: */ }
/* 213: */ }
/* 214:276 */ return factory;
/* 215: */ }
/* 216: */
/* 217: */ protected MapSchema.MessageFactory getMapFactory(Class<?> clazz)
/* 218: */ {
/* 219:282 */ String className = clazz.getName();
/* 220:283 */ MapSchema.MessageFactory factory = (MapSchema.MessageFactory)this.mapMapping.get(className);
/* 221:284 */ if (factory == null) {
/* 222:286 */ if (className.startsWith("java.util"))
/* 223: */ {
/* 224:288 */ factory = MapSchema.MessageFactories.valueOf(clazz
/* 225:289 */ .getSimpleName());
/* 226: */ }
/* 227: */ else
/* 228: */ {
/* 229:293 */ factory = new RuntimeMapFactory(clazz);
/* 230:294 */ MapSchema.MessageFactory f = (MapSchema.MessageFactory)this.mapMapping.putIfAbsent(className, factory);
/* 231:296 */ if (f != null) {
/* 232:297 */ factory = f;
/* 233: */ }
/* 234: */ }
/* 235: */ }
/* 236:301 */ return factory;
/* 237: */ }
/* 238: */
/* 239: */ protected void writeCollectionIdTo(Output output, int fieldNumber, Class<?> clazz)
/* 240: */ throws IOException
/* 241: */ {
/* 242:309 */ CollectionSchema.MessageFactory factory = (CollectionSchema.MessageFactory)this.collectionMapping.get(clazz);
/* 243:310 */ if ((factory == null) && (clazz.getName().startsWith("java.util"))) {
/* 244:315 */ output.writeString(fieldNumber, clazz.getSimpleName(), false);
/* 245: */ } else {
/* 246:319 */ output.writeString(fieldNumber, clazz.getName(), false);
/* 247: */ }
/* 248: */ }
/* 249: */
/* 250: */ protected void transferCollectionId(Input input, Output output, int fieldNumber)
/* 251: */ throws IOException
/* 252: */ {
/* 253:327 */ input.transferByteRangeTo(output, true, fieldNumber, false);
/* 254: */ }
/* 255: */
/* 256: */ protected CollectionSchema.MessageFactory resolveCollectionFrom(Input input)
/* 257: */ throws IOException
/* 258: */ {
/* 259:334 */ String className = input.readString();
/* 260: */
/* 261:336 */ CollectionSchema.MessageFactory factory = (CollectionSchema.MessageFactory)this.collectionMapping.get(className);
/* 262:337 */ if (factory == null) {
/* 263:339 */ if (className.indexOf('.') == -1)
/* 264: */ {
/* 265:341 */ factory = CollectionSchema.MessageFactories.valueOf(className);
/* 266: */ }
/* 267: */ else
/* 268: */ {
/* 269:346 */ factory = new RuntimeCollectionFactory(RuntimeEnv.loadClass(className));
/* 270: */
/* 271:348 */ CollectionSchema.MessageFactory f = (CollectionSchema.MessageFactory)this.collectionMapping.putIfAbsent(className, factory);
/* 272:349 */ if (f != null) {
/* 273:350 */ factory = f;
/* 274: */ }
/* 275: */ }
/* 276: */ }
/* 277:354 */ return factory;
/* 278: */ }
/* 279: */
/* 280: */ protected void writeMapIdTo(Output output, int fieldNumber, Class<?> clazz)
/* 281: */ throws IOException
/* 282: */ {
/* 283:361 */ MapSchema.MessageFactory factory = (MapSchema.MessageFactory)this.mapMapping.get(clazz);
/* 284:362 */ if ((factory == null) && (clazz.getName().startsWith("java.util"))) {
/* 285:367 */ output.writeString(fieldNumber, clazz.getSimpleName(), false);
/* 286: */ } else {
/* 287:371 */ output.writeString(fieldNumber, clazz.getName(), false);
/* 288: */ }
/* 289: */ }
/* 290: */
/* 291: */ protected void transferMapId(Input input, Output output, int fieldNumber)
/* 292: */ throws IOException
/* 293: */ {
/* 294:379 */ input.transferByteRangeTo(output, true, fieldNumber, false);
/* 295: */ }
/* 296: */
/* 297: */ protected MapSchema.MessageFactory resolveMapFrom(Input input)
/* 298: */ throws IOException
/* 299: */ {
/* 300:386 */ String className = input.readString();
/* 301:387 */ MapSchema.MessageFactory factory = (MapSchema.MessageFactory)this.mapMapping.get(className);
/* 302:388 */ if (factory == null) {
/* 303:390 */ if (className.indexOf('.') == -1)
/* 304: */ {
/* 305:392 */ factory = MapSchema.MessageFactories.valueOf(className);
/* 306: */ }
/* 307: */ else
/* 308: */ {
/* 309:396 */ factory = new RuntimeMapFactory(RuntimeEnv.loadClass(className));
/* 310:397 */ MapSchema.MessageFactory f = (MapSchema.MessageFactory)this.mapMapping.putIfAbsent(className, factory);
/* 311:399 */ if (f != null) {
/* 312:400 */ factory = f;
/* 313: */ }
/* 314: */ }
/* 315: */ }
/* 316:404 */ return factory;
/* 317: */ }
/* 318: */
/* 319: */ protected void writeEnumIdTo(Output output, int fieldNumber, Class<?> clazz)
/* 320: */ throws IOException
/* 321: */ {
/* 322:411 */ output.writeString(fieldNumber, clazz.getName(), false);
/* 323: */ }
/* 324: */
/* 325: */ protected void transferEnumId(Input input, Output output, int fieldNumber)
/* 326: */ throws IOException
/* 327: */ {
/* 328:418 */ input.transferByteRangeTo(output, true, fieldNumber, false);
/* 329: */ }
/* 330: */
/* 331: */ protected EnumIO<?> resolveEnumFrom(Input input)
/* 332: */ throws IOException
/* 333: */ {
/* 334:424 */ return getEnumIO(input.readString(), true);
/* 335: */ }
/* 336: */
/* 337: */ protected <T> HasDelegate<T> tryWriteDelegateIdTo(Output output, int fieldNumber, Class<T> clazz)
/* 338: */ throws IOException
/* 339: */ {
/* 340:432 */ HasDelegate<T> hd = (HasDelegate)this.delegateMapping.get(clazz
/* 341:433 */ .getName());
/* 342:434 */ if (hd == null) {
/* 343:435 */ return null;
/* 344: */ }
/* 345:437 */ output.writeString(fieldNumber, clazz.getName(), false);
/* 346: */
/* 347:439 */ return hd;
/* 348: */ }
/* 349: */
/* 350: */ protected <T> HasDelegate<T> transferDelegateId(Input input, Output output, int fieldNumber)
/* 351: */ throws IOException
/* 352: */ {
/* 353:447 */ String className = input.readString();
/* 354: */
/* 355: */
/* 356:450 */ HasDelegate<T> hd = (HasDelegate)this.delegateMapping.get(className);
/* 357:451 */ if (hd == null) {
/* 358:452 */ throw new IdStrategy.UnknownTypeException("delegate: " + className + " (Outdated registry)");
/* 359: */ }
/* 360:455 */ output.writeString(fieldNumber, className, false);
/* 361: */
/* 362:457 */ return hd;
/* 363: */ }
/* 364: */
/* 365: */ protected <T> HasDelegate<T> resolveDelegateFrom(Input input)
/* 366: */ throws IOException
/* 367: */ {
/* 368:465 */ String className = input.readString();
/* 369: */
/* 370: */
/* 371:468 */ HasDelegate<T> hd = (HasDelegate)this.delegateMapping.get(className);
/* 372:469 */ if (hd == null) {
/* 373:470 */ throw new IdStrategy.UnknownTypeException("delegate: " + className + " (Outdated registry)");
/* 374: */ }
/* 375:473 */ return hd;
/* 376: */ }
/* 377: */
/* 378: */ protected <T> HasSchema<T> tryWritePojoIdTo(Output output, int fieldNumber, Class<T> clazz, boolean registered)
/* 379: */ throws IOException
/* 380: */ {
/* 381:480 */ HasSchema<T> hs = getSchemaWrapper(clazz, false);
/* 382:481 */ if ((hs == null) || ((registered) && ((hs instanceof Lazy)))) {
/* 383:482 */ return null;
/* 384: */ }
/* 385:484 */ output.writeString(fieldNumber, clazz.getName(), false);
/* 386: */
/* 387:486 */ return hs;
/* 388: */ }
/* 389: */
/* 390: */ protected <T> HasSchema<T> writePojoIdTo(Output output, int fieldNumber, Class<T> clazz)
/* 391: */ throws IOException
/* 392: */ {
/* 393:493 */ output.writeString(fieldNumber, clazz.getName(), false);
/* 394: */
/* 395: */
/* 396:496 */ return getSchemaWrapper(clazz, true);
/* 397: */ }
/* 398: */
/* 399: */ protected <T> HasSchema<T> transferPojoId(Input input, Output output, int fieldNumber)
/* 400: */ throws IOException
/* 401: */ {
/* 402:503 */ String className = input.readString();
/* 403: */
/* 404:505 */ HasSchema<T> wrapper = getSchemaWrapper(className, 0 != (0x2 & this.flags));
/* 405:507 */ if (wrapper == null) {
/* 406:509 */ throw new ProtostuffException("polymorphic pojo not registered: " + className);
/* 407: */ }
/* 408:513 */ output.writeString(fieldNumber, className, false);
/* 409: */
/* 410:515 */ return wrapper;
/* 411: */ }
/* 412: */
/* 413: */ protected <T> HasSchema<T> resolvePojoFrom(Input input, int fieldNumber)
/* 414: */ throws IOException
/* 415: */ {
/* 416:522 */ String className = input.readString();
/* 417: */
/* 418:524 */ HasSchema<T> wrapper = getSchemaWrapper(className, 0 != (0x2 & this.flags));
/* 419:526 */ if (wrapper == null) {
/* 420:527 */ throw new ProtostuffException("polymorphic pojo not registered: " + className);
/* 421: */ }
/* 422:530 */ return wrapper;
/* 423: */ }
/* 424: */
/* 425: */ protected <T> Schema<T> writeMessageIdTo(Output output, int fieldNumber, Message<T> message)
/* 426: */ throws IOException
/* 427: */ {
/* 428:537 */ output.writeString(fieldNumber, message.getClass().getName(), false);
/* 429: */
/* 430:539 */ return message.cachedSchema();
/* 431: */ }
/* 432: */
/* 433: */ protected void writeArrayIdTo(Output output, Class<?> componentType)
/* 434: */ throws IOException
/* 435: */ {
/* 436:546 */ output.writeString(15, componentType
/* 437:547 */ .getName(), false);
/* 438: */ }
/* 439: */
/* 440: */ protected void transferArrayId(Input input, Output output, int fieldNumber, boolean mapped)
/* 441: */ throws IOException
/* 442: */ {
/* 443:554 */ input.transferByteRangeTo(output, true, fieldNumber, false);
/* 444: */ }
/* 445: */
/* 446: */ protected Class<?> resolveArrayComponentTypeFrom(Input input, boolean mapped)
/* 447: */ throws IOException
/* 448: */ {
/* 449:561 */ return resolveClass(input.readString());
/* 450: */ }
/* 451: */
/* 452: */ static Class<?> resolveClass(String className)
/* 453: */ {
/* 454:567 */ RuntimeFieldFactory<Object> inline = RuntimeFieldFactory.getInline(className);
/* 455:569 */ if (inline == null) {
/* 456:570 */ return RuntimeEnv.loadClass(className);
/* 457: */ }
/* 458:572 */ if (className.indexOf('.') != -1) {
/* 459:573 */ return inline.typeClass();
/* 460: */ }
/* 461:575 */ switch (inline.id)
/* 462: */ {
/* 463: */ case 1:
/* 464:578 */ return Boolean.TYPE;
/* 465: */ case 2:
/* 466:580 */ return Byte.TYPE;
/* 467: */ case 3:
/* 468:582 */ return Character.TYPE;
/* 469: */ case 4:
/* 470:584 */ return Short.TYPE;
/* 471: */ case 5:
/* 472:586 */ return Integer.TYPE;
/* 473: */ case 6:
/* 474:588 */ return Long.TYPE;
/* 475: */ case 7:
/* 476:590 */ return Float.TYPE;
/* 477: */ case 8:
/* 478:592 */ return Double.TYPE;
/* 479: */ }
/* 480:594 */ throw new RuntimeException("Should never happen.");
/* 481: */ }
/* 482: */
/* 483: */ protected void writeClassIdTo(Output output, Class<?> componentType, boolean array)
/* 484: */ throws IOException
/* 485: */ {
/* 486:602 */ int id = array ? 20 : 18;
/* 487: */
/* 488: */
/* 489:605 */ output.writeString(id, componentType.getName(), false);
/* 490: */ }
/* 491: */
/* 492: */ protected void transferClassId(Input input, Output output, int fieldNumber, boolean mapped, boolean array)
/* 493: */ throws IOException
/* 494: */ {
/* 495:612 */ input.transferByteRangeTo(output, true, fieldNumber, false);
/* 496: */ }
/* 497: */
/* 498: */ protected Class<?> resolveClassFrom(Input input, boolean mapped, boolean array)
/* 499: */ throws IOException
/* 500: */ {
/* 501:619 */ return resolveClass(input.readString());
/* 502: */ }
/* 503: */
/* 504: */ static final class RuntimeCollectionFactory
/* 505: */ implements CollectionSchema.MessageFactory
/* 506: */ {
/* 507: */ final Class<?> collectionClass;
/* 508: */ final RuntimeEnv.Instantiator<?> instantiator;
/* 509: */
/* 510: */ public RuntimeCollectionFactory(Class<?> collectionClass)
/* 511: */ {
/* 512:631 */ this.collectionClass = collectionClass;
/* 513:632 */ this.instantiator = RuntimeEnv.newInstantiator(collectionClass);
/* 514: */ }
/* 515: */
/* 516: */ public <V> Collection<V> newMessage()
/* 517: */ {
/* 518:639 */ return (Collection)this.instantiator.newInstance();
/* 519: */ }
/* 520: */
/* 521: */ public Class<?> typeClass()
/* 522: */ {
/* 523:645 */ return this.collectionClass;
/* 524: */ }
/* 525: */ }
/* 526: */
/* 527: */ static final class RuntimeMapFactory
/* 528: */ implements MapSchema.MessageFactory
/* 529: */ {
/* 530: */ final Class<?> mapClass;
/* 531: */ final RuntimeEnv.Instantiator<?> instantiator;
/* 532: */
/* 533: */ public RuntimeMapFactory(Class<?> mapClass)
/* 534: */ {
/* 535:657 */ this.mapClass = mapClass;
/* 536:658 */ this.instantiator = RuntimeEnv.newInstantiator(mapClass);
/* 537: */ }
/* 538: */
/* 539: */ public <K, V> Map<K, V> newMessage()
/* 540: */ {
/* 541:665 */ return (Map)this.instantiator.newInstance();
/* 542: */ }
/* 543: */
/* 544: */ public Class<?> typeClass()
/* 545: */ {
/* 546:671 */ return this.mapClass;
/* 547: */ }
/* 548: */ }
/* 549: */
/* 550: */ static final class Lazy<T>
/* 551: */ extends HasSchema<T>
/* 552: */ {
/* 553: */ final Class<T> typeClass;
/* 554: */ private volatile Schema<T> schema;
/* 555: */ private volatile Pipe.Schema<T> pipeSchema;
/* 556: */
/* 557: */ Lazy(Class<T> typeClass, IdStrategy strategy)
/* 558: */ {
/* 559:684 */ super();
/* 560:685 */ this.typeClass = typeClass;
/* 561: */ }
/* 562: */
/* 563: */ public Schema<T> getSchema()
/* 564: */ {
/* 565:692 */ Schema<T> schema = this.schema;
/* 566:693 */ if (schema == null) {
/* 567:695 */ synchronized (this)
/* 568: */ {
/* 569:697 */ if ((schema = this.schema) == null) {
/* 570:699 */ if (Message.class.isAssignableFrom(this.typeClass))
/* 571: */ {
/* 572:702 */ Message<T> m = (Message)IdStrategy.createMessageInstance(this.typeClass);
/* 573:703 */ this.schema = (schema = m.cachedSchema());
/* 574: */ }
/* 575: */ else
/* 576: */ {
/* 577:709 */ this.schema = (schema = this.strategy.newSchema(this.typeClass));
/* 578: */ }
/* 579: */ }
/* 580: */ }
/* 581: */ }
/* 582:715 */ return schema;
/* 583: */ }
/* 584: */
/* 585: */ public Pipe.Schema<T> getPipeSchema()
/* 586: */ {
/* 587:721 */ Pipe.Schema<T> pipeSchema = this.pipeSchema;
/* 588:722 */ if (pipeSchema == null) {
/* 589:724 */ synchronized (this)
/* 590: */ {
/* 591:726 */ if ((pipeSchema = this.pipeSchema) == null) {
/* 592:729 */ this.pipeSchema = (pipeSchema = RuntimeSchema.resolvePipeSchema(getSchema(), this.typeClass, true));
/* 593: */ }
/* 594: */ }
/* 595: */ }
/* 596:733 */ return pipeSchema;
/* 597: */ }
/* 598: */ }
/* 599: */
/* 600: */ static final class Mapped<T>
/* 601: */ extends HasSchema<T>
/* 602: */ {
/* 603: */ final Class<? super T> baseClass;
/* 604: */ final Class<T> typeClass;
/* 605: */ private volatile HasSchema<T> wrapper;
/* 606: */
/* 607: */ Mapped(Class<? super T> baseClass, Class<T> typeClass, IdStrategy strategy)
/* 608: */ {
/* 609:747 */ super();
/* 610:748 */ this.baseClass = baseClass;
/* 611:749 */ this.typeClass = typeClass;
/* 612: */ }
/* 613: */
/* 614: */ public Schema<T> getSchema()
/* 615: */ {
/* 616:755 */ HasSchema<T> wrapper = this.wrapper;
/* 617:756 */ if (wrapper == null) {
/* 618:758 */ synchronized (this)
/* 619: */ {
/* 620:760 */ if ((wrapper = this.wrapper) == null) {
/* 621:762 */ this.wrapper = (wrapper = this.strategy.getSchemaWrapper(this.typeClass, true));
/* 622: */ }
/* 623: */ }
/* 624: */ }
/* 625:768 */ return wrapper.getSchema();
/* 626: */ }
/* 627: */
/* 628: */ public Pipe.Schema<T> getPipeSchema()
/* 629: */ {
/* 630:774 */ HasSchema<T> wrapper = this.wrapper;
/* 631:775 */ if (wrapper == null) {
/* 632:777 */ synchronized (this)
/* 633: */ {
/* 634:779 */ if ((wrapper = this.wrapper) == null) {
/* 635:781 */ this.wrapper = (wrapper = this.strategy.getSchemaWrapper(this.typeClass, true));
/* 636: */ }
/* 637: */ }
/* 638: */ }
/* 639:787 */ return wrapper.getPipeSchema();
/* 640: */ }
/* 641: */ }
/* 642: */
/* 643: */ static final class LazyRegister<T>
/* 644: */ extends HasSchema<T>
/* 645: */ {
/* 646: */ final Class<T> typeClass;
/* 647: */ private volatile Schema<T> schema;
/* 648: */ private volatile Pipe.Schema<T> pipeSchema;
/* 649: */
/* 650: */ LazyRegister(Class<T> typeClass, IdStrategy strategy)
/* 651: */ {
/* 652:800 */ super();
/* 653:801 */ this.typeClass = typeClass;
/* 654: */ }
/* 655: */
/* 656: */ public Schema<T> getSchema()
/* 657: */ {
/* 658:807 */ Schema<T> schema = this.schema;
/* 659:808 */ if (schema == null) {
/* 660:810 */ synchronized (this)
/* 661: */ {
/* 662:812 */ if ((schema = this.schema) == null) {
/* 663:815 */ this.schema = (schema = this.strategy.newSchema(this.typeClass));
/* 664: */ }
/* 665: */ }
/* 666: */ }
/* 667:820 */ return schema;
/* 668: */ }
/* 669: */
/* 670: */ public Pipe.Schema<T> getPipeSchema()
/* 671: */ {
/* 672:826 */ Pipe.Schema<T> pipeSchema = this.pipeSchema;
/* 673:827 */ if (pipeSchema == null) {
/* 674:829 */ synchronized (this)
/* 675: */ {
/* 676:831 */ if ((pipeSchema = this.pipeSchema) == null) {
/* 677:834 */ this.pipeSchema = (pipeSchema = RuntimeSchema.resolvePipeSchema(getSchema(), this.typeClass, true));
/* 678: */ }
/* 679: */ }
/* 680: */ }
/* 681:839 */ return pipeSchema;
/* 682: */ }
/* 683: */ }
/* 684: */
/* 685: */ static final class Registered<T>
/* 686: */ extends HasSchema<T>
/* 687: */ {
/* 688: */ final Schema<T> schema;
/* 689: */ private volatile Pipe.Schema<T> pipeSchema;
/* 690: */
/* 691: */ Registered(Schema<T> schema, IdStrategy strategy)
/* 692: */ {
/* 693:850 */ super();
/* 694:851 */ this.schema = schema;
/* 695: */ }
/* 696: */
/* 697: */ public Schema<T> getSchema()
/* 698: */ {
/* 699:857 */ return this.schema;
/* 700: */ }
/* 701: */
/* 702: */ public Pipe.Schema<T> getPipeSchema()
/* 703: */ {
/* 704:863 */ Pipe.Schema<T> pipeSchema = this.pipeSchema;
/* 705:864 */ if (pipeSchema == null) {
/* 706:866 */ synchronized (this)
/* 707: */ {
/* 708:868 */ if ((pipeSchema = this.pipeSchema) == null) {
/* 709:871 */ this.pipeSchema = (pipeSchema = RuntimeSchema.resolvePipeSchema(this.schema, this.schema.typeClass(), true));
/* 710: */ }
/* 711: */ }
/* 712: */ }
/* 713:876 */ return pipeSchema;
/* 714: */ }
/* 715: */ }
/* 716: */ }
/* Location: C:\Users\LX\Desktop\新建文件夹 (2)\
* Qualified Name: io.protostuff.runtime.DefaultIdStrategy
* JD-Core Version: 0.7.0.1
*/ | 31,484 | 0.512709 | 0.423747 | 726 | 41.360882 | 29.313576 | 146 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.504132 | false | false | 8 |
a0f44b9001e4f9609ba518a7a9f92cc3e4522b59 | 30,657,476,608,974 | c9eac1ae42fe5e6d25129ac6981b35a505aaea91 | /src/test/java/ru/malygin/MergeFileTest.java | 9da3614835ad1baa9c6befb5a2b7fc3ca19df8a1 | [] | no_license | Wildcall/mergeFiles | https://github.com/Wildcall/mergeFiles | f4eaad95ea0e95e75e6f80f627e9f2826ac11f7a | fbd2dfb748bc2f627306b6703940030254b9c1b3 | refs/heads/master | 2023-08-05T13:37:41.247000 | 2021-09-15T12:59:08 | 2021-09-15T12:59:08 | 404,661,829 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ru.malygin;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import ru.malygin.sort.DataType;
import ru.malygin.sort.MergeFile;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Stream;
public class MergeFileTest {
// Generate options
private static final Random random = new Random();
// Sort options
private static final String inputDir = "data/input/";
private static final String outputDir = "data/output/";
@BeforeClass
public static void beforeClass() {
try {
Files.createDirectories(Path.of(inputDir));
Files.createDirectories(Path.of(outputDir));
} catch (IOException e) {
e.printStackTrace();
}
}
@ParameterizedTest
@MethodSource("variationsParamsForTest")
public void mergeTest(int filesCount, int maxItemsInFile, DataType dataType, boolean descending, boolean preSort, boolean generate, boolean sorted) throws IOException {
// File path options
final String testDesc = dataType.toString() + "_" +
(descending ? "descending" : "ascending") + "_" +
(preSort ? "presort" : "skip") + "_" +
(generate ? "generate" : "preset") + "_" +
(sorted ? "sorted" : "unsorted");
final String currentInputDir = inputDir + testDesc + "/";
final String outputFile = outputDir + testDesc + ".txt";
// Setup MergeFile
MergeFile.setOutputFile(outputFile);
MergeFile.setDescending(descending);
MergeFile.setDataType(dataType);
long start;
if (generate) {
start = System.currentTimeMillis();
generateInputFile(currentInputDir, filesCount, maxItemsInFile, dataType, descending, sorted);
System.out.println("Генерация файлов - " + (System.currentTimeMillis() - start) + " мс.");
}
start = System.currentTimeMillis();
List<String> filePaths = new ArrayList<>(Files.list(Path.of(currentInputDir)).map(Path::toString).toList());
System.out.println("Составление списка файлов - " + (System.currentTimeMillis() - start) + " мс.");
if (preSort) {
MergeFile.presortAndMerge(filePaths);
} else {
MergeFile.merge(filePaths);
}
System.out.println("Слияние - " + (System.currentTimeMillis() - start) + " мс.");
Assertions.assertTrue(checkSort(outputFile, descending, dataType));
Assertions.assertEquals((long) filesCount * maxItemsInFile, checkCount(outputFile));
}
private static Stream<Arguments> variationsParamsForTest() {
return Stream.of(
// generate sorted data
// Count FileSize DataType descending preSort generate sorted
Arguments.of(10, 100_000, DataType.INTEGER, false, false, true, true),
Arguments.of(10, 100_000, DataType.INTEGER, true, false, true, true),
Arguments.of(10, 100_000, DataType.STRING, false, false, true, true),
Arguments.of(10, 100_000, DataType.STRING, true, false, true, true),
// generate sorted data and presort
// Count FileSize DataType descending preSort generate sorted
Arguments.of(10, 100_000, DataType.INTEGER, false, true, true, true),
Arguments.of(10, 100_000, DataType.INTEGER, true, true, true, true),
Arguments.of(10, 100_000, DataType.STRING, false, true, true, true),
Arguments.of(10, 100_000, DataType.STRING, true, true, true, true),
// generate unsorted data and presort
// Count FileSize DataType descending preSort generate sorted
Arguments.of(10, 100_000, DataType.STRING, false, true, true, false),
Arguments.of(10, 100_000, DataType.STRING, true, true, true, false),
Arguments.of(10, 100_000, DataType.INTEGER, false, true, true, false),
Arguments.of(10, 100_000, DataType.INTEGER, true, true, true, false)
);
}
@ParameterizedTest
@MethodSource("variationsParamsForBigDataTest")
public void mergeBigSizeFile(int filesCount, int maxItemsInFile, boolean descending) throws IOException {
// File path options
final String testDesc = "bigSize_" + DataType.INTEGER +
(descending ? "_descending" : "_ascending");
final String currentInputDir = inputDir + testDesc + "/";
final String outputFile = outputDir + testDesc + ".txt";
// Setup MergeFile
MergeFile.setOutputFile(outputFile);
MergeFile.setDescending(descending);
MergeFile.setDataType(DataType.INTEGER);
long start = System.currentTimeMillis();
generateInputFile(currentInputDir, filesCount, maxItemsInFile, DataType.INTEGER, descending, true);
System.out.println("Генерация файлов - " + (System.currentTimeMillis() - start) + " мс.");
start = System.currentTimeMillis();
List<String> filePaths = new ArrayList<>(Files.list(Path.of(currentInputDir)).map(Path::toString).toList());
System.out.println("Составление списка файлов - " + (System.currentTimeMillis() - start) + " мс.");
MergeFile.merge(filePaths);
System.out.println("Слияние - " + (System.currentTimeMillis() - start) + " мс.");
Assertions.assertTrue(checkSort(outputFile, descending, DataType.INTEGER));
Assertions.assertEquals((long) filesCount * maxItemsInFile, checkCount(outputFile));
}
private static Stream<Arguments> variationsParamsForBigDataTest() {
return Stream.of(
// generate sorted INTEGER data
// descending
Arguments.of(2, 100_000_000, false),
Arguments.of(2, 100_000_000, true)
);
}
@Test
public void wrongInputPath() throws IOException {
// Generate options
final int filesCount = 5;
final int maxItemsInFile = 10;
// File path options
final String testDesc = "wrong_input_path";
final String currentInputDir = inputDir + testDesc + "/";
final String outputFile = outputDir + testDesc + ".txt";
// Setup MergeFile
MergeFile.setOutputFile(outputFile);
MergeFile.setDescending(false);
MergeFile.setDataType(DataType.INTEGER);
long start = System.currentTimeMillis();
generateInputFile(currentInputDir, filesCount, maxItemsInFile, DataType.INTEGER, false, true);
System.out.println("Генерация файлов - " + (System.currentTimeMillis() - start) + " мс.");
start = System.currentTimeMillis();
List<String> filePaths = new ArrayList<>(Files.list(Path.of(currentInputDir)).map(Path::toString).toList());
// Add wrong path
filePaths.add(currentInputDir + "input5.txt");
System.out.println("Составление списка файлов - " + (System.currentTimeMillis() - start) + " мс.");
MergeFile.merge(filePaths);
System.out.println("Слияние - " + (System.currentTimeMillis() - start) + " мс.");
Assertions.assertTrue(checkSort(outputFile, false, DataType.INTEGER));
Assertions.assertEquals((long) filesCount * maxItemsInFile, checkCount(outputFile));
}
@Test
public void wrongOutputPath() throws IOException {
// Generate options
final int filesCount = 5;
final int maxItemsInFile = 10;
// File path options
final String testDesc = "wrong_output_path";
final String currentInputDir = inputDir + testDesc + "/";
// Create wrong output file path
final String outputFile = outputDir + "wrongPath/" + testDesc + ".txt";
// Setup MergeFile
try {
MergeFile.setOutputFile(outputFile);
} catch (IOException e) {
e.printStackTrace();
}
MergeFile.setDescending(false);
MergeFile.setDataType(DataType.INTEGER);
long start = System.currentTimeMillis();
generateInputFile(currentInputDir, filesCount, maxItemsInFile, DataType.INTEGER, false, true);
System.out.println("Генерация файлов - " + (System.currentTimeMillis() - start) + " мс.");
start = System.currentTimeMillis();
List<String> filePaths = new ArrayList<>(Files.list(Path.of(currentInputDir)).map(Path::toString).toList());
System.out.println("Составление списка файлов - " + (System.currentTimeMillis() - start) + " мс.");
MergeFile.merge(filePaths);
System.out.println("Слияние - " + (System.currentTimeMillis() - start) + " мс.");
Assertions.assertTrue(checkSort(MergeFile.getOutputFile(), false, DataType.INTEGER));
Assertions.assertEquals((long) filesCount * maxItemsInFile, checkCount(MergeFile.getOutputFile()));
}
private static void generateInputFile(String path, int count, int maxSize, DataType dataType, boolean descending, boolean sorted) throws IOException {
Files.createDirectories(Path.of(path));
for (int i = 0; i < count; i++) {
String filePath = path + "input" + i + ".txt";
BufferedWriter bw = getBufferedWriter(filePath);
if (dataType.equals(DataType.INTEGER)) {
if (sorted) {
writeSortedIntegerFile(bw, maxSize, descending);
} else {
writeRandomIntegerFile(bw, maxSize);
}
} else {
if (sorted){
writeSortedStringFile(bw, maxSize, descending);
} else {
writeRandomStringFile(bw, maxSize);
}
}
}
}
private static void writeSortedIntegerFile(BufferedWriter bw, int maxSize, boolean descending) throws IOException {
int k = 0;
int size = 0;
while (size != maxSize) {
if (random.nextBoolean()) {
int result = descending ? maxSize * 3 - k : k;
bw.write(Long.toString(result));
bw.newLine();
size++;
}
k++;
}
bw.close();
}
private static void writeRandomIntegerFile(BufferedWriter bw, int maxSize) throws IOException {
for (int i = 0; i < maxSize; i++) {
bw.write(Long.toString(random.nextInt(maxSize)));
bw.newLine();
}
bw.close();
}
private static void writeSortedStringFile(BufferedWriter bw, int maxSize, boolean descending) throws IOException {
StringBuilder tmp = new StringBuilder();
String[] strings = new String[maxSize];
for(int i = 0; i < maxSize; i++) {
for (int k = 0; k < random.nextInt(7) + 4; k++){
tmp.append(Character.toString(random.nextInt(26) + 97));
}
strings[i] = tmp.toString();
tmp.delete(0, tmp.length());
}
if (descending) {
Arrays.parallelSort(strings, Comparator.reverseOrder());
} else {
Arrays.parallelSort(strings);
}
Arrays.stream(strings).forEach(string -> {
try {
bw.write(string);
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
}
} );
bw.close();
}
private static void writeRandomStringFile(BufferedWriter bw, int maxSize) throws IOException {
StringBuilder tmp = new StringBuilder();
for(int i = 0; i < maxSize; i++) {
for (int k = 0; k < random.nextInt(7) + 4; k++){
tmp.append(Character.toString(random.nextInt(26) + 97));
}
bw.write(tmp.toString());
bw.newLine();
tmp.delete(0, tmp.length());
}
bw.close();
}
private static boolean checkSort(String file, boolean descending, DataType dataType) throws IOException {
BufferedReader br = getBufferReader(file);
String current = br.readLine();
String previous = current;
while (current != null) {
if (compare(current, previous, dataType, descending) >= 0) {
previous = current;
current = br.readLine();
} else {
br.close();
return false;
}
}
br.close();
return true;
}
private static long checkCount(String file) throws IOException {
BufferedReader br = getBufferReader(file);
long count = 0;
while (br.readLine() != null) {
count++;
}
br.close();
return count;
}
private static int compare(String st1, String st2, DataType dataType, boolean descending) {
int cmp;
if (dataType.equals(DataType.INTEGER)) {
try {
cmp = Integer.compare(Integer.parseInt(st1), Integer.parseInt(st2));
} catch (NumberFormatException e) {
cmp = st1.compareTo(st2);
}
} else {
cmp = st1.compareTo(st2);
}
return descending ? -cmp : cmp;
}
private static BufferedReader getBufferReader(String filePath) throws IOException {
return new BufferedReader(
new InputStreamReader(
new FileInputStream(filePath), StandardCharsets.UTF_8));
}
private static BufferedWriter getBufferedWriter(String filePath) throws IOException {
return new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(filePath),StandardCharsets.UTF_8));
}
} | UTF-8 | Java | 14,634 | java | MergeFileTest.java | Java | [] | null | [] | package ru.malygin;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import ru.malygin.sort.DataType;
import ru.malygin.sort.MergeFile;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Stream;
public class MergeFileTest {
// Generate options
private static final Random random = new Random();
// Sort options
private static final String inputDir = "data/input/";
private static final String outputDir = "data/output/";
@BeforeClass
public static void beforeClass() {
try {
Files.createDirectories(Path.of(inputDir));
Files.createDirectories(Path.of(outputDir));
} catch (IOException e) {
e.printStackTrace();
}
}
@ParameterizedTest
@MethodSource("variationsParamsForTest")
public void mergeTest(int filesCount, int maxItemsInFile, DataType dataType, boolean descending, boolean preSort, boolean generate, boolean sorted) throws IOException {
// File path options
final String testDesc = dataType.toString() + "_" +
(descending ? "descending" : "ascending") + "_" +
(preSort ? "presort" : "skip") + "_" +
(generate ? "generate" : "preset") + "_" +
(sorted ? "sorted" : "unsorted");
final String currentInputDir = inputDir + testDesc + "/";
final String outputFile = outputDir + testDesc + ".txt";
// Setup MergeFile
MergeFile.setOutputFile(outputFile);
MergeFile.setDescending(descending);
MergeFile.setDataType(dataType);
long start;
if (generate) {
start = System.currentTimeMillis();
generateInputFile(currentInputDir, filesCount, maxItemsInFile, dataType, descending, sorted);
System.out.println("Генерация файлов - " + (System.currentTimeMillis() - start) + " мс.");
}
start = System.currentTimeMillis();
List<String> filePaths = new ArrayList<>(Files.list(Path.of(currentInputDir)).map(Path::toString).toList());
System.out.println("Составление списка файлов - " + (System.currentTimeMillis() - start) + " мс.");
if (preSort) {
MergeFile.presortAndMerge(filePaths);
} else {
MergeFile.merge(filePaths);
}
System.out.println("Слияние - " + (System.currentTimeMillis() - start) + " мс.");
Assertions.assertTrue(checkSort(outputFile, descending, dataType));
Assertions.assertEquals((long) filesCount * maxItemsInFile, checkCount(outputFile));
}
private static Stream<Arguments> variationsParamsForTest() {
return Stream.of(
// generate sorted data
// Count FileSize DataType descending preSort generate sorted
Arguments.of(10, 100_000, DataType.INTEGER, false, false, true, true),
Arguments.of(10, 100_000, DataType.INTEGER, true, false, true, true),
Arguments.of(10, 100_000, DataType.STRING, false, false, true, true),
Arguments.of(10, 100_000, DataType.STRING, true, false, true, true),
// generate sorted data and presort
// Count FileSize DataType descending preSort generate sorted
Arguments.of(10, 100_000, DataType.INTEGER, false, true, true, true),
Arguments.of(10, 100_000, DataType.INTEGER, true, true, true, true),
Arguments.of(10, 100_000, DataType.STRING, false, true, true, true),
Arguments.of(10, 100_000, DataType.STRING, true, true, true, true),
// generate unsorted data and presort
// Count FileSize DataType descending preSort generate sorted
Arguments.of(10, 100_000, DataType.STRING, false, true, true, false),
Arguments.of(10, 100_000, DataType.STRING, true, true, true, false),
Arguments.of(10, 100_000, DataType.INTEGER, false, true, true, false),
Arguments.of(10, 100_000, DataType.INTEGER, true, true, true, false)
);
}
@ParameterizedTest
@MethodSource("variationsParamsForBigDataTest")
public void mergeBigSizeFile(int filesCount, int maxItemsInFile, boolean descending) throws IOException {
// File path options
final String testDesc = "bigSize_" + DataType.INTEGER +
(descending ? "_descending" : "_ascending");
final String currentInputDir = inputDir + testDesc + "/";
final String outputFile = outputDir + testDesc + ".txt";
// Setup MergeFile
MergeFile.setOutputFile(outputFile);
MergeFile.setDescending(descending);
MergeFile.setDataType(DataType.INTEGER);
long start = System.currentTimeMillis();
generateInputFile(currentInputDir, filesCount, maxItemsInFile, DataType.INTEGER, descending, true);
System.out.println("Генерация файлов - " + (System.currentTimeMillis() - start) + " мс.");
start = System.currentTimeMillis();
List<String> filePaths = new ArrayList<>(Files.list(Path.of(currentInputDir)).map(Path::toString).toList());
System.out.println("Составление списка файлов - " + (System.currentTimeMillis() - start) + " мс.");
MergeFile.merge(filePaths);
System.out.println("Слияние - " + (System.currentTimeMillis() - start) + " мс.");
Assertions.assertTrue(checkSort(outputFile, descending, DataType.INTEGER));
Assertions.assertEquals((long) filesCount * maxItemsInFile, checkCount(outputFile));
}
private static Stream<Arguments> variationsParamsForBigDataTest() {
return Stream.of(
// generate sorted INTEGER data
// descending
Arguments.of(2, 100_000_000, false),
Arguments.of(2, 100_000_000, true)
);
}
@Test
public void wrongInputPath() throws IOException {
// Generate options
final int filesCount = 5;
final int maxItemsInFile = 10;
// File path options
final String testDesc = "wrong_input_path";
final String currentInputDir = inputDir + testDesc + "/";
final String outputFile = outputDir + testDesc + ".txt";
// Setup MergeFile
MergeFile.setOutputFile(outputFile);
MergeFile.setDescending(false);
MergeFile.setDataType(DataType.INTEGER);
long start = System.currentTimeMillis();
generateInputFile(currentInputDir, filesCount, maxItemsInFile, DataType.INTEGER, false, true);
System.out.println("Генерация файлов - " + (System.currentTimeMillis() - start) + " мс.");
start = System.currentTimeMillis();
List<String> filePaths = new ArrayList<>(Files.list(Path.of(currentInputDir)).map(Path::toString).toList());
// Add wrong path
filePaths.add(currentInputDir + "input5.txt");
System.out.println("Составление списка файлов - " + (System.currentTimeMillis() - start) + " мс.");
MergeFile.merge(filePaths);
System.out.println("Слияние - " + (System.currentTimeMillis() - start) + " мс.");
Assertions.assertTrue(checkSort(outputFile, false, DataType.INTEGER));
Assertions.assertEquals((long) filesCount * maxItemsInFile, checkCount(outputFile));
}
@Test
public void wrongOutputPath() throws IOException {
// Generate options
final int filesCount = 5;
final int maxItemsInFile = 10;
// File path options
final String testDesc = "wrong_output_path";
final String currentInputDir = inputDir + testDesc + "/";
// Create wrong output file path
final String outputFile = outputDir + "wrongPath/" + testDesc + ".txt";
// Setup MergeFile
try {
MergeFile.setOutputFile(outputFile);
} catch (IOException e) {
e.printStackTrace();
}
MergeFile.setDescending(false);
MergeFile.setDataType(DataType.INTEGER);
long start = System.currentTimeMillis();
generateInputFile(currentInputDir, filesCount, maxItemsInFile, DataType.INTEGER, false, true);
System.out.println("Генерация файлов - " + (System.currentTimeMillis() - start) + " мс.");
start = System.currentTimeMillis();
List<String> filePaths = new ArrayList<>(Files.list(Path.of(currentInputDir)).map(Path::toString).toList());
System.out.println("Составление списка файлов - " + (System.currentTimeMillis() - start) + " мс.");
MergeFile.merge(filePaths);
System.out.println("Слияние - " + (System.currentTimeMillis() - start) + " мс.");
Assertions.assertTrue(checkSort(MergeFile.getOutputFile(), false, DataType.INTEGER));
Assertions.assertEquals((long) filesCount * maxItemsInFile, checkCount(MergeFile.getOutputFile()));
}
private static void generateInputFile(String path, int count, int maxSize, DataType dataType, boolean descending, boolean sorted) throws IOException {
Files.createDirectories(Path.of(path));
for (int i = 0; i < count; i++) {
String filePath = path + "input" + i + ".txt";
BufferedWriter bw = getBufferedWriter(filePath);
if (dataType.equals(DataType.INTEGER)) {
if (sorted) {
writeSortedIntegerFile(bw, maxSize, descending);
} else {
writeRandomIntegerFile(bw, maxSize);
}
} else {
if (sorted){
writeSortedStringFile(bw, maxSize, descending);
} else {
writeRandomStringFile(bw, maxSize);
}
}
}
}
private static void writeSortedIntegerFile(BufferedWriter bw, int maxSize, boolean descending) throws IOException {
int k = 0;
int size = 0;
while (size != maxSize) {
if (random.nextBoolean()) {
int result = descending ? maxSize * 3 - k : k;
bw.write(Long.toString(result));
bw.newLine();
size++;
}
k++;
}
bw.close();
}
private static void writeRandomIntegerFile(BufferedWriter bw, int maxSize) throws IOException {
for (int i = 0; i < maxSize; i++) {
bw.write(Long.toString(random.nextInt(maxSize)));
bw.newLine();
}
bw.close();
}
private static void writeSortedStringFile(BufferedWriter bw, int maxSize, boolean descending) throws IOException {
StringBuilder tmp = new StringBuilder();
String[] strings = new String[maxSize];
for(int i = 0; i < maxSize; i++) {
for (int k = 0; k < random.nextInt(7) + 4; k++){
tmp.append(Character.toString(random.nextInt(26) + 97));
}
strings[i] = tmp.toString();
tmp.delete(0, tmp.length());
}
if (descending) {
Arrays.parallelSort(strings, Comparator.reverseOrder());
} else {
Arrays.parallelSort(strings);
}
Arrays.stream(strings).forEach(string -> {
try {
bw.write(string);
bw.newLine();
} catch (IOException e) {
e.printStackTrace();
}
} );
bw.close();
}
private static void writeRandomStringFile(BufferedWriter bw, int maxSize) throws IOException {
StringBuilder tmp = new StringBuilder();
for(int i = 0; i < maxSize; i++) {
for (int k = 0; k < random.nextInt(7) + 4; k++){
tmp.append(Character.toString(random.nextInt(26) + 97));
}
bw.write(tmp.toString());
bw.newLine();
tmp.delete(0, tmp.length());
}
bw.close();
}
private static boolean checkSort(String file, boolean descending, DataType dataType) throws IOException {
BufferedReader br = getBufferReader(file);
String current = br.readLine();
String previous = current;
while (current != null) {
if (compare(current, previous, dataType, descending) >= 0) {
previous = current;
current = br.readLine();
} else {
br.close();
return false;
}
}
br.close();
return true;
}
private static long checkCount(String file) throws IOException {
BufferedReader br = getBufferReader(file);
long count = 0;
while (br.readLine() != null) {
count++;
}
br.close();
return count;
}
private static int compare(String st1, String st2, DataType dataType, boolean descending) {
int cmp;
if (dataType.equals(DataType.INTEGER)) {
try {
cmp = Integer.compare(Integer.parseInt(st1), Integer.parseInt(st2));
} catch (NumberFormatException e) {
cmp = st1.compareTo(st2);
}
} else {
cmp = st1.compareTo(st2);
}
return descending ? -cmp : cmp;
}
private static BufferedReader getBufferReader(String filePath) throws IOException {
return new BufferedReader(
new InputStreamReader(
new FileInputStream(filePath), StandardCharsets.UTF_8));
}
private static BufferedWriter getBufferedWriter(String filePath) throws IOException {
return new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(filePath),StandardCharsets.UTF_8));
}
} | 14,634 | 0.584269 | 0.573319 | 355 | 39.650703 | 34.686146 | 172 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.909859 | false | false | 8 |
487e3b277f288cebe36657f263d7d12c4ec20f17 | 7,559,142,489,525 | 1f4ea412c98e954bab573ae4f216367803598560 | /src/main/java/mx/com/bq/java/examples/e7/map/MapApp.java | 918ca87feda26fdd218ed75473334896b9eb652f | [] | no_license | LuFerMX/ejercicios-j8 | https://github.com/LuFerMX/ejercicios-j8 | c795ab1bfa1e4d901dc3197f5a071b8f2c8b6c2d | 327266bc3832b73cbb9afe8a2520b9e285e586ac | refs/heads/master | 2021-09-14T18:56:12.134000 | 2018-05-17T17:07:16 | 2018-05-17T17:07:16 | 126,048,770 | 0 | 0 | null | false | 2018-03-20T18:49:12 | 2018-03-20T16:32:40 | 2018-03-20T16:32:43 | 2018-03-20T18:49:11 | 1 | 0 | 0 | 0 | null | false | null | package mx.com.bq.java.examples.e7.map;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collector;
import java.util.stream.Collectors;
public class MapApp {
private Map<Integer, String> map;
public void poblar() {
map = new HashMap<>();
map.put(1, "Juan");
map.put(2, "Rodrigo");
map.put(3, "Zamano");
map.put(4, "Alberto");
map.put(5, "Pablo");
}
public void imprimir_v7() {
for (Entry <Integer, String> e : map.entrySet()) {
System.out.println("Key : "+ e.getKey() + " Valor: "+ e.getValue());
}
}
public void imprimir_v8() {
// map.forEach((k,v) -> System.out.println("K : "+ k + " V: "+ v ) );
map.entrySet().stream().forEach(System.out::println);
}
public void recoleactar(){
Map<Integer, String> recolectado = map.entrySet().stream()
.filter(e->e.getValue().contains("J"))
.collect(Collectors.toMap(p -> p.getKey(), p-> p.getValue()));
recolectado.entrySet().stream().forEach(System.out::println);
}
public void insertarSiAusente() {
map.putIfAbsent(6, "Jaime");
}
public void operarSiPresente() {
map.computeIfPresent(3, (k,v) -> k+v );
System.out.println(map.get(3));
}
public void obtenerOrPredeterminado() {
String valor = map.getOrDefault(6, "Valor Default");
System.out.println(valor);
}
public static void main(String[] args) {
MapApp app = new MapApp();
app.poblar();
//app.imprimir_v7();
app.insertarSiAusente();
//app.imprimir_v8();
//app.operarSiPresente();
//app.obtenerOrPredeterminado();
app.recoleactar();
}
}
| UTF-8 | Java | 1,875 | java | MapApp.java | Java | [
{
"context": " map = new HashMap<>();\n map.put(1, \"Juan\");\n map.put(2, \"Rodrigo\");\n map.put",
"end": 350,
"score": 0.9996887445449829,
"start": 346,
"tag": "NAME",
"value": "Juan"
},
{
"context": ";\n map.put(1, \"Juan\");\n map.put(2, ... | null | [] | package mx.com.bq.java.examples.e7.map;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collector;
import java.util.stream.Collectors;
public class MapApp {
private Map<Integer, String> map;
public void poblar() {
map = new HashMap<>();
map.put(1, "Juan");
map.put(2, "Rodrigo");
map.put(3, "Zamano");
map.put(4, "Alberto");
map.put(5, "Pablo");
}
public void imprimir_v7() {
for (Entry <Integer, String> e : map.entrySet()) {
System.out.println("Key : "+ e.getKey() + " Valor: "+ e.getValue());
}
}
public void imprimir_v8() {
// map.forEach((k,v) -> System.out.println("K : "+ k + " V: "+ v ) );
map.entrySet().stream().forEach(System.out::println);
}
public void recoleactar(){
Map<Integer, String> recolectado = map.entrySet().stream()
.filter(e->e.getValue().contains("J"))
.collect(Collectors.toMap(p -> p.getKey(), p-> p.getValue()));
recolectado.entrySet().stream().forEach(System.out::println);
}
public void insertarSiAusente() {
map.putIfAbsent(6, "Jaime");
}
public void operarSiPresente() {
map.computeIfPresent(3, (k,v) -> k+v );
System.out.println(map.get(3));
}
public void obtenerOrPredeterminado() {
String valor = map.getOrDefault(6, "Valor Default");
System.out.println(valor);
}
public static void main(String[] args) {
MapApp app = new MapApp();
app.poblar();
//app.imprimir_v7();
app.insertarSiAusente();
//app.imprimir_v8();
//app.operarSiPresente();
//app.obtenerOrPredeterminado();
app.recoleactar();
}
}
| 1,875 | 0.546133 | 0.538667 | 69 | 26.173914 | 20.785975 | 80 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.652174 | false | false | 8 |
1e2d79b0b3406711bccf6a0829102754c4019a33 | 30,227,979,881,655 | 907e68ec0a564b203edbe89367fffa8b2064f145 | /app/src/main/java/com/example/edejesus1097/miniproj/TempTime.java | 7d92d42019211e673dd4eb1e1b668fc1c22fda87 | [] | no_license | ericdejesus/TempConnect | https://github.com/ericdejesus/TempConnect | 8bff25476222144c3d4d450bbf2005000f57253b | c00c42b7d703ff1c421c45de3ad60b9586fce0b8 | refs/heads/master | 2020-03-28T16:22:52.630000 | 2018-09-20T04:32:22 | 2018-09-20T04:32:22 | 148,688,694 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.edejesus1097.miniproj;
import java.util.ArrayList;
import java.util.List;
public class TempTime {
public List<Integer> Time = new ArrayList<Integer>();
public List<Integer> Temp = new ArrayList<Integer>();
public TempTime(){}
public TempTime(Integer inTime[],Integer inTemp[],Integer size) {
//inserting list into the class time and temperature
if (size == inTemp.length && size == inTime.length) {
for(int i =0; i <size ; i++)
{
Time.add(inTime[i]);
Temp.add(inTemp[i]);
}
}
}
}
| UTF-8 | Java | 615 | java | TempTime.java | Java | [
{
"context": "package com.example.edejesus1097.miniproj;\nimport java.util.ArrayList;\nimport java",
"end": 32,
"score": 0.9929313063621521,
"start": 20,
"tag": "USERNAME",
"value": "edejesus1097"
}
] | null | [] | package com.example.edejesus1097.miniproj;
import java.util.ArrayList;
import java.util.List;
public class TempTime {
public List<Integer> Time = new ArrayList<Integer>();
public List<Integer> Temp = new ArrayList<Integer>();
public TempTime(){}
public TempTime(Integer inTime[],Integer inTemp[],Integer size) {
//inserting list into the class time and temperature
if (size == inTemp.length && size == inTime.length) {
for(int i =0; i <size ; i++)
{
Time.add(inTime[i]);
Temp.add(inTemp[i]);
}
}
}
}
| 615 | 0.586992 | 0.578862 | 23 | 25.73913 | 22.63936 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.478261 | false | false | 8 |
936178cade3e34e9a2342f829ebd274c89caa8cf | 6,296,422,125,083 | 33eedf0f06c9562aa32ad3c6b4694ce5ba0d01fd | /meritnations/src/test/java/test/DemoMaven.java | cff54686a29809af313e9c5c9bddc73e7646f41a | [] | no_license | AnkushAutomation/Meritnation | https://github.com/AnkushAutomation/Meritnation | 19a512627ef99d9d8cbfe2f94afdb2ee1b52f5a4 | fed70acb37fba2440e830298ce1547510d979a73 | refs/heads/master | 2020-03-22T01:32:40.327000 | 2018-07-14T07:55:24 | 2018-07-14T07:55:24 | 139,312,470 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package test;
import org.testng.annotations.Test;
public class DemoMaven {
@Test
public void testHello() {
/**Hello World**/
System.out.println("Welcome to Maven World");
}
}
| UTF-8 | Java | 201 | java | DemoMaven.java | Java | [] | null | [] | package test;
import org.testng.annotations.Test;
public class DemoMaven {
@Test
public void testHello() {
/**Hello World**/
System.out.println("Welcome to Maven World");
}
}
| 201 | 0.641791 | 0.641791 | 13 | 13.384615 | 15.01045 | 47 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.846154 | false | false | 8 |
94b45b315c0887a19fc281a396de45ddb2a46fb0 | 23,493,471,163,820 | b73e83d59032875f04f90200be6c20bcee0e7ad0 | /src/main/java/com/ky/clothing/service/impl/GoodsServiceImpl.java | f79a1316a42d9ec52716b430951a77053b91c704 | [] | no_license | Daye1112/clothingOrderPro | https://github.com/Daye1112/clothingOrderPro | f32f84aee6def146ec2cb01a0a75c21b2cf18849 | be42c97f1dac2a0bc6aebc59581923792b7764f1 | refs/heads/master | 2022-12-22T07:42:12.494000 | 2019-12-24T02:48:40 | 2019-12-24T02:48:40 | 199,277,844 | 0 | 1 | null | false | 2022-12-16T04:49:25 | 2019-07-28T11:18:59 | 2019-12-24T02:48:45 | 2022-12-16T04:49:22 | 10,933 | 0 | 1 | 16 | CSS | false | false | package com.ky.clothing.service.impl;
import com.ky.clothing.dao.GoodsMapper;
import com.ky.clothing.entity.Goods;
import com.ky.clothing.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Daye
* Goods表Service层实现类
*/
@Service
public class GoodsServiceImpl implements GoodsService {
private GoodsMapper goodsMapper;
@Transactional(rollbackFor = Exception.class)
@Override
public int updateByPrimaryKeySelective(Goods goods) {
return goodsMapper.updateByPrimaryKeySelective(goods);
}
@Transactional(rollbackFor = Exception.class)
@Override
public int insertSelective(Goods goods) {
return goodsMapper.insertSelective(goods);
}
@Transactional(rollbackFor = Exception.class)
@Override
public void updateGoodsValidByGoodsId(Integer goodsId) {
goodsMapper.updateGoodsValidByGoodsId(goodsId);
}
@Transactional(rollbackFor = Exception.class, readOnly = true)
@Override
public Map<String, Object> selectAllBaseInfoLimit(Integer startIndex, Integer pageSize) {
Map<String, Object> goodsInfoMap = new HashMap<>();
List<Goods> goodsList = goodsMapper.selectAllBaseInfoLimit(startIndex, pageSize);
Integer totalRecording = goodsMapper.selectTotalRecordingCountGoodsId();
Integer totalPage = (totalRecording + pageSize + 1) / pageSize;
goodsInfoMap.put("goodsList", goodsList);
goodsInfoMap.put("totalPage", totalPage);
return goodsInfoMap;
}
@Transactional(rollbackFor = Exception.class)
@Override
public void updateGoodsStockByGoodsId(Integer cartId) {
goodsMapper.updateGoodsStockByGoodsId(cartId);
}
@Transactional(rollbackFor = Exception.class, readOnly = true)
@Override
public Goods selectFuzzyByGoodsName(String goodsName) {
return goodsMapper.selectFuzzyByGoodsName("%" + goodsName + "%");
}
@Transactional(rollbackFor = Exception.class)
@Override
public void updateGoodsStockSelfByGoodsId(Integer goodsId) {
goodsMapper.updateGoodsStockSelfByGoodsId(goodsId);
}
@Transactional(rollbackFor = Exception.class)
@Override
public void updateGoodsScoreByGoodsId(Goods goods) {
goodsMapper.updateGoodsScoreByGoodsId(goods);
}
@Transactional(rollbackFor = Exception.class, readOnly = true)
@Override
public List<Map<String, Object>> selectByVisitNumLimitFour() {
return goodsMapper.selectByVisitNumLimitFour();
}
@Transactional(rollbackFor = Exception.class)
@Override
public void updateVisitNumIncByGoodsId(Integer goodsId) {
goodsMapper.updateVisitNumIncByGoodsId(goodsId);
}
@Transactional(rollbackFor = Exception.class, readOnly = true)
@Override
public List<Goods> selectGoodsLimit(Integer pageNow, Integer pageSize) {
Integer startIndex = (pageNow - 1) * pageSize;
return goodsMapper.selectGoodsLimit(startIndex, pageSize);
}
@Transactional(rollbackFor = Exception.class, readOnly = true)
@Override
public Goods selectByPrimaryKey(Integer goodsId) {
return goodsMapper.selectByPrimaryKey(goodsId);
}
@Transactional(rollbackFor = Exception.class, readOnly = true)
@Override
public List<Goods> selectGoodsTopThree() {
return goodsMapper.selectGoodsTopThree();
}
@Autowired
public void setGoodsMapper(GoodsMapper goodsMapper) {
this.goodsMapper = goodsMapper;
}
@Override
public int selectGoodsCount() {
return goodsMapper.selectGoodsCount();
}
}
| UTF-8 | Java | 3,813 | java | GoodsServiceImpl.java | Java | [
{
"context": "a.util.List;\nimport java.util.Map;\n\n/**\n * @author Daye\n * Goods表Service层实现类\n */\n@Service\npublic class Go",
"end": 428,
"score": 0.9990240931510925,
"start": 424,
"tag": "USERNAME",
"value": "Daye"
}
] | null | [] | package com.ky.clothing.service.impl;
import com.ky.clothing.dao.GoodsMapper;
import com.ky.clothing.entity.Goods;
import com.ky.clothing.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Daye
* Goods表Service层实现类
*/
@Service
public class GoodsServiceImpl implements GoodsService {
private GoodsMapper goodsMapper;
@Transactional(rollbackFor = Exception.class)
@Override
public int updateByPrimaryKeySelective(Goods goods) {
return goodsMapper.updateByPrimaryKeySelective(goods);
}
@Transactional(rollbackFor = Exception.class)
@Override
public int insertSelective(Goods goods) {
return goodsMapper.insertSelective(goods);
}
@Transactional(rollbackFor = Exception.class)
@Override
public void updateGoodsValidByGoodsId(Integer goodsId) {
goodsMapper.updateGoodsValidByGoodsId(goodsId);
}
@Transactional(rollbackFor = Exception.class, readOnly = true)
@Override
public Map<String, Object> selectAllBaseInfoLimit(Integer startIndex, Integer pageSize) {
Map<String, Object> goodsInfoMap = new HashMap<>();
List<Goods> goodsList = goodsMapper.selectAllBaseInfoLimit(startIndex, pageSize);
Integer totalRecording = goodsMapper.selectTotalRecordingCountGoodsId();
Integer totalPage = (totalRecording + pageSize + 1) / pageSize;
goodsInfoMap.put("goodsList", goodsList);
goodsInfoMap.put("totalPage", totalPage);
return goodsInfoMap;
}
@Transactional(rollbackFor = Exception.class)
@Override
public void updateGoodsStockByGoodsId(Integer cartId) {
goodsMapper.updateGoodsStockByGoodsId(cartId);
}
@Transactional(rollbackFor = Exception.class, readOnly = true)
@Override
public Goods selectFuzzyByGoodsName(String goodsName) {
return goodsMapper.selectFuzzyByGoodsName("%" + goodsName + "%");
}
@Transactional(rollbackFor = Exception.class)
@Override
public void updateGoodsStockSelfByGoodsId(Integer goodsId) {
goodsMapper.updateGoodsStockSelfByGoodsId(goodsId);
}
@Transactional(rollbackFor = Exception.class)
@Override
public void updateGoodsScoreByGoodsId(Goods goods) {
goodsMapper.updateGoodsScoreByGoodsId(goods);
}
@Transactional(rollbackFor = Exception.class, readOnly = true)
@Override
public List<Map<String, Object>> selectByVisitNumLimitFour() {
return goodsMapper.selectByVisitNumLimitFour();
}
@Transactional(rollbackFor = Exception.class)
@Override
public void updateVisitNumIncByGoodsId(Integer goodsId) {
goodsMapper.updateVisitNumIncByGoodsId(goodsId);
}
@Transactional(rollbackFor = Exception.class, readOnly = true)
@Override
public List<Goods> selectGoodsLimit(Integer pageNow, Integer pageSize) {
Integer startIndex = (pageNow - 1) * pageSize;
return goodsMapper.selectGoodsLimit(startIndex, pageSize);
}
@Transactional(rollbackFor = Exception.class, readOnly = true)
@Override
public Goods selectByPrimaryKey(Integer goodsId) {
return goodsMapper.selectByPrimaryKey(goodsId);
}
@Transactional(rollbackFor = Exception.class, readOnly = true)
@Override
public List<Goods> selectGoodsTopThree() {
return goodsMapper.selectGoodsTopThree();
}
@Autowired
public void setGoodsMapper(GoodsMapper goodsMapper) {
this.goodsMapper = goodsMapper;
}
@Override
public int selectGoodsCount() {
return goodsMapper.selectGoodsCount();
}
}
| 3,813 | 0.726269 | 0.725743 | 117 | 31.504274 | 26.54093 | 93 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.410256 | false | false | 8 |
e1aaaca8d88ccce25f676483c29c8a47e6c9c7ad | 7,490,423,020,055 | b6f2180b288d08ddca19792479a9ecfc094e22a5 | /src/main/java/gildedrose/InnHttpServer.java | 2e8182bc28c89479ef7db48f84cd85e214a05462 | [] | no_license | digideskio/CodeStoryStep2 | https://github.com/digideskio/CodeStoryStep2 | 359e56ca493c9ad1ac84a065babeb8e61e1bf63a | 57f463f1f51b07772bcc2a4e9e0fdb53704ac5fc | refs/heads/master | 2021-01-13T07:22:59.165000 | 2012-03-28T21:36:40 | 2012-03-28T21:36:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package gildedrose;
import com.google.common.base.*;
import com.sun.jersey.api.container.httpserver.*;
import com.sun.net.httpserver.HttpServer;
import lombok.*;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.util.*;
import static java.lang.String.format;
import static net.gageot.listmaker.ListMaker.*;
@Path("/")
public class InnHttpServer extends AbstractResource {
private static Inn inn = new Inn();
@GET
@Produces("text/html")
public Response index() {
return file("index.html");
}
@GET
@Path("/updateQuality")
public Response updateQuality() {
inn.updateQuality();
return redirect("/");
}
@GET
@Path("/reset")
public Response reset() {
inn = new Inn();
return redirect("/");
}
@GET
@Produces("application/json")
@Path("/inventory.json")
public List<IndexedItem> inventory() {
return with(inn.getItems()).to(new Function<Item, IndexedItem>() {
int index;
@Override
public IndexedItem apply(Item item) {
return new IndexedItem(item, index++);
}
}).toList();
}
@GET
@Path("/web/{path: .*}")
public Response staticResource(@PathParam("path") String path) {
return file(path);
}
@AllArgsConstructor
static class IndexedItem {
@Delegate Item item;
@Getter int index;
}
public static HttpServer start(int port) throws Exception {
HttpServer httpServer = HttpServerFactory.create(format("http://localhost:%d/", port));
httpServer.start();
return httpServer;
}
public static void main(String[] args) throws Exception {
start(9090);
}
}
| UTF-8 | Java | 1,564 | java | InnHttpServer.java | Java | [] | null | [] | package gildedrose;
import com.google.common.base.*;
import com.sun.jersey.api.container.httpserver.*;
import com.sun.net.httpserver.HttpServer;
import lombok.*;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.util.*;
import static java.lang.String.format;
import static net.gageot.listmaker.ListMaker.*;
@Path("/")
public class InnHttpServer extends AbstractResource {
private static Inn inn = new Inn();
@GET
@Produces("text/html")
public Response index() {
return file("index.html");
}
@GET
@Path("/updateQuality")
public Response updateQuality() {
inn.updateQuality();
return redirect("/");
}
@GET
@Path("/reset")
public Response reset() {
inn = new Inn();
return redirect("/");
}
@GET
@Produces("application/json")
@Path("/inventory.json")
public List<IndexedItem> inventory() {
return with(inn.getItems()).to(new Function<Item, IndexedItem>() {
int index;
@Override
public IndexedItem apply(Item item) {
return new IndexedItem(item, index++);
}
}).toList();
}
@GET
@Path("/web/{path: .*}")
public Response staticResource(@PathParam("path") String path) {
return file(path);
}
@AllArgsConstructor
static class IndexedItem {
@Delegate Item item;
@Getter int index;
}
public static HttpServer start(int port) throws Exception {
HttpServer httpServer = HttpServerFactory.create(format("http://localhost:%d/", port));
httpServer.start();
return httpServer;
}
public static void main(String[] args) throws Exception {
start(9090);
}
}
| 1,564 | 0.680946 | 0.678389 | 74 | 20.135136 | 19.707541 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.243243 | false | false | 8 |
f82bfe59d95cba5c1318523055233d7e7da1514d | 31,928,786,925,465 | 6a37da1adf986eb9691a6abd7710e990bc3bffa6 | /modules/hibernate5/test/src/net/oschina/j2cache/hibernate5/service/ArticleService.java | 64d5ee665b191c1290d45cdf158eb2be06570571 | [
"Apache-2.0"
] | permissive | YuriLuo/J2Cache | https://github.com/YuriLuo/J2Cache | 2f5da8dca23f083d96370fbfb932b160253c61db | 9b93f810d0274a1b3f8a72ca250cb46e0870314a | refs/heads/master | 2022-12-22T03:41:07.705000 | 2021-01-07T05:29:15 | 2021-01-07T05:29:15 | 230,865,683 | 2 | 0 | Apache-2.0 | false | 2022-12-10T05:19:53 | 2019-12-30T07:02:45 | 2022-05-06T11:08:46 | 2022-12-10T05:19:52 | 310 | 1 | 0 | 11 | Java | false | false | package net.oschina.j2cache.hibernate5.service;
import net.oschina.j2cache.hibernate5.bean.Article;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.List;
@Transactional
@Service
public class ArticleService implements IArticleService {
@Resource
private SessionFactory sessionFactory;
protected Session getSession() {
return this.sessionFactory.getCurrentSession();
}
public void save(Article article) {
getSession().saveOrUpdate(article);
}
public List<Article> find(Criterion... criterions) {
Criteria criteria = getSession().createCriteria(Article.class);
for (Criterion c : criterions) {
criteria.add(c);
}
criteria.setCacheable(true);
return criteria.list();
}
public void delete(String id) {
getSession().delete(getSession().get(Article.class, id));
}
public Article findUnique(Criterion... criterions) {
Criteria criteria = getSession().createCriteria(Article.class);
for (Criterion c : criterions) {
criteria.add(c);
}
criteria.setCacheable(true);
return (Article)criteria.uniqueResult();
}
public Article get(String id) {
return (Article)getSession().get(Article.class,id);
}
}
| UTF-8 | Java | 1,518 | java | ArticleService.java | Java | [] | null | [] | package net.oschina.j2cache.hibernate5.service;
import net.oschina.j2cache.hibernate5.bean.Article;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.List;
@Transactional
@Service
public class ArticleService implements IArticleService {
@Resource
private SessionFactory sessionFactory;
protected Session getSession() {
return this.sessionFactory.getCurrentSession();
}
public void save(Article article) {
getSession().saveOrUpdate(article);
}
public List<Article> find(Criterion... criterions) {
Criteria criteria = getSession().createCriteria(Article.class);
for (Criterion c : criterions) {
criteria.add(c);
}
criteria.setCacheable(true);
return criteria.list();
}
public void delete(String id) {
getSession().delete(getSession().get(Article.class, id));
}
public Article findUnique(Criterion... criterions) {
Criteria criteria = getSession().createCriteria(Article.class);
for (Criterion c : criterions) {
criteria.add(c);
}
criteria.setCacheable(true);
return (Article)criteria.uniqueResult();
}
public Article get(String id) {
return (Article)getSession().get(Article.class,id);
}
}
| 1,518 | 0.6917 | 0.689065 | 54 | 27.111111 | 21.737207 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.462963 | false | false | 8 |
2774985bdc1549d2e0a6a27bd5c5e736d74b2a58 | 7,267,084,712,886 | 84c31d752d3f13486b5ea1f8b0ccbd8f7a293f8e | /SPRING CLOUD/components-client-3/src/main/java/com/components/client2/dto/UserTypeEntity.java | c006746a112aa9eb2606ab061b956db78c28da55 | [] | no_license | LEXXAR1997/AppsJava | https://github.com/LEXXAR1997/AppsJava | 922a3675d4c8f64f67573bcf0a534c0be0c881c3 | 9835d10bd3d2b5afdcaf51d81936c1dc96ef7003 | refs/heads/master | 2023-07-29T13:03:56.845000 | 2021-09-02T19:21:13 | 2021-09-02T19:21:13 | 379,742,892 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.components.client2.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class UserTypeEntity {
int ID;
String name;
public UserTypeEntity(String name) {
super();
this.name = name;
}
}
| UTF-8 | Java | 338 | java | UserTypeEntity.java | Java | [] | null | [] | package com.components.client2.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class UserTypeEntity {
int ID;
String name;
public UserTypeEntity(String name) {
super();
this.name = name;
}
}
| 338 | 0.760355 | 0.757396 | 24 | 13.083333 | 12.519707 | 37 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.875 | false | false | 8 |
6ffd3a13b4776b7de504a5b7bda0635235febc64 | 7,267,084,714,264 | 2a8bf37084a9fd7dca396e6744ae946daf319a2e | /test/src/org/lf2019/lf1021/NPhone.java | e863c512ed9f4e64743ce220094def9b1b9abefb | [] | no_license | FizzCool/test | https://github.com/FizzCool/test | dd92cff59c7aa61236a998f55a18d339efb3d8cf | e2065a17b78dd3cd3dfca6f07e208bc275a93d70 | refs/heads/master | 2020-11-26T22:47:12.815000 | 2020-03-19T02:00:15 | 2020-03-19T02:00:15 | 229,221,623 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.lf2019.lf1021;
public class NPhone extends Phone {
public void call(String name){
super.call("Lili");
System.out.println("打完了");
}
}
| UTF-8 | Java | 176 | java | NPhone.java | Java | [] | null | [] | package org.lf2019.lf1021;
public class NPhone extends Phone {
public void call(String name){
super.call("Lili");
System.out.println("打完了");
}
}
| 176 | 0.629412 | 0.582353 | 8 | 20.25 | 14.523687 | 35 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 8 |
623610220d3d4d3f951d98e55478d6612e1a7764 | 26,448,408,610,947 | e9adf9227baee96486bb61bfc78fca99660a6bfc | /bee-engine/src/main/java/com/dianping/bee/server/mysql/InformationSchemaTableProvider.java | 55b241581467453d542eced92129e19c49e006e1 | [] | no_license | lietou/insight | https://github.com/lietou/insight | b1cacc2902c755982a71ea4659311a75ed4acb86 | 4757005689201327eed6e5dd62740a88e84658f0 | refs/heads/master | 2021-01-22T12:17:01.291000 | 2013-04-20T01:38:29 | 2013-04-20T01:38:29 | 8,964,847 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Project: bee-engine
*
* File Created at 2012-9-3
*
* Copyright 2012 dianping.com.
* All rights reserved.
*
* This software is the confidential and proprietary information of
* Dianping Company. ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with dianping.com.
*/
package com.dianping.bee.server.mysql;
import com.dianping.bee.engine.spi.ColumnMeta;
import com.dianping.bee.engine.spi.IndexMeta;
import com.dianping.bee.engine.spi.TableProvider;
/**
* @author <a href="mailto:yiming.liu@dianping.com">Yiming Liu</a>
*/
public enum InformationSchemaTableProvider implements TableProvider {
CHARACTER_SETS("CHARACTER_SETS"),
COLLATIONS("COLLATIONS"),
COLLATION_CHARACTER_SET_APPLICABILITY("COLLATION_CHARACTER_SET_APPLICABILITY"),
COLUMNS("COLUMNS", ColumnsColumn.values(), ColumnsIndex.values()),
COLUMN_PRIVILEGES("COLUMN_PRIVILEGES"),
ENGINES("ENGINES"),
EVENTS("EVENTS"),
FILES("FILES"),
GLOBAL_STATUS("GLOBAL_STATUS"),
GLOBAL_VARIABLES("GLOBAL_VARIABLES"),
INNODB_CMP("INNODB_CMP"),
INNODB_CMPMEM("INNODB_CMP"),
INNODB_CMPMEM_REST("INNODB_CMP"),
INNODB_LOCKS("INNODB_LOCKS"),
INNODB_LOCK_WAITS("INNODB_LOCK_WAITS"),
INNODB_TRX("INNODB_TRX"),
KEY_COLUMN_USAGE("KEY_COLUMN_USAGE"),
PARAMETERS("PARAMETERS"),
PARTITIONS("PARTITIONS"),
PLUGINS("PLUGINS"),
PROCESSLIST("PROCESSLIST"),
PROFILING("PROFILING"),
REFERENTIAL_CONSTRAINTS("REFERENTIAL_CONSTRAINTS"),
ROUTINES("ROUTINES"),
SCHEMATA("SCHEMATA", SchemataColumn.values(), SchemataIndex.values()),
SCHEMA_PRIVILEGES("SCHEMA_PRIVILEGES"),
SESSION_STATUS("SESSION_STATUS"),
SESSION_VARIABLES("SESSION_VARIABLES"),
STATISTICS("STATISTICS"),
TABLES("TABLES", TablesColumn.values(), TablesIndex.values()),
TABLESPACES("TABLESPACES"),
TABLE_CONSTRAINTS("TABLE_CONSTRAINTS"),
TABLE_PRIVILEGES("TABLE_PRIVILEGES"),
TRIGGERS("TRIGGERS"),
USER_PRIVILEGES("USER_PRIVILEGES"),
VIEWS("VIEWS");
private String m_name;
private ColumnMeta[] m_columns;
private IndexMeta m_defaultIndex;
private IndexMeta[] m_indexes;
private InformationSchemaTableProvider(String name) {
m_name = name;
}
private InformationSchemaTableProvider(String name, ColumnMeta[] columns, IndexMeta[] indexes) {
m_name = name;
m_columns = columns;
m_defaultIndex = indexes.length > 0 ? indexes[0] : null;
m_indexes = indexes;
}
@Override
public ColumnMeta[] getColumns() {
return m_columns;
}
@Override
public IndexMeta getDefaultIndex() {
if (m_defaultIndex == null) {
throw new RuntimeException("No default index defined yet!");
} else {
return m_defaultIndex;
}
}
@Override
public IndexMeta[] getIndexes() {
return m_indexes;
}
@Override
public String getName() {
return m_name;
}
} | UTF-8 | Java | 2,885 | java | InformationSchemaTableProvider.java | Java | [
{
"context": "pi.TableProvider;\n\n/**\n * @author <a href=\"mailto:yiming.liu@dianping.com\">Yiming Liu</a>\n */\npublic enum InformationSchema",
"end": 658,
"score": 0.9998676180839539,
"start": 635,
"tag": "EMAIL",
"value": "yiming.liu@dianping.com"
},
{
"context": " @author <a hr... | null | [] | /**
* Project: bee-engine
*
* File Created at 2012-9-3
*
* Copyright 2012 dianping.com.
* All rights reserved.
*
* This software is the confidential and proprietary information of
* Dianping Company. ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with dianping.com.
*/
package com.dianping.bee.server.mysql;
import com.dianping.bee.engine.spi.ColumnMeta;
import com.dianping.bee.engine.spi.IndexMeta;
import com.dianping.bee.engine.spi.TableProvider;
/**
* @author <a href="mailto:<EMAIL>"><NAME></a>
*/
public enum InformationSchemaTableProvider implements TableProvider {
CHARACTER_SETS("CHARACTER_SETS"),
COLLATIONS("COLLATIONS"),
COLLATION_CHARACTER_SET_APPLICABILITY("COLLATION_CHARACTER_SET_APPLICABILITY"),
COLUMNS("COLUMNS", ColumnsColumn.values(), ColumnsIndex.values()),
COLUMN_PRIVILEGES("COLUMN_PRIVILEGES"),
ENGINES("ENGINES"),
EVENTS("EVENTS"),
FILES("FILES"),
GLOBAL_STATUS("GLOBAL_STATUS"),
GLOBAL_VARIABLES("GLOBAL_VARIABLES"),
INNODB_CMP("INNODB_CMP"),
INNODB_CMPMEM("INNODB_CMP"),
INNODB_CMPMEM_REST("INNODB_CMP"),
INNODB_LOCKS("INNODB_LOCKS"),
INNODB_LOCK_WAITS("INNODB_LOCK_WAITS"),
INNODB_TRX("INNODB_TRX"),
KEY_COLUMN_USAGE("KEY_COLUMN_USAGE"),
PARAMETERS("PARAMETERS"),
PARTITIONS("PARTITIONS"),
PLUGINS("PLUGINS"),
PROCESSLIST("PROCESSLIST"),
PROFILING("PROFILING"),
REFERENTIAL_CONSTRAINTS("REFERENTIAL_CONSTRAINTS"),
ROUTINES("ROUTINES"),
SCHEMATA("SCHEMATA", SchemataColumn.values(), SchemataIndex.values()),
SCHEMA_PRIVILEGES("SCHEMA_PRIVILEGES"),
SESSION_STATUS("SESSION_STATUS"),
SESSION_VARIABLES("SESSION_VARIABLES"),
STATISTICS("STATISTICS"),
TABLES("TABLES", TablesColumn.values(), TablesIndex.values()),
TABLESPACES("TABLESPACES"),
TABLE_CONSTRAINTS("TABLE_CONSTRAINTS"),
TABLE_PRIVILEGES("TABLE_PRIVILEGES"),
TRIGGERS("TRIGGERS"),
USER_PRIVILEGES("USER_PRIVILEGES"),
VIEWS("VIEWS");
private String m_name;
private ColumnMeta[] m_columns;
private IndexMeta m_defaultIndex;
private IndexMeta[] m_indexes;
private InformationSchemaTableProvider(String name) {
m_name = name;
}
private InformationSchemaTableProvider(String name, ColumnMeta[] columns, IndexMeta[] indexes) {
m_name = name;
m_columns = columns;
m_defaultIndex = indexes.length > 0 ? indexes[0] : null;
m_indexes = indexes;
}
@Override
public ColumnMeta[] getColumns() {
return m_columns;
}
@Override
public IndexMeta getDefaultIndex() {
if (m_defaultIndex == null) {
throw new RuntimeException("No default index defined yet!");
} else {
return m_defaultIndex;
}
}
@Override
public IndexMeta[] getIndexes() {
return m_indexes;
}
@Override
public String getName() {
return m_name;
}
} | 2,865 | 0.72513 | 0.720971 | 139 | 19.76259 | 22.050819 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.05036 | false | false | 8 |
db27e233972512c19668f2e1d00545680e9a27a6 | 29,643,864,280,783 | 0347190d4ab3c1a0b74cb931fb84ceada5e6750a | /ROOT/src/com/cubesofttech/model/Approver.java | 14f281de9e04b7ecfa76a264f6de4a2a161f6788 | [] | no_license | ohoh00/cubeproject | https://github.com/ohoh00/cubeproject | 8e2c2f17f0c1b4a4ea29028e4958b70daee223b7 | 71ef9ecccf837376ffe44a68a3f551115d228f26 | refs/heads/main | 2023-05-14T12:18:01.452000 | 2023-05-03T02:28:34 | 2023-05-03T02:28:34 | 366,575,208 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cubesofttech.model;
import java.io.Serializable;
import java.util.*;
import java.math.*;
import javax.persistence.*;
@Entity
@Table(name = "approver")
@NamedQueries({
@NamedQuery(name = "Approver.findAll", query = "SELECT t FROM Approver t")})
public class Approver implements Serializable {
/** Creates a new instance of Approver */
public Approver() {
}
public Approver(
Integer id
, String userId
, String apprId
, String apprName
, Integer row
, Integer apprNo
) {
this.id = id;
this.userId = userId;
this.apprId = apprId;
this.apprName = apprName;
this.row = row;
this.apprNo = apprNo;
}
@Id
@Column(name = "id")
private Integer id;
@Column(name = "user_id")
private String userId;
@Column(name = "appr_id")
private String apprId;
@Column(name = "appr_name")
private String apprName;
@Column(name = "row")
private Integer row;
@Column(name = "appr_no")
private Integer apprNo;
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserId() {
return this.userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getApprId() {
return this.apprId;
}
public void setApprId(String apprId) {
this.apprId = apprId;
}
public String getApprName() {
return this.apprName;
}
public void setApprName(String apprName) {
this.apprName = apprName;
}
public Integer getRow() {
return this.row;
}
public void setRow(Integer row) {
this.row = row;
}
public Integer getApprNo() {
return this.apprNo;
}
public void setApprNo(Integer apprNo) {
this.apprNo = apprNo;
}
public String toString() {
return super.toString() + "id=[" + id + "]\n" + "userId=[" + userId + "]\n" + "apprId=[" + apprId + "]\n" + "apprName=[" + apprName + "]\n" + "row=[" + row + "]\n" + "apprNo=[" + apprNo + "]\n";
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Approver)) {
return false;
}
Approver that = (Approver) obj;
if (!(that.getId() == null ? this.getId() == null
: that.getId().equals(this.getId()))) {
return false;
}
if (!(that.getUserId() == null ? this.getUserId() == null
: that.getUserId().equals(this.getUserId()))) {
return false;
}
if (!(that.getApprId() == null ? this.getApprId() == null
: that.getApprId().equals(this.getApprId()))) {
return false;
}
if (!(that.getApprName() == null ? this.getApprName() == null
: that.getApprName().equals(this.getApprName()))) {
return false;
}
if (!(that.getRow() == null ? this.getRow() == null
: that.getRow().equals(this.getRow()))) {
return false;
}
if (!(that.getApprNo() == null ? this.getApprNo() == null
: that.getApprNo().equals(this.getApprNo()))) {
return false;
}
return true;
}
}
| UTF-8 | Java | 3,539 | java | Approver.java | Java | [] | null | [] | package com.cubesofttech.model;
import java.io.Serializable;
import java.util.*;
import java.math.*;
import javax.persistence.*;
@Entity
@Table(name = "approver")
@NamedQueries({
@NamedQuery(name = "Approver.findAll", query = "SELECT t FROM Approver t")})
public class Approver implements Serializable {
/** Creates a new instance of Approver */
public Approver() {
}
public Approver(
Integer id
, String userId
, String apprId
, String apprName
, Integer row
, Integer apprNo
) {
this.id = id;
this.userId = userId;
this.apprId = apprId;
this.apprName = apprName;
this.row = row;
this.apprNo = apprNo;
}
@Id
@Column(name = "id")
private Integer id;
@Column(name = "user_id")
private String userId;
@Column(name = "appr_id")
private String apprId;
@Column(name = "appr_name")
private String apprName;
@Column(name = "row")
private Integer row;
@Column(name = "appr_no")
private Integer apprNo;
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserId() {
return this.userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getApprId() {
return this.apprId;
}
public void setApprId(String apprId) {
this.apprId = apprId;
}
public String getApprName() {
return this.apprName;
}
public void setApprName(String apprName) {
this.apprName = apprName;
}
public Integer getRow() {
return this.row;
}
public void setRow(Integer row) {
this.row = row;
}
public Integer getApprNo() {
return this.apprNo;
}
public void setApprNo(Integer apprNo) {
this.apprNo = apprNo;
}
public String toString() {
return super.toString() + "id=[" + id + "]\n" + "userId=[" + userId + "]\n" + "apprId=[" + apprId + "]\n" + "apprName=[" + apprName + "]\n" + "row=[" + row + "]\n" + "apprNo=[" + apprNo + "]\n";
}
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Approver)) {
return false;
}
Approver that = (Approver) obj;
if (!(that.getId() == null ? this.getId() == null
: that.getId().equals(this.getId()))) {
return false;
}
if (!(that.getUserId() == null ? this.getUserId() == null
: that.getUserId().equals(this.getUserId()))) {
return false;
}
if (!(that.getApprId() == null ? this.getApprId() == null
: that.getApprId().equals(this.getApprId()))) {
return false;
}
if (!(that.getApprName() == null ? this.getApprName() == null
: that.getApprName().equals(this.getApprName()))) {
return false;
}
if (!(that.getRow() == null ? this.getRow() == null
: that.getRow().equals(this.getRow()))) {
return false;
}
if (!(that.getApprNo() == null ? this.getApprNo() == null
: that.getApprNo().equals(this.getApprNo()))) {
return false;
}
return true;
}
}
| 3,539 | 0.509749 | 0.509749 | 127 | 26.866142 | 24.366093 | 202 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.598425 | false | false | 8 |
f6c9201cd6401a41a4cbb13ce4e55f0f585551b8 | 1,099,511,628,837 | 34f525dd99db86f91225831bd3a7e2170a3cd111 | /src/main/java/com/dobbypos/model/service/HqServiceImpl.java | c71ff163b2c17d518cb77ac9b18d6001051ea539 | [] | no_license | ssosso210/git-web-pos | https://github.com/ssosso210/git-web-pos | 033696352a295ec3b8749decd5e28a93f9e2688d | 8aa6d1f4ed550ba47201c256d32c4b597e49ef58 | refs/heads/master | 2021-01-10T03:25:46.618000 | 2016-02-18T11:22:39 | 2016-02-18T11:22:39 | 49,864,281 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dobbypos.model.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.dobbypos.model.dao.HqDao;
import com.dobbypos.model.dto.Hq;
@Service("hqService")
public class HqServiceImpl implements HqService {
public void init() {
System.out.println("init method is called");
}
public void destroy() {
System.out.println("destroy method is called");
}
@Autowired
@Qualifier("hqDao")
private HqDao hqDao;
@Override
public Hq searchHqByHqId(String hqId) {
return hqDao.selectHqByHqId(hqId);
}
}
| UTF-8 | Java | 679 | java | HqServiceImpl.java | Java | [] | null | [] | package com.dobbypos.model.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.dobbypos.model.dao.HqDao;
import com.dobbypos.model.dto.Hq;
@Service("hqService")
public class HqServiceImpl implements HqService {
public void init() {
System.out.println("init method is called");
}
public void destroy() {
System.out.println("destroy method is called");
}
@Autowired
@Qualifier("hqDao")
private HqDao hqDao;
@Override
public Hq searchHqByHqId(String hqId) {
return hqDao.selectHqByHqId(hqId);
}
}
| 679 | 0.748159 | 0.748159 | 42 | 15.166667 | 19.584879 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.809524 | false | false | 8 |
6e53d70eafc85b84d0a053d8d5cc23f28e3ab564 | 12,232,066,888,192 | 0fb59f3d585456737d1e43c748fd3a8f439c8aa0 | /SpiderTask3/app/src/main/java/com/example/aishwarya/spidertask3/MainActivity.java | a7286435d5e06f44800333f5ef9db5d6cab5dea2 | [] | no_license | MayTune/Spider-Inductions-2016 | https://github.com/MayTune/Spider-Inductions-2016 | c8c84f9d039bd155c484198f3d45ac13caa9e817 | fdd0bc235613e377ced634b6c1ef5117e0f1b104 | refs/heads/master | 2021-01-20T20:53:07.131000 | 2016-07-06T10:07:23 | 2016-07-06T10:07:23 | 60,018,020 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.aishwarya.spidertask3;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
Button sbutton;
private EditText movieText;
private EditText Year;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
movieText = (EditText) findViewById(R.id.movieText);
Year = (EditText) findViewById(R.id.Year);
sbutton = (Button) findViewById(R.id.sbutton);
sbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,MovieList.class);
intent.putExtra("NAME",movieText.getText().toString());
intent.putExtra("YEAR",Year.getText().toString());
startActivity(intent);
}
});
}
}
| UTF-8 | Java | 1,130 | java | MainActivity.java | Java | [
{
"context": "package com.example.aishwarya.spidertask3;\n\nimport android.content.Intent;\nimpo",
"end": 29,
"score": 0.9690283536911011,
"start": 20,
"tag": "USERNAME",
"value": "aishwarya"
}
] | null | [] | package com.example.aishwarya.spidertask3;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
Button sbutton;
private EditText movieText;
private EditText Year;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
movieText = (EditText) findViewById(R.id.movieText);
Year = (EditText) findViewById(R.id.Year);
sbutton = (Button) findViewById(R.id.sbutton);
sbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,MovieList.class);
intent.putExtra("NAME",movieText.getText().toString());
intent.putExtra("YEAR",Year.getText().toString());
startActivity(intent);
}
});
}
}
| 1,130 | 0.668142 | 0.666372 | 36 | 30.305555 | 23.226923 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.638889 | false | false | 8 |
f374a11af71e247769d138ea164aafa2ae1ca702 | 33,225,867,067,982 | 01df68ce108ef20ced22beaa992346b048653145 | /gravitee-apim-rest-api/gravitee-apim-rest-api-service/src/main/java/io/gravitee/rest/api/service/cockpit/command/handler/GoodbyeCommandHandler.java | 8b2416392f5939f49fe33068d6f56e4d41e6b424 | [
"Apache-2.0"
] | permissive | anniyanvr/gravitee-gateway | https://github.com/anniyanvr/gravitee-gateway | 022436afe23c0768da0c65461d7ea5433f9e7d21 | d4c84ecdeddbd568342b23bb2a30ede91e32d230 | refs/heads/master | 2023-04-13T07:32:54.111000 | 2023-03-30T15:34:21 | 2023-03-30T15:52:40 | 83,608,024 | 0 | 0 | Apache-2.0 | true | 2023-03-31T19:30:00 | 2017-03-01T22:26:04 | 2023-01-31T16:48:17 | 2023-03-31T06:22:34 | 149,401 | 0 | 0 | 1 | Java | false | false | /**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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 io.gravitee.rest.api.service.cockpit.command.handler;
import io.gravitee.cockpit.api.command.Command;
import io.gravitee.cockpit.api.command.CommandHandler;
import io.gravitee.cockpit.api.command.CommandStatus;
import io.gravitee.cockpit.api.command.goodbye.GoodbyeCommand;
import io.gravitee.cockpit.api.command.goodbye.GoodbyeReply;
import io.gravitee.rest.api.model.promotion.PromotionEntityStatus;
import io.gravitee.rest.api.model.promotion.PromotionQuery;
import io.gravitee.rest.api.service.InstallationService;
import io.gravitee.rest.api.service.promotion.PromotionService;
import io.reactivex.rxjava3.core.Single;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* @author David BRASSELY (david.brassely at graviteesource.com)
* @author GraviteeSource Team
*/
@Component
public class GoodbyeCommandHandler implements CommandHandler<GoodbyeCommand, GoodbyeReply> {
static final String DELETED_STATUS = "DELETED";
private final Logger logger = LoggerFactory.getLogger(GoodbyeCommandHandler.class);
private final InstallationService installationService;
private final PromotionService promotionService;
public GoodbyeCommandHandler(final InstallationService installationService, PromotionService promotionService) {
this.installationService = installationService;
this.promotionService = promotionService;
}
@Override
public Command.Type handleType() {
return Command.Type.GOODBYE_COMMAND;
}
@Override
public Single<GoodbyeReply> handle(GoodbyeCommand command) {
final Map<String, String> additionalInformation = this.installationService.getOrInitialize().getAdditionalInformation();
additionalInformation.put(InstallationService.COCKPIT_INSTALLATION_STATUS, DELETED_STATUS);
rejectAllPromotionToValidate();
try {
this.installationService.setAdditionalInformation(additionalInformation);
logger.info("Installation status is [{}].", DELETED_STATUS);
return Single.just(new GoodbyeReply(command.getId(), CommandStatus.SUCCEEDED));
} catch (Exception ex) {
logger.info("Error occurred when deleting installation.", ex);
return Single.just(new GoodbyeReply(command.getId(), CommandStatus.ERROR));
}
}
private void rejectAllPromotionToValidate() {
PromotionQuery promotionQuery = new PromotionQuery();
promotionQuery.setStatuses(List.of(PromotionEntityStatus.TO_BE_VALIDATED));
promotionService
.search(promotionQuery, null, null)
.getContent()
.forEach(promotionEntity -> {
promotionEntity.setStatus(PromotionEntityStatus.REJECTED);
promotionService.createOrUpdate(promotionEntity);
});
}
}
| UTF-8 | Java | 3,545 | java | GoodbyeCommandHandler.java | Java | [
{
"context": "ingframework.stereotype.Component;\n\n/**\n * @author David BRASSELY (david.brassely at graviteesource.com)\n * @author",
"end": 1445,
"score": 0.9997614026069641,
"start": 1431,
"tag": "NAME",
"value": "David BRASSELY"
},
{
"context": "eotype.Component;\n\n/**\n * @aut... | null | [] | /**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* 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 io.gravitee.rest.api.service.cockpit.command.handler;
import io.gravitee.cockpit.api.command.Command;
import io.gravitee.cockpit.api.command.CommandHandler;
import io.gravitee.cockpit.api.command.CommandStatus;
import io.gravitee.cockpit.api.command.goodbye.GoodbyeCommand;
import io.gravitee.cockpit.api.command.goodbye.GoodbyeReply;
import io.gravitee.rest.api.model.promotion.PromotionEntityStatus;
import io.gravitee.rest.api.model.promotion.PromotionQuery;
import io.gravitee.rest.api.service.InstallationService;
import io.gravitee.rest.api.service.promotion.PromotionService;
import io.reactivex.rxjava3.core.Single;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* @author <NAME> (david.brassely at graviteesource.com)
* @author GraviteeSource Team
*/
@Component
public class GoodbyeCommandHandler implements CommandHandler<GoodbyeCommand, GoodbyeReply> {
static final String DELETED_STATUS = "DELETED";
private final Logger logger = LoggerFactory.getLogger(GoodbyeCommandHandler.class);
private final InstallationService installationService;
private final PromotionService promotionService;
public GoodbyeCommandHandler(final InstallationService installationService, PromotionService promotionService) {
this.installationService = installationService;
this.promotionService = promotionService;
}
@Override
public Command.Type handleType() {
return Command.Type.GOODBYE_COMMAND;
}
@Override
public Single<GoodbyeReply> handle(GoodbyeCommand command) {
final Map<String, String> additionalInformation = this.installationService.getOrInitialize().getAdditionalInformation();
additionalInformation.put(InstallationService.COCKPIT_INSTALLATION_STATUS, DELETED_STATUS);
rejectAllPromotionToValidate();
try {
this.installationService.setAdditionalInformation(additionalInformation);
logger.info("Installation status is [{}].", DELETED_STATUS);
return Single.just(new GoodbyeReply(command.getId(), CommandStatus.SUCCEEDED));
} catch (Exception ex) {
logger.info("Error occurred when deleting installation.", ex);
return Single.just(new GoodbyeReply(command.getId(), CommandStatus.ERROR));
}
}
private void rejectAllPromotionToValidate() {
PromotionQuery promotionQuery = new PromotionQuery();
promotionQuery.setStatuses(List.of(PromotionEntityStatus.TO_BE_VALIDATED));
promotionService
.search(promotionQuery, null, null)
.getContent()
.forEach(promotionEntity -> {
promotionEntity.setStatus(PromotionEntityStatus.REJECTED);
promotionService.createOrUpdate(promotionEntity);
});
}
}
| 3,537 | 0.743582 | 0.74048 | 86 | 40.220932 | 31.774057 | 128 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.593023 | false | false | 8 |
d493c610ae4383e1e672f4e95f0b2051b0cfcc5b | 23,304,492,612,988 | 0ef954c4761c04d743ca88c0336d2a4556d22735 | /app/src/main/java/xyz/rnovoselov/projects/gameofthrones/utils/NetworkStatusChecker.java | 5ede1e92482f6c587ff3907637325f9affcf8da2 | [] | no_license | RNOVOSELOV/GameOfThrones | https://github.com/RNOVOSELOV/GameOfThrones | 67399b275c9681bdb131815efd91c863be6fe29a | 11c1c810f635e0fff88fed2f35eac3011de3e6a0 | refs/heads/master | 2021-01-11T01:17:15.432000 | 2017-04-23T06:26:32 | 2017-04-23T06:26:32 | 70,730,182 | 2 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package xyz.rnovoselov.projects.gameofthrones.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
/**
* Created by novoselov on 13.10.2016.
*/
public class NetworkStatusChecker {
public static boolean isNetworkAvailable (Context context) {
ConnectivityManager cm = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
NetworkInfo network = cm.getActiveNetworkInfo();
return (network != null) && network.isConnectedOrConnecting();
}
}
| UTF-8 | Java | 585 | java | NetworkStatusChecker.java | Java | [
{
"context": "package xyz.rnovoselov.projects.gameofthrones.utils;\n\nimport android.con",
"end": 22,
"score": 0.9904534220695496,
"start": 12,
"tag": "USERNAME",
"value": "rnovoselov"
},
{
"context": "import android.net.NetworkInfo;\n\n/**\n * Created by novoselov on 13.10.2016.\n *... | null | [] | package xyz.rnovoselov.projects.gameofthrones.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
/**
* Created by novoselov on 13.10.2016.
*/
public class NetworkStatusChecker {
public static boolean isNetworkAvailable (Context context) {
ConnectivityManager cm = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
NetworkInfo network = cm.getActiveNetworkInfo();
return (network != null) && network.isConnectedOrConnecting();
}
}
| 585 | 0.758974 | 0.745299 | 18 | 31.5 | 30.188759 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.444444 | false | false | 8 |
6c58a76f0902df0668383a9ba0d66316ec1a2d01 | 20,366,734,929,085 | af01641b30413e6b8e1c0bfb9230e7c8a23a88f7 | /src/main/java/org/xmltv/service/CntvEpgService.java | 33ad99d0bb922de849c0342c225d4cc45c848218 | [
"Apache-2.0"
] | permissive | zcy0521/cntvepg | https://github.com/zcy0521/cntvepg | 160f5bbf1041042b51ab8908d3f384bd0f68fe33 | 7b39176ad98ff39553a3a804182748cbfbdd9f50 | refs/heads/master | 2021-06-20T00:18:46.477000 | 2019-11-03T16:48:01 | 2019-11-03T16:48:01 | 218,795,098 | 0 | 0 | Apache-2.0 | false | 2021-06-04T02:17:37 | 2019-10-31T15:13:57 | 2019-11-03T16:48:07 | 2021-06-04T02:17:36 | 44 | 0 | 0 | 2 | Java | false | false | package org.xmltv.service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.FileCopyUtils;
import org.xmltv.pojo.CntvEpgChannel;
import org.xmltv.pojo.CntvEpgChannelProgram;
import org.xmltv.pojo.*;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.springframework.util.ResourceUtils.CLASSPATH_URL_PREFIX;
/**
* CNTV EPG信息工具类
*/
@Slf4j
@Service
public class CntvEpgService {
private static final String CNTV_M3U_FILE_NAME = "public/cntv.m3u";
private static final String CNTV_EPG_API_SCHEME = "http";
private static final String CNTV_EPG_API_HOST = "api.cntv.cn";
private static final String CNTV_EPG_API_PATH = "/epg/epginfo";
private static final Integer SEARCH_DATE_DEFAULT_OFFSET = 8;
@Autowired
private ResourceLoader resourceLoader;
/**
* 获取代查询的频道名称列表
*/
List<String> getCntvChannelList() {
// 解析 cntv.m3u 文件
String text = "";
try {
Resource cntvM3uResource = resourceLoader.getResource(CLASSPATH_URL_PREFIX + CNTV_M3U_FILE_NAME);
InputStream inputStream = cntvM3uResource.getInputStream();
Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
text = FileCopyUtils.copyToString(reader);
} catch (IOException e) {
e.printStackTrace();
}
// 正则匹配
Pattern pattern = Pattern.compile("tvg-id=\"(.*?)\"");
Matcher matcher = pattern.matcher(text);
List<String> channelList = Lists.newArrayList();
while (matcher.find()) {
// matcher.group(0) tvg-id="cctv"
// matcher.group(1) cctv
String channelName = matcher.group(1);
if (!channelList.contains(channelName) && StringUtils.isNotBlank(channelName)) {
channelList.add(channelName);
}
}
return channelList;
}
/**
* 查询 CNTV EPG 接口
*/
private String searchEpgInfoFromApi(String channels, String date) {
// 查询频道
if (StringUtils.isEmpty(channels)) {
return "";
}
// 查询日期
if (StringUtils.isEmpty(date)) {
date = new DateTime(date).toString("yyyyMMdd");
}
// 请求接口
CloseableHttpClient httpclient = HttpClients.createDefault();
String responseBody = "";
try {
// uri
URI uri = new URIBuilder().setScheme(CNTV_EPG_API_SCHEME).setHost(CNTV_EPG_API_HOST).setPath(CNTV_EPG_API_PATH)
.setParameter("c", channels)
.setParameter("d", date)
.build();
// httpget
HttpGet httpget = new HttpGet(uri);
log.debug("Executing request " + httpget.getRequestLine());
// Create a custom response handler
ResponseHandler<String> responseHandler;
responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
};
responseBody = httpclient.execute(httpget, responseHandler);
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return responseBody;
}
/**
* 获取 xmltv
* @param channelIdList 查询频道集合
* @param offset 查询日期偏移量
* @return xml
*/
CntvXmltv getCntvXmltv(List<String> channelIdList, Integer offset) {
// 查询频道
String channelValue = Joiner.on(",").skipNulls().join(channelIdList);
// 查询日期
offset = null == offset ? SEARCH_DATE_DEFAULT_OFFSET : offset;
// 请求 cntv 接口
ObjectMapper mapper = new ObjectMapper();
CntvXmltv xmltv = new CntvXmltv();
List<CntvXmltvChannel> channel = Lists.newArrayList();
List<CntvXmltvProgramme> programme = Lists.newArrayList();
for (int i = 0; i < offset; i++) {
DateTime date = new DateTime().plusDays(i);
String dateValue = date.toString("yyyyMMdd");
String egpInfo = searchEpgInfoFromApi(channelValue, dateValue);
if (StringUtils.isEmpty(egpInfo)) {
continue;
}
// 解析json
try {
JsonNode epgNode = mapper.readTree(egpInfo);
for (String channelId : channelIdList) {
JsonNode channelNode = epgNode.get(channelId);
CntvEpgChannel epgChannel = mapper.treeToValue(channelNode, CntvEpgChannel.class);
// channel tag
if (i == 0) {
CntvXmltvChannel xmltvChannel = new CntvXmltvChannel();
xmltvChannel.setId(channelId);
CntvXmltvChannelDisplayName displayName = new CntvXmltvChannelDisplayName();
displayName.setLang("zh");
displayName.setValue(epgChannel.getChannelName());
xmltvChannel.setDisplayName(displayName);
channel.add(xmltvChannel);
}
// programme tag
List<CntvEpgChannelProgram> epgChannelProgramList = epgChannel.getProgram();
if (CollectionUtils.isEmpty(epgChannelProgramList)) {
continue;
}
for (CntvEpgChannelProgram epgChannelProgram : epgChannelProgramList) {
CntvXmltvProgramme xmltvProgramme = new CntvXmltvProgramme();
xmltvProgramme.setStart(epgChannelProgram.getSt());
xmltvProgramme.setStop(epgChannelProgram.getEt());
xmltvProgramme.setChannel(channelId);
CntvXmltvProgrammeTitle title = new CntvXmltvProgrammeTitle();
title.setLang("zh");
xmltvProgramme.setTitle(title);
title.setValue(epgChannelProgram.getT());
CntvXmltvProgrammeDesc desc = new CntvXmltvProgrammeDesc();
title.setLang("zh");
xmltvProgramme.setDesc(desc);
programme.add(xmltvProgramme);
}
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
xmltv.setChannel(channel);
xmltv.setProgramme(programme);
return xmltv;
}
public CntvXmltv getCntvXmltv() {
return getCntvXmltv(getCntvChannelList(), SEARCH_DATE_DEFAULT_OFFSET);
}
}
| UTF-8 | Java | 8,290 | java | CntvEpgService.java | Java | [] | null | [] | package org.xmltv.service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.FileCopyUtils;
import org.xmltv.pojo.CntvEpgChannel;
import org.xmltv.pojo.CntvEpgChannelProgram;
import org.xmltv.pojo.*;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.springframework.util.ResourceUtils.CLASSPATH_URL_PREFIX;
/**
* CNTV EPG信息工具类
*/
@Slf4j
@Service
public class CntvEpgService {
private static final String CNTV_M3U_FILE_NAME = "public/cntv.m3u";
private static final String CNTV_EPG_API_SCHEME = "http";
private static final String CNTV_EPG_API_HOST = "api.cntv.cn";
private static final String CNTV_EPG_API_PATH = "/epg/epginfo";
private static final Integer SEARCH_DATE_DEFAULT_OFFSET = 8;
@Autowired
private ResourceLoader resourceLoader;
/**
* 获取代查询的频道名称列表
*/
List<String> getCntvChannelList() {
// 解析 cntv.m3u 文件
String text = "";
try {
Resource cntvM3uResource = resourceLoader.getResource(CLASSPATH_URL_PREFIX + CNTV_M3U_FILE_NAME);
InputStream inputStream = cntvM3uResource.getInputStream();
Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
text = FileCopyUtils.copyToString(reader);
} catch (IOException e) {
e.printStackTrace();
}
// 正则匹配
Pattern pattern = Pattern.compile("tvg-id=\"(.*?)\"");
Matcher matcher = pattern.matcher(text);
List<String> channelList = Lists.newArrayList();
while (matcher.find()) {
// matcher.group(0) tvg-id="cctv"
// matcher.group(1) cctv
String channelName = matcher.group(1);
if (!channelList.contains(channelName) && StringUtils.isNotBlank(channelName)) {
channelList.add(channelName);
}
}
return channelList;
}
/**
* 查询 CNTV EPG 接口
*/
private String searchEpgInfoFromApi(String channels, String date) {
// 查询频道
if (StringUtils.isEmpty(channels)) {
return "";
}
// 查询日期
if (StringUtils.isEmpty(date)) {
date = new DateTime(date).toString("yyyyMMdd");
}
// 请求接口
CloseableHttpClient httpclient = HttpClients.createDefault();
String responseBody = "";
try {
// uri
URI uri = new URIBuilder().setScheme(CNTV_EPG_API_SCHEME).setHost(CNTV_EPG_API_HOST).setPath(CNTV_EPG_API_PATH)
.setParameter("c", channels)
.setParameter("d", date)
.build();
// httpget
HttpGet httpget = new HttpGet(uri);
log.debug("Executing request " + httpget.getRequestLine());
// Create a custom response handler
ResponseHandler<String> responseHandler;
responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
};
responseBody = httpclient.execute(httpget, responseHandler);
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return responseBody;
}
/**
* 获取 xmltv
* @param channelIdList 查询频道集合
* @param offset 查询日期偏移量
* @return xml
*/
CntvXmltv getCntvXmltv(List<String> channelIdList, Integer offset) {
// 查询频道
String channelValue = Joiner.on(",").skipNulls().join(channelIdList);
// 查询日期
offset = null == offset ? SEARCH_DATE_DEFAULT_OFFSET : offset;
// 请求 cntv 接口
ObjectMapper mapper = new ObjectMapper();
CntvXmltv xmltv = new CntvXmltv();
List<CntvXmltvChannel> channel = Lists.newArrayList();
List<CntvXmltvProgramme> programme = Lists.newArrayList();
for (int i = 0; i < offset; i++) {
DateTime date = new DateTime().plusDays(i);
String dateValue = date.toString("yyyyMMdd");
String egpInfo = searchEpgInfoFromApi(channelValue, dateValue);
if (StringUtils.isEmpty(egpInfo)) {
continue;
}
// 解析json
try {
JsonNode epgNode = mapper.readTree(egpInfo);
for (String channelId : channelIdList) {
JsonNode channelNode = epgNode.get(channelId);
CntvEpgChannel epgChannel = mapper.treeToValue(channelNode, CntvEpgChannel.class);
// channel tag
if (i == 0) {
CntvXmltvChannel xmltvChannel = new CntvXmltvChannel();
xmltvChannel.setId(channelId);
CntvXmltvChannelDisplayName displayName = new CntvXmltvChannelDisplayName();
displayName.setLang("zh");
displayName.setValue(epgChannel.getChannelName());
xmltvChannel.setDisplayName(displayName);
channel.add(xmltvChannel);
}
// programme tag
List<CntvEpgChannelProgram> epgChannelProgramList = epgChannel.getProgram();
if (CollectionUtils.isEmpty(epgChannelProgramList)) {
continue;
}
for (CntvEpgChannelProgram epgChannelProgram : epgChannelProgramList) {
CntvXmltvProgramme xmltvProgramme = new CntvXmltvProgramme();
xmltvProgramme.setStart(epgChannelProgram.getSt());
xmltvProgramme.setStop(epgChannelProgram.getEt());
xmltvProgramme.setChannel(channelId);
CntvXmltvProgrammeTitle title = new CntvXmltvProgrammeTitle();
title.setLang("zh");
xmltvProgramme.setTitle(title);
title.setValue(epgChannelProgram.getT());
CntvXmltvProgrammeDesc desc = new CntvXmltvProgrammeDesc();
title.setLang("zh");
xmltvProgramme.setDesc(desc);
programme.add(xmltvProgramme);
}
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
xmltv.setChannel(channel);
xmltv.setProgramme(programme);
return xmltv;
}
public CntvXmltv getCntvXmltv() {
return getCntvXmltv(getCntvChannelList(), SEARCH_DATE_DEFAULT_OFFSET);
}
}
| 8,290 | 0.596442 | 0.59362 | 221 | 35.877827 | 26.879124 | 123 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.552036 | false | false | 8 |
4abb2dfc415cd289323df769a7e4abce91d2d40f | 11,269,994,186,460 | e4d0ed74846252d9e86c55d73957ea2db5577e2d | /src/com/lut/service/ScoreService.java | a1d669dc99ca07231119b5e41942e425ba355b3a | [] | no_license | Innux/score3 | https://github.com/Innux/score3 | 9c263cf2c8b76bdfc85f74fd8160963f193a2650 | f97eb0b3ae7d60a2afc0c244e341e8f79734eef7 | refs/heads/master | 2020-03-10T22:30:22.759000 | 2018-05-24T12:14:54 | 2018-05-24T12:14:54 | 129,620,553 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.lut.service;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.transaction.annotation.Transactional;
import com.lut.dao.CourseDao;
import com.lut.dao.ScoreDao;
import com.lut.dao.StudentDao;
import com.lut.utils.ExcelUtils;
import com.lut.utils.PageBean;
import com.lut.vo.Clazz;
import com.lut.vo.Major;
import com.lut.vo.Student;
import com.lut.vo.scoreNcourse.Course;
import com.lut.vo.scoreNcourse.Score;
@Transactional
public class ScoreService {
private ScoreDao scoreDao;
public void setScoreDao(ScoreDao scoreDao) {
this.scoreDao = scoreDao;
}
private StudentDao studentDao;
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
private CourseDao courseDao;
public void setCourseDao(CourseDao courseDao) {
this.courseDao = courseDao;
}
public PageBean<Score> findByPage(Integer page) {
PageBean<Score> pageBean = new PageBean<Score>();
// 设置当前页数:
pageBean.setPage(page);
// 设置每页显示记录数:
int limit = 10;
pageBean.setLimit(limit);
// 设置总记录数:
int totalCount = 0;
totalCount = scoreDao.findCount();
pageBean.setTotalCount(totalCount);
// 设置总页数:
int totalPage = 0;
if (totalCount % limit == 0) {
totalPage = totalCount / limit;
} else {
totalPage = totalCount / limit + 1;
}
pageBean.setTotalPage(totalPage);
// 每页显示的数据集合:
// 从哪开始:
int begin = (page - 1) * limit;
List<Score> list = scoreDao.findByPage(begin, limit);
pageBean.setList(list);
return pageBean;
}
public Score findByScoreId(Integer s_id) {
return scoreDao.findByScoreId(s_id);
}
public void delete(Score score) {
scoreDao.delete(score);
}
public PageBean<Score> findByPage(Score searchModel, Integer page) {
PageBean<Score> pageBean = new PageBean<Score>();
// 设置当前页数:
pageBean.setPage(page);
// 设置每页显示记录数:
int limit = 10;
pageBean.setLimit(limit);
int begin = (page - 1) * limit;
int totalCount = 0;
Map<String, List<?>> map = scoreDao.findByPage(searchModel, begin, limit);
List<Long> countList = (List<Long>) map.get("countList");
totalCount = countList.get(0).intValue();
// totalCount = scoreDao.findCount();
pageBean.setTotalCount(totalCount);
// 设置总页数:
int totalPage = 0;
if (totalCount % limit == 0) {
totalPage = totalCount / limit;
} else {
totalPage = totalCount / limit + 1;
}
pageBean.setTotalPage(totalPage);
List<Score> scoreList = (List<Score>) map.get("scoreList");
pageBean.setList(scoreList);
return pageBean;
}
public PageBean<Score> stuFindByPage(Integer stuId,Score searchModel, Integer page) {
PageBean<Score> pageBean = new PageBean<Score>();
// 设置当前页数:
pageBean.setPage(page);
// 设置每页显示记录数:
int limit = 10;
pageBean.setLimit(limit);
int begin = (page - 1) * limit;
int totalCount = 0;
Map<String, List<?>> map = scoreDao.stuFindByPage(stuId,searchModel, begin, limit);
List<Long> countList = (List<Long>) map.get("countList");
totalCount = countList.get(0).intValue();
// totalCount = scoreDao.findCount();
pageBean.setTotalCount(totalCount);
// 设置总页数:
int totalPage = 0;
if (totalCount % limit == 0) {
totalPage = totalCount / limit;
} else {
totalPage = totalCount / limit + 1;
}
pageBean.setTotalPage(totalPage);
List<Score> scoreList = (List<Score>) map.get("scoreList");
pageBean.setList(scoreList);
return pageBean;
}
public List<Object[]> findByStuId(int id) {
List<Object[]> list = scoreDao.findByStuId(id);
return list;
}
public List<Score> findAll() {
// TODO Auto-generated method stub
return scoreDao.findAll();
}
public void exportExcel(List<Score> scoreList, ServletOutputStream outputStream) {
ExcelUtils.exportScoreExcel(scoreList, outputStream);
}
public void importExcel(File scoreExcel, String scoreExcelFileName) {
try {
FileInputStream fileInputStream = new FileInputStream(scoreExcel);
boolean is03Excel = scoreExcelFileName.matches("^.+\\.(?i)(xls)$");
Workbook workbook = is03Excel ? new HSSFWorkbook(fileInputStream) : new XSSFWorkbook(fileInputStream);
Sheet sheet = workbook.getSheetAt(0);
if (sheet.getPhysicalNumberOfRows() > 2) {
Score score = null;
Student student = null;
Course course = null;
for (int k = 2; k < sheet.getPhysicalNumberOfRows(); k++) {
Row row = sheet.getRow(k);
score = new Score();
// 学年
Cell cell0 = row.getCell(0);
score.setS_year(cell0.getStringCellValue());
// 学期
Cell cell1 = row.getCell(1);
score.setS_half((cell1.getStringCellValue().equals("上学期") ? 1 : 2));
// 以下为学生信息
// 学生id
Cell cell2 = row.getCell(2);
int id = (int) cell2.getNumericCellValue();
// 姓名
student = studentDao.findByStuId(id);
// 设置score的student
score.setStudent(student);
// 科目
Cell cell6 = row.getCell(6);
String name = cell6.getStringCellValue().trim();
course = courseDao.findByName(name);
// 设置score的course
score.setCourse(course);
// 成绩
Cell cell7 = row.getCell(7);
int sco = (int) cell7.getNumericCellValue();
score.setS_score(sco);
// 5、保存
scoreDao.save(score);
}
workbook.close();
fileInputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| UTF-8 | Java | 5,910 | java | ScoreService.java | Java | [] | null | [] | package com.lut.service;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.transaction.annotation.Transactional;
import com.lut.dao.CourseDao;
import com.lut.dao.ScoreDao;
import com.lut.dao.StudentDao;
import com.lut.utils.ExcelUtils;
import com.lut.utils.PageBean;
import com.lut.vo.Clazz;
import com.lut.vo.Major;
import com.lut.vo.Student;
import com.lut.vo.scoreNcourse.Course;
import com.lut.vo.scoreNcourse.Score;
@Transactional
public class ScoreService {
private ScoreDao scoreDao;
public void setScoreDao(ScoreDao scoreDao) {
this.scoreDao = scoreDao;
}
private StudentDao studentDao;
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
private CourseDao courseDao;
public void setCourseDao(CourseDao courseDao) {
this.courseDao = courseDao;
}
public PageBean<Score> findByPage(Integer page) {
PageBean<Score> pageBean = new PageBean<Score>();
// 设置当前页数:
pageBean.setPage(page);
// 设置每页显示记录数:
int limit = 10;
pageBean.setLimit(limit);
// 设置总记录数:
int totalCount = 0;
totalCount = scoreDao.findCount();
pageBean.setTotalCount(totalCount);
// 设置总页数:
int totalPage = 0;
if (totalCount % limit == 0) {
totalPage = totalCount / limit;
} else {
totalPage = totalCount / limit + 1;
}
pageBean.setTotalPage(totalPage);
// 每页显示的数据集合:
// 从哪开始:
int begin = (page - 1) * limit;
List<Score> list = scoreDao.findByPage(begin, limit);
pageBean.setList(list);
return pageBean;
}
public Score findByScoreId(Integer s_id) {
return scoreDao.findByScoreId(s_id);
}
public void delete(Score score) {
scoreDao.delete(score);
}
public PageBean<Score> findByPage(Score searchModel, Integer page) {
PageBean<Score> pageBean = new PageBean<Score>();
// 设置当前页数:
pageBean.setPage(page);
// 设置每页显示记录数:
int limit = 10;
pageBean.setLimit(limit);
int begin = (page - 1) * limit;
int totalCount = 0;
Map<String, List<?>> map = scoreDao.findByPage(searchModel, begin, limit);
List<Long> countList = (List<Long>) map.get("countList");
totalCount = countList.get(0).intValue();
// totalCount = scoreDao.findCount();
pageBean.setTotalCount(totalCount);
// 设置总页数:
int totalPage = 0;
if (totalCount % limit == 0) {
totalPage = totalCount / limit;
} else {
totalPage = totalCount / limit + 1;
}
pageBean.setTotalPage(totalPage);
List<Score> scoreList = (List<Score>) map.get("scoreList");
pageBean.setList(scoreList);
return pageBean;
}
public PageBean<Score> stuFindByPage(Integer stuId,Score searchModel, Integer page) {
PageBean<Score> pageBean = new PageBean<Score>();
// 设置当前页数:
pageBean.setPage(page);
// 设置每页显示记录数:
int limit = 10;
pageBean.setLimit(limit);
int begin = (page - 1) * limit;
int totalCount = 0;
Map<String, List<?>> map = scoreDao.stuFindByPage(stuId,searchModel, begin, limit);
List<Long> countList = (List<Long>) map.get("countList");
totalCount = countList.get(0).intValue();
// totalCount = scoreDao.findCount();
pageBean.setTotalCount(totalCount);
// 设置总页数:
int totalPage = 0;
if (totalCount % limit == 0) {
totalPage = totalCount / limit;
} else {
totalPage = totalCount / limit + 1;
}
pageBean.setTotalPage(totalPage);
List<Score> scoreList = (List<Score>) map.get("scoreList");
pageBean.setList(scoreList);
return pageBean;
}
public List<Object[]> findByStuId(int id) {
List<Object[]> list = scoreDao.findByStuId(id);
return list;
}
public List<Score> findAll() {
// TODO Auto-generated method stub
return scoreDao.findAll();
}
public void exportExcel(List<Score> scoreList, ServletOutputStream outputStream) {
ExcelUtils.exportScoreExcel(scoreList, outputStream);
}
public void importExcel(File scoreExcel, String scoreExcelFileName) {
try {
FileInputStream fileInputStream = new FileInputStream(scoreExcel);
boolean is03Excel = scoreExcelFileName.matches("^.+\\.(?i)(xls)$");
Workbook workbook = is03Excel ? new HSSFWorkbook(fileInputStream) : new XSSFWorkbook(fileInputStream);
Sheet sheet = workbook.getSheetAt(0);
if (sheet.getPhysicalNumberOfRows() > 2) {
Score score = null;
Student student = null;
Course course = null;
for (int k = 2; k < sheet.getPhysicalNumberOfRows(); k++) {
Row row = sheet.getRow(k);
score = new Score();
// 学年
Cell cell0 = row.getCell(0);
score.setS_year(cell0.getStringCellValue());
// 学期
Cell cell1 = row.getCell(1);
score.setS_half((cell1.getStringCellValue().equals("上学期") ? 1 : 2));
// 以下为学生信息
// 学生id
Cell cell2 = row.getCell(2);
int id = (int) cell2.getNumericCellValue();
// 姓名
student = studentDao.findByStuId(id);
// 设置score的student
score.setStudent(student);
// 科目
Cell cell6 = row.getCell(6);
String name = cell6.getStringCellValue().trim();
course = courseDao.findByName(name);
// 设置score的course
score.setCourse(course);
// 成绩
Cell cell7 = row.getCell(7);
int sco = (int) cell7.getNumericCellValue();
score.setS_score(sco);
// 5、保存
scoreDao.save(score);
}
workbook.close();
fileInputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 5,910 | 0.686292 | 0.677856 | 211 | 25.966825 | 20.758915 | 107 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.402844 | false | false | 8 |
3390537a0e7ccfa98ddbe4226f67a1824a559e3d | 28,321,014,356,401 | 4cb3f01828885127b2898f728d7dedc85b92c2bd | /WEB-INF/src/kca/customizing/ezpm000006/MailAuth.java | 0c2fdf76bc7c6e7d522a53fb7d63f93733a54009 | [] | no_license | kwonssy02/micepro | https://github.com/kwonssy02/micepro | 3e9012ae59430a84cca5ba362a722da47b8b8870 | cfdedc09ac92806007b0e7e6f273d179eb0f6f63 | refs/heads/master | 2016-08-10T01:41:07.668000 | 2013-03-02T15:56:57 | 2013-03-02T15:56:57 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package kca.customizing.ezpm000006;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class MailAuth extends Authenticator {
private PasswordAuthentication pa;
public MailAuth(String id, String pwd){
// 로그인 시 사용할 ID, 패스 워드
pa = new PasswordAuthentication(id, pwd);
}
// 아래의 메소드는 시스템 측에서 사용하는 메소드이며
// 패스 워드 인증이 필요한 경우 호출 됩니다.
public PasswordAuthentication getPasswordAuthentication() {
return pa;
}
}
| UTF-8 | Java | 622 | java | MailAuth.java | Java | [] | null | [] | package kca.customizing.ezpm000006;
import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
public class MailAuth extends Authenticator {
private PasswordAuthentication pa;
public MailAuth(String id, String pwd){
// 로그인 시 사용할 ID, 패스 워드
pa = new PasswordAuthentication(id, pwd);
}
// 아래의 메소드는 시스템 측에서 사용하는 메소드이며
// 패스 워드 인증이 필요한 경우 호출 됩니다.
public PasswordAuthentication getPasswordAuthentication() {
return pa;
}
}
| 622 | 0.655172 | 0.643678 | 19 | 25.473684 | 20.134726 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.473684 | false | false | 8 |
9c7f4d0d4022d85f0bb36beae22fd0068e151314 | 28,321,014,358,228 | d7647f1cbfe00ff5cbaa2cbc1774db5ca2c60178 | /guithub_web/src/main/java/com/guithub/dao/board/general/PostDAOImpl.java | c49d70eddea35f7128192953f0dcd5b79141e392 | [] | no_license | jsorry0130/guithub | https://github.com/jsorry0130/guithub | da2e6f214e61ac945022cb00a6c52689a45fb181 | c57672858e560e0d6a66fdb101733c1f31ad654d | refs/heads/master | 2023-05-05T20:25:30.975000 | 2021-05-29T08:53:44 | 2021-05-29T08:53:44 | 359,703,063 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.guithub.dao.board.general;
import java.util.HashMap;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.guithub.domain.board.general.FileVO;
import com.guithub.domain.board.general.PostVO;
import com.guithub.domain.board.general.PostVO_view;
import com.guithub.domain.board.general.ReplyVO;
@Repository
public class PostDAOImpl implements PostDAO {
@Autowired
private SqlSession sql;
private static String namespace = "com.guithub.mappers.board.general";
//게시물 목록(페이징 + 서치)
@Override
public List<PostVO> getList(int page, String field, String keyword) throws Exception {
//한 페이지당 글을 15개씩 나타내기 위한 카운트
int startRowNum = 1+(page-1)*15;
int endRowNum = page*15;
//매퍼에 전달하기 위해 해쉬데이터 생성
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("startRowNum", startRowNum);
data.put("endRowNum", endRowNum);
data.put("field", field);
data.put("keyword", keyword);
return sql.selectList(namespace + ".getList", data);
}
//게시물 목록(페이징+서치+댓글 카운트)
@Override
public List<PostVO_view> getList_view(int page, String field, String keyword) throws Exception {
//한 페이지당 글을 15개씩 나타내기 위한 카운트
int startRowNum = 1+(page-1)*15;
int endRowNum = page*15;
//매퍼에 전달하기 위해 해쉬데이터 생성
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("startRowNum", startRowNum);
data.put("endRowNum", endRowNum);
data.put("field", field);
data.put("keyword", keyword);
return sql.selectList(namespace+".getList_view", data);
}
//게시물 개수 카운트
@Override
public int getCount(String field, String keyword) throws Exception {
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("field", field);
data.put("keyword", keyword);
return sql.selectOne(namespace + ".getCount", data);
}
//게시물 상세보기
@Override
public PostVO getDetail(int id) {
return sql.selectOne(namespace+".getDetail", id);
}
//게시물 등록
@Override
public void regPost(PostVO vo) throws Exception {
System.out.println(sql.insert(namespace + ".regPost", vo));
}
//게시물 삭제
@Override
public int delPost(int id, String password) throws Exception {
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("id", id);
data.put("password", password);
return sql.delete(namespace+".delPost", data);
}
//게시물 조회수 갱신
@Override
public void updateHit(int id) throws Exception {
sql.update(namespace+".updateHit", id);
}
//게시물 패스워드 검증
@Override
public boolean checkPwd(int id, String password) throws Exception {
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("id", id);
data.put("password", password);
boolean bool = sql.selectOne(namespace+".checkPwd", data);
System.out.println("불린값 확인" + bool);
return bool;
}
//게시물 수정
@Override
public void editPost(PostVO vo) throws Exception {
sql.update(namespace+".editPost", vo);
}
//파일 정보 삽입
@Override
public void regFile(FileVO vo) throws Exception {
sql.insert(namespace+".regFile", vo);
}
//파일 정보 보기
@Override
public List<FileVO> getFile(int id) {
return sql.selectList(namespace+".getFile", id);
}
//파일 삭제
@Override
public void delFile(int id) {
sql.delete(namespace+".delFile", id);
}
}
| UHC | Java | 3,875 | java | PostDAOImpl.java | Java | [
{
"context": "\n\t\t\r\n\t\tdata.put(\"id\", id);\r\n\t\tdata.put(\"password\", password);\r\n\t\t\t\r\n\t\treturn sql.delete(namespace+\".delPost\",",
"end": 2510,
"score": 0.9499636888504028,
"start": 2502,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "();\r\n\t\tdata.put... | null | [] | package com.guithub.dao.board.general;
import java.util.HashMap;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.guithub.domain.board.general.FileVO;
import com.guithub.domain.board.general.PostVO;
import com.guithub.domain.board.general.PostVO_view;
import com.guithub.domain.board.general.ReplyVO;
@Repository
public class PostDAOImpl implements PostDAO {
@Autowired
private SqlSession sql;
private static String namespace = "com.guithub.mappers.board.general";
//게시물 목록(페이징 + 서치)
@Override
public List<PostVO> getList(int page, String field, String keyword) throws Exception {
//한 페이지당 글을 15개씩 나타내기 위한 카운트
int startRowNum = 1+(page-1)*15;
int endRowNum = page*15;
//매퍼에 전달하기 위해 해쉬데이터 생성
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("startRowNum", startRowNum);
data.put("endRowNum", endRowNum);
data.put("field", field);
data.put("keyword", keyword);
return sql.selectList(namespace + ".getList", data);
}
//게시물 목록(페이징+서치+댓글 카운트)
@Override
public List<PostVO_view> getList_view(int page, String field, String keyword) throws Exception {
//한 페이지당 글을 15개씩 나타내기 위한 카운트
int startRowNum = 1+(page-1)*15;
int endRowNum = page*15;
//매퍼에 전달하기 위해 해쉬데이터 생성
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("startRowNum", startRowNum);
data.put("endRowNum", endRowNum);
data.put("field", field);
data.put("keyword", keyword);
return sql.selectList(namespace+".getList_view", data);
}
//게시물 개수 카운트
@Override
public int getCount(String field, String keyword) throws Exception {
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("field", field);
data.put("keyword", keyword);
return sql.selectOne(namespace + ".getCount", data);
}
//게시물 상세보기
@Override
public PostVO getDetail(int id) {
return sql.selectOne(namespace+".getDetail", id);
}
//게시물 등록
@Override
public void regPost(PostVO vo) throws Exception {
System.out.println(sql.insert(namespace + ".regPost", vo));
}
//게시물 삭제
@Override
public int delPost(int id, String password) throws Exception {
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("id", id);
data.put("password", <PASSWORD>);
return sql.delete(namespace+".delPost", data);
}
//게시물 조회수 갱신
@Override
public void updateHit(int id) throws Exception {
sql.update(namespace+".updateHit", id);
}
//게시물 패스워드 검증
@Override
public boolean checkPwd(int id, String password) throws Exception {
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("id", id);
data.put("password", <PASSWORD>);
boolean bool = sql.selectOne(namespace+".checkPwd", data);
System.out.println("불린값 확인" + bool);
return bool;
}
//게시물 수정
@Override
public void editPost(PostVO vo) throws Exception {
sql.update(namespace+".editPost", vo);
}
//파일 정보 삽입
@Override
public void regFile(FileVO vo) throws Exception {
sql.insert(namespace+".regFile", vo);
}
//파일 정보 보기
@Override
public List<FileVO> getFile(int id) {
return sql.selectList(namespace+".getFile", id);
}
//파일 삭제
@Override
public void delFile(int id) {
sql.delete(namespace+".delFile", id);
}
}
| 3,879 | 0.665916 | 0.661413 | 152 | 21.375 | 22.619802 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.822368 | false | false | 8 |
40e158ebc9e1942c4a54f3058c941b940ab198ff | 24,120,536,396,778 | 93e1fd72f6fa6e960e5330ef30fb5bfafba760fd | /src/main/java/com/matteoveroni/routerfx/core/RouterAnimation.java | 1f60054f9a79906d4236051ce585a3ee9ed42621 | [
"MIT"
] | permissive | mavek87/RouterFX | https://github.com/mavek87/RouterFX | 75c3567d31453f0e0b3e9ee1be95cdefe5e2180d | e992337f42643aca6fd5e62b67c7f050a5637b80 | refs/heads/master | 2023-04-30T18:39:48.817000 | 2021-05-14T21:07:11 | 2021-05-14T21:07:11 | 326,998,289 | 1 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.matteoveroni.routerfx.core;
/**
* @Author Matteo Veroni
*/
public enum RouterAnimation {
FADE_SHORT("fade", 1300.0),
FADE_MEDIUM("fade", 2100.0),
FADE_LONG("fade", 5000.0);
private final String name;
private final double duration;
RouterAnimation(String name, double duration) {
this.name = name;
this.duration = duration;
}
public String getName() {
return name;
}
public double getDuration() {
return duration;
}
}
| UTF-8 | Java | 518 | java | RouterAnimation.java | Java | [
{
"context": "ge com.matteoveroni.routerfx.core;\n\n/**\n * @Author Matteo Veroni\n */\npublic enum RouterAnimation {\n \n FADE_S",
"end": 69,
"score": 0.999870777130127,
"start": 56,
"tag": "NAME",
"value": "Matteo Veroni"
}
] | null | [] | package com.matteoveroni.routerfx.core;
/**
* @Author <NAME>
*/
public enum RouterAnimation {
FADE_SHORT("fade", 1300.0),
FADE_MEDIUM("fade", 2100.0),
FADE_LONG("fade", 5000.0);
private final String name;
private final double duration;
RouterAnimation(String name, double duration) {
this.name = name;
this.duration = duration;
}
public String getName() {
return name;
}
public double getDuration() {
return duration;
}
}
| 511 | 0.610039 | 0.581081 | 27 | 18.148148 | 15.296341 | 51 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.518519 | false | false | 8 |
1d9d208d8fcbf3cbcc000f24c2be7aa3464244d4 | 26,482,768,408,738 | 1ad205df819d00c8afd9eda7f90c446e5f5506e2 | /itlenergy-web/src/main/java/com/itl_energy/webapi/HouseResource.java | cb6b143b0315eb01b81eda4bc1528935e86d8e43 | [
"MIT"
] | permissive | itlenergy/itlenergy | https://github.com/itlenergy/itlenergy | 310a61dc28b1c9dbc36bceaf4ee9e0ae50450c93 | d363c89e16a2ca0459729c90fae3c05626943177 | refs/heads/master | 2020-05-28T08:49:47.218000 | 2015-02-19T12:22:32 | 2015-02-19T12:22:32 | 19,250,056 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.itl_energy.webapi;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.itl_energy.model.House;
import com.itl_energy.model.Hub;
import com.itl_energy.model.Tariff;
import com.itl_energy.model.ItemList;
import com.itl_energy.repo.HouseCollection;
import com.itl_energy.repo.HubCollection;
import com.itl_energy.repo.ForecastStatusCollection;
import com.itl_energy.repo.TariffCollection;
import com.itl_energy.webcore.AuthRoles;
/**
* The Web API RESTful interface to the Houses collection.
*
* @author Gordon Mackenzie-Leigh <gordon@stugo.co.uk>
* @author Bruce Stephen
*/
@Path("houses")
@Stateless
public class HouseResource extends ResourceBase<House>
{
@EJB HouseCollection houses;
@EJB HubCollection hubs;
@EJB TariffCollection tariffs;
@EJB ForecastStatusCollection forecasts;
@PostConstruct
void init()
{
super.collection = this.houses;
}
/**
* Gets all hubs for the specified house.
* @param id Any valid house id.
* @return HTTP 404 if house not found, or HTTP 200 ItemList entity response.
*/
@GET
@Path("{id}/hubs")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getHubs(@PathParam("id")int id)
{
requireRole(AuthRoles.ADMIN);
House house = houses.get(id);
if (house == null)
return Response.status(Response.Status.NOT_FOUND).build();
else
{
List<Hub> items = hubs.findByHouseId(id);
return Response.ok(new ItemList<>(items)).build();
}
}
/**
* Gets all tariffs for the specified house.
* @param id Any valid house id.
* @return HTTP 404 if house not found, or HTTP 200 ItemList entity response.
*/
@GET
@Path("{id}/tariffs")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getTariffs(@PathParam("id")int id)
{
requireRole(AuthRoles.ADMIN);
House house = houses.get(id);
if (house == null)
return Response.status(Response.Status.NOT_FOUND).build();
else
{
List<Tariff> items = tariffs.findByHouseId(id);
return Response.ok(new ItemList<>(items)).build();
}
}
} | UTF-8 | Java | 2,570 | java | HouseResource.java | Java | [
{
"context": "interface to the Houses collection.\n * \n * @author Gordon Mackenzie-Leigh <gordon@stugo.co.uk>\n * @author Bruce Stephen\n */",
"end": 790,
"score": 0.9998704791069031,
"start": 768,
"tag": "NAME",
"value": "Gordon Mackenzie-Leigh"
},
{
"context": "ollection.\n * \n *... | null | [] | package com.itl_energy.webapi;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.itl_energy.model.House;
import com.itl_energy.model.Hub;
import com.itl_energy.model.Tariff;
import com.itl_energy.model.ItemList;
import com.itl_energy.repo.HouseCollection;
import com.itl_energy.repo.HubCollection;
import com.itl_energy.repo.ForecastStatusCollection;
import com.itl_energy.repo.TariffCollection;
import com.itl_energy.webcore.AuthRoles;
/**
* The Web API RESTful interface to the Houses collection.
*
* @author <NAME> <<EMAIL>>
* @author <NAME>
*/
@Path("houses")
@Stateless
public class HouseResource extends ResourceBase<House>
{
@EJB HouseCollection houses;
@EJB HubCollection hubs;
@EJB TariffCollection tariffs;
@EJB ForecastStatusCollection forecasts;
@PostConstruct
void init()
{
super.collection = this.houses;
}
/**
* Gets all hubs for the specified house.
* @param id Any valid house id.
* @return HTTP 404 if house not found, or HTTP 200 ItemList entity response.
*/
@GET
@Path("{id}/hubs")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getHubs(@PathParam("id")int id)
{
requireRole(AuthRoles.ADMIN);
House house = houses.get(id);
if (house == null)
return Response.status(Response.Status.NOT_FOUND).build();
else
{
List<Hub> items = hubs.findByHouseId(id);
return Response.ok(new ItemList<>(items)).build();
}
}
/**
* Gets all tariffs for the specified house.
* @param id Any valid house id.
* @return HTTP 404 if house not found, or HTTP 200 ItemList entity response.
*/
@GET
@Path("{id}/tariffs")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getTariffs(@PathParam("id")int id)
{
requireRole(AuthRoles.ADMIN);
House house = houses.get(id);
if (house == null)
return Response.status(Response.Status.NOT_FOUND).build();
else
{
List<Tariff> items = tariffs.findByHouseId(id);
return Response.ok(new ItemList<>(items)).build();
}
}
} | 2,536 | 0.655642 | 0.650973 | 88 | 28.21591 | 21.038628 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.488636 | false | false | 8 |
15f013bf0c889521e1aa24fc1c45cc690b04ceb7 | 25,400,436,650,277 | b098fd8822750dd1db7b99407497687a8128a715 | /app/src/main/java/com/cgpanda/easyinvest/WebServices/PortfolioApi.java | 61698b0d98f3abda4ead53070f13a60023aaacff | [] | no_license | DenyingMad/easyInvestClient | https://github.com/DenyingMad/easyInvestClient | c5eb5e2e0e66b1bd7a1c8bcb2ba6c37b5bf6b87c | 30d4dc3d092773c96a6f9ea4356e545003bc7735 | refs/heads/master | 2022-08-06T12:12:35.173000 | 2020-05-27T00:39:38 | 2020-05-27T00:39:38 | 255,736,461 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cgpanda.easyinvest.WebServices;
import com.cgpanda.easyinvest.Entity.PortfolioSecurities.Securities;
import com.cgpanda.easyinvest.Entity.UserPortfolio;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Path;
public interface PortfolioApi {
@GET("user/securities/portfolio/")
Call<UserPortfolio> getUserPortfolio(@Header("api_key") String api_key);
@GET("{engine}/markets/{market}/boards/{boardid}/securities/{secid}.json?iss.json=extended&iss.meta=off")
Call<List<Securities>> getSecurities(@Path("engine") String engine, @Path("market") String market, @Path("boardid") String boardid, @Path("secid") String secid);
}
| UTF-8 | Java | 727 | java | PortfolioApi.java | Java | [] | null | [] | package com.cgpanda.easyinvest.WebServices;
import com.cgpanda.easyinvest.Entity.PortfolioSecurities.Securities;
import com.cgpanda.easyinvest.Entity.UserPortfolio;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Path;
public interface PortfolioApi {
@GET("user/securities/portfolio/")
Call<UserPortfolio> getUserPortfolio(@Header("api_key") String api_key);
@GET("{engine}/markets/{market}/boards/{boardid}/securities/{secid}.json?iss.json=extended&iss.meta=off")
Call<List<Securities>> getSecurities(@Path("engine") String engine, @Path("market") String market, @Path("boardid") String boardid, @Path("secid") String secid);
}
| 727 | 0.768913 | 0.763411 | 19 | 37.263157 | 41.797562 | 165 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.684211 | false | false | 8 |
b5733698ab492c6aa1c0ed0149a50fa7ee04d683 | 25,039,659,348,002 | 444082f787c56410a6ef62d2fca03f848008cb98 | /factions/src/main/java/me/mickmmars/factions/factions/flags/FactionFlag.java | 6c31054dc5f6b9215bbf579de8e00f8765e07a63 | [] | no_license | amxrmxhdx/PixliesFactionSystem-2.0 | https://github.com/amxrmxhdx/PixliesFactionSystem-2.0 | 3861ab974b731de0c73ffbbc4e486f5c9d1c6bca | a8e099f189a14c936f7e59c0e552dada5108ff22 | refs/heads/master | 2022-04-11T15:14:24.033000 | 2020-01-18T04:30:50 | 2020-01-18T04:30:50 | 217,929,229 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package me.mickmmars.factions.factions.flags;
import java.util.ArrayList;
import java.util.List;
public enum FactionFlag {
FRIENDLYFIRE("§cFriendly-fire", false),
PVP("§cPvP", false),
INFPOWER("§cInfinite power", false),
EXPLOSIONS("§cExplosions", true),
OPEN("§cOpen/No-invitation", false),
ANIMALS("§cAnimals", true),
PERMANENT("§cPermanent", false),
MONSTER("§cMonsters", false);
private final String name;
private Boolean value;
private static List<FactionFlag> flags = new ArrayList<FactionFlag>();
FactionFlag(String name, Boolean value) {
this.name = name;
this.value = value;
}
public Boolean getValue() { return value; }
public void setValue(Boolean value) { this.value = value; }
public String getName() {
return name;
}
}
| UTF-8 | Java | 841 | java | FactionFlag.java | Java | [
{
"context": "package me.mickmmars.factions.factions.flags;\n\nimport java.util.ArrayL",
"end": 20,
"score": 0.7113462090492249,
"start": 12,
"tag": "USERNAME",
"value": "ickmmars"
}
] | null | [] | package me.mickmmars.factions.factions.flags;
import java.util.ArrayList;
import java.util.List;
public enum FactionFlag {
FRIENDLYFIRE("§cFriendly-fire", false),
PVP("§cPvP", false),
INFPOWER("§cInfinite power", false),
EXPLOSIONS("§cExplosions", true),
OPEN("§cOpen/No-invitation", false),
ANIMALS("§cAnimals", true),
PERMANENT("§cPermanent", false),
MONSTER("§cMonsters", false);
private final String name;
private Boolean value;
private static List<FactionFlag> flags = new ArrayList<FactionFlag>();
FactionFlag(String name, Boolean value) {
this.name = name;
this.value = value;
}
public Boolean getValue() { return value; }
public void setValue(Boolean value) { this.value = value; }
public String getName() {
return name;
}
}
| 841 | 0.655462 | 0.655462 | 33 | 24.242424 | 19.625324 | 74 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.848485 | false | false | 8 |
643621433bda7c8fa6f887b27146e07f9c211e3b | 4,183,298,204,535 | de0bb0ab119a38f65d354c07145a85daaf686f7c | /src/com/ericsson/oss/tool/MOGetServiceFactoryEditor.java | d870451227a49f38722d472e38a26da3a73b08d1 | [] | no_license | fanfang2014/CodeGenerator | https://github.com/fanfang2014/CodeGenerator | e50718cc7be89d4910f7237b4d7e65231f00b93b | 36a00c0d1cf53543acc192d8efdbfb83f3ce54cd | refs/heads/master | 2020-06-13T09:13:57.543000 | 2016-12-02T20:41:06 | 2016-12-02T20:41:06 | 75,428,802 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*------------------------------------------------------------------------------
*******************************************************************************
* COPYRIGHT Ericsson 2013
*
* The copyright to the computer program(s) herein is the property of
* Ericsson Inc. The programs may be used and/or copied only with written
* permission from Ericsson Inc. or in accordance with the terms and
* conditions stipulated in the agreement/contract under which the
* program(s) have been supplied.
*******************************************************************************
*----------------------------------------------------------------------------*/
package com.ericsson.oss.tool;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
public class MOGetServiceFactoryEditor {
public static final String tab = " ";
public static void editModelTest(String fullPathFileName, String neTypeEnum, String neTypeString)
{
BufferedReader reader = null;
BufferedWriter writer = null;
ArrayList<String> list = new ArrayList<String>();
try {
reader = new BufferedReader(new FileReader(fullPathFileName));
String tmp;
while ((tmp = reader.readLine()) != null)
list.add(tmp);
Iterator<String> it = list.iterator();
int index = 0;
while (it.hasNext()) {
String nextLine = it.next().toString();
if(nextLine.contains("public void testGetCapabilityModelForVMRFNodeReference() {"))
{
for (int i = 0; i < 5; i++)
{
it.next();
index++;
}
list.add(index++, tab);
list.add(index++, tab + "@Test");
list.add(index++, tab + "public void testGetCapabilityModelFor" + neTypeEnum + "NodeReference() {");
list.add(index++, tab + tab + "when(moGetServiceInstances.select(any(NscsCertificateStateInfoTypeQualifier.class))).thenReturn(moGetServiceInstances);");
list.add(index++, tab + tab + "when(moGetServiceInstances.get()).thenReturn(comEcimCertificateStateInfo);");
list.add(index++, tab + tab + "assertEquals(comEcimCertificateStateInfo, beanUnderTest.getMOGetService(" + neTypeString + "NodeRef));");
list.add(index++, tab +"}");
it = list.subList(index+1, list.size() - 1).iterator();
}
else if(nextLine.contains("private static final String VMRF_NODE_NAME = "))
{
it.next();
index++;
list.add(index++, tab + "private static final String " + neTypeEnum + "_NODE_NAME = \"" + neTypeEnum + "123\";");
it = list.subList(index+1, list.size() - 1).iterator();
}
else if(nextLine.contains("private final NodeReference vMRFNodeRef = new NodeRef(VMRF_NODE_NAME);"))
{
it.next();
index++;
list.add(index++, tab + "private final NodeReference " + neTypeString + "NodeRef = new NodeRef(" + neTypeEnum + "_NODE_NAME);");
it = list.subList(index+1, list.size() - 1).iterator();
}
else if(nextLine.contains("when(capabilityService.getMOGetServiceType(vMRFNodeRef)).thenReturn(COM_ECIM_FAMILY);"))
{
it.next();
index++;
list.add(index++, tab + "when(capabilityService.getMOGetServiceType(" + neTypeString + "NodeRef)).thenReturn(COM_ECIM_FAMILY);");
it = list.subList(index+1, list.size() - 1).iterator();
}
index++;
}
writer = new BufferedWriter(new FileWriter(fullPathFileName));
for (int i = 0; i < list.size(); i++)
writer.write(list.get(i) + "\r\n");
writer.flush();
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
| UTF-8 | Java | 4,230 | java | MOGetServiceFactoryEditor.java | Java | [
{
"context": "*************************************\n * COPYRIGHT Ericsson 2013\n *\n * The copyright to the computer prog",
"end": 179,
"score": 0.9714498519897461,
"start": 175,
"tag": "NAME",
"value": "Eric"
}
] | null | [] | /*------------------------------------------------------------------------------
*******************************************************************************
* COPYRIGHT Ericsson 2013
*
* The copyright to the computer program(s) herein is the property of
* Ericsson Inc. The programs may be used and/or copied only with written
* permission from Ericsson Inc. or in accordance with the terms and
* conditions stipulated in the agreement/contract under which the
* program(s) have been supplied.
*******************************************************************************
*----------------------------------------------------------------------------*/
package com.ericsson.oss.tool;
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
public class MOGetServiceFactoryEditor {
public static final String tab = " ";
public static void editModelTest(String fullPathFileName, String neTypeEnum, String neTypeString)
{
BufferedReader reader = null;
BufferedWriter writer = null;
ArrayList<String> list = new ArrayList<String>();
try {
reader = new BufferedReader(new FileReader(fullPathFileName));
String tmp;
while ((tmp = reader.readLine()) != null)
list.add(tmp);
Iterator<String> it = list.iterator();
int index = 0;
while (it.hasNext()) {
String nextLine = it.next().toString();
if(nextLine.contains("public void testGetCapabilityModelForVMRFNodeReference() {"))
{
for (int i = 0; i < 5; i++)
{
it.next();
index++;
}
list.add(index++, tab);
list.add(index++, tab + "@Test");
list.add(index++, tab + "public void testGetCapabilityModelFor" + neTypeEnum + "NodeReference() {");
list.add(index++, tab + tab + "when(moGetServiceInstances.select(any(NscsCertificateStateInfoTypeQualifier.class))).thenReturn(moGetServiceInstances);");
list.add(index++, tab + tab + "when(moGetServiceInstances.get()).thenReturn(comEcimCertificateStateInfo);");
list.add(index++, tab + tab + "assertEquals(comEcimCertificateStateInfo, beanUnderTest.getMOGetService(" + neTypeString + "NodeRef));");
list.add(index++, tab +"}");
it = list.subList(index+1, list.size() - 1).iterator();
}
else if(nextLine.contains("private static final String VMRF_NODE_NAME = "))
{
it.next();
index++;
list.add(index++, tab + "private static final String " + neTypeEnum + "_NODE_NAME = \"" + neTypeEnum + "123\";");
it = list.subList(index+1, list.size() - 1).iterator();
}
else if(nextLine.contains("private final NodeReference vMRFNodeRef = new NodeRef(VMRF_NODE_NAME);"))
{
it.next();
index++;
list.add(index++, tab + "private final NodeReference " + neTypeString + "NodeRef = new NodeRef(" + neTypeEnum + "_NODE_NAME);");
it = list.subList(index+1, list.size() - 1).iterator();
}
else if(nextLine.contains("when(capabilityService.getMOGetServiceType(vMRFNodeRef)).thenReturn(COM_ECIM_FAMILY);"))
{
it.next();
index++;
list.add(index++, tab + "when(capabilityService.getMOGetServiceType(" + neTypeString + "NodeRef)).thenReturn(COM_ECIM_FAMILY);");
it = list.subList(index+1, list.size() - 1).iterator();
}
index++;
}
writer = new BufferedWriter(new FileWriter(fullPathFileName));
for (int i = 0; i < list.size(); i++)
writer.write(list.get(i) + "\r\n");
writer.flush();
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
| 4,230 | 0.495508 | 0.491017 | 84 | 49.357143 | 40.010605 | 173 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.833333 | false | false | 8 |
06b3747f42ee11b335592086691458d572ed09da | 7,327,214,225,607 | 01468fdfe1a9877a2ae8f97b33ead3de187dfca8 | /fling/src/main/java/org/apache/sling/samples/fling/validation/CommentValidator.java | 0991ea83c8ad79410820a70c675e692f70a29624 | [
"Apache-2.0"
] | permissive | apache/sling-samples | https://github.com/apache/sling-samples | 63566d33ca885b4591051c122368e605453d11fc | d3929f88a7c11e4ef89f08a12d221f193daac921 | refs/heads/master | 2023-08-29T07:59:36.785000 | 2023-04-04T21:12:56 | 2023-04-04T21:12:56 | 107,436,391 | 37 | 25 | Apache-2.0 | false | 2023-02-14T21:25:44 | 2017-10-18T16:46:47 | 2022-12-25T01:54:50 | 2023-02-14T21:25:43 | 9,285 | 30 | 21 | 9 | Java | false | false | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sling.samples.fling.validation;
import javax.annotation.Nonnull;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.validation.SlingValidationException;
import org.apache.sling.validation.ValidationFailure;
import org.apache.sling.validation.ValidationResult;
import org.apache.sling.validation.spi.support.DefaultValidationFailure;
import org.apache.sling.validation.spi.support.DefaultValidationResult;
import org.apache.sling.validation.spi.ValidatorContext;
import org.apache.sling.validation.spi.Validator;
import org.osgi.framework.Constants;
import org.osgi.service.component.annotations.Component;
@Component(
service = Validator.class,
property = {
Constants.SERVICE_DESCRIPTION + "=Apache Sling Fling Sample “Comment Validator”",
Constants.SERVICE_VENDOR + "=The Apache Software Foundation",
"validator.id=org.apache.sling.samples.fling.validation.CommentValidator"
},
immediate = true
)
public class CommentValidator implements Validator<String> {
private static final String COMMENT_PARAMETER = "comment";
private static final String I18N_MESSAGE_KEY = "fling.validator.comment.invalid";
@Override
@Nonnull
public ValidationResult validate(@Nonnull String data, @Nonnull ValidatorContext validatorContext, @Nonnull ValueMap arguments) throws SlingValidationException {
final String comment = arguments.get(COMMENT_PARAMETER, String.class);
if (comment == null) {
throw new SlingValidationException("Valid comment is missing.");
}
if (comment.equals(data)) {
return DefaultValidationResult.VALID;
} else {
final ValidationFailure failure = new DefaultValidationFailure(validatorContext.getLocation(), 0, validatorContext.getDefaultResourceBundle(), I18N_MESSAGE_KEY, comment);
return new DefaultValidationResult(failure);
}
}
}
| UTF-8 | Java | 2,757 | java | CommentValidator.java | Java | [
{
"context": " private static final String I18N_MESSAGE_KEY = \"fling.validator.comment.invalid\";\n\n @Override\n @Nonnull\n public Validati",
"end": 1997,
"score": 0.857876181602478,
"start": 1966,
"tag": "KEY",
"value": "fling.validator.comment.invalid"
}
] | null | [] | /*
* 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.sling.samples.fling.validation;
import javax.annotation.Nonnull;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.validation.SlingValidationException;
import org.apache.sling.validation.ValidationFailure;
import org.apache.sling.validation.ValidationResult;
import org.apache.sling.validation.spi.support.DefaultValidationFailure;
import org.apache.sling.validation.spi.support.DefaultValidationResult;
import org.apache.sling.validation.spi.ValidatorContext;
import org.apache.sling.validation.spi.Validator;
import org.osgi.framework.Constants;
import org.osgi.service.component.annotations.Component;
@Component(
service = Validator.class,
property = {
Constants.SERVICE_DESCRIPTION + "=Apache Sling Fling Sample “Comment Validator”",
Constants.SERVICE_VENDOR + "=The Apache Software Foundation",
"validator.id=org.apache.sling.samples.fling.validation.CommentValidator"
},
immediate = true
)
public class CommentValidator implements Validator<String> {
private static final String COMMENT_PARAMETER = "comment";
private static final String I18N_MESSAGE_KEY = "fling.validator.comment.invalid";
@Override
@Nonnull
public ValidationResult validate(@Nonnull String data, @Nonnull ValidatorContext validatorContext, @Nonnull ValueMap arguments) throws SlingValidationException {
final String comment = arguments.get(COMMENT_PARAMETER, String.class);
if (comment == null) {
throw new SlingValidationException("Valid comment is missing.");
}
if (comment.equals(data)) {
return DefaultValidationResult.VALID;
} else {
final ValidationFailure failure = new DefaultValidationFailure(validatorContext.getLocation(), 0, validatorContext.getDefaultResourceBundle(), I18N_MESSAGE_KEY, comment);
return new DefaultValidationResult(failure);
}
}
}
| 2,757 | 0.75336 | 0.750091 | 64 | 42.015625 | 36.090813 | 182 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.546875 | false | false | 8 |
1c5afac6ccc86926c77ba0cf46c78178b37eff9d | 7,662,221,660,249 | 0a23ebc186578ed2aab06d74c0184d5e052ffef3 | /coursemanagement/src/main/java/com/vontroy/pku_ss_cloud_class/utils/DecryptHelper.java | 39b8a09662fc56d66faab0f054258b6dd9545bf1 | [] | no_license | fxyburan/cloud_class_android | https://github.com/fxyburan/cloud_class_android | b77949661875c0bd8d1040ced4d8912f1237a8d4 | c599919df8544d723d7fbbaa73a89af42f394b77 | refs/heads/master | 2023-08-10T10:31:31.373000 | 2018-12-03T07:37:21 | 2018-12-03T07:37:21 | 160,150,691 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.vontroy.pku_ss_cloud_class.utils;
/**
* Created by LinkedME06 on 16/10/29.
*/
public class DecryptHelper {
/**
* 密码+随机码加密
*
* @param password
* @param rnd
* @return
*/
public static String getEncryptedPassword(String password, String rnd) {
return Decrypt.MD5(Decrypt.MD5(password) + rnd);
}
/**
* 密码加密
*
* @param password
* @return
*/
public static String getEncryptedPassword(String password) {
return Decrypt.SHA1(password);
}
public static void main(String[] args) {
System.out.print("ddddd" + DecryptHelper.getEncryptedPassword("12345678", "0.47684905941392275"));
// System.out.print("ddddd" +DecryptHelper.getEncryptedPassword("12345678"));
}
}
| UTF-8 | Java | 811 | java | DecryptHelper.java | Java | [
{
"context": "ntroy.pku_ss_cloud_class.utils;\n\n/**\n * Created by LinkedME06 on 16/10/29.\n */\n\npublic class DecryptHelper {\n\n ",
"end": 75,
"score": 0.9994775056838989,
"start": 65,
"tag": "USERNAME",
"value": "LinkedME06"
},
{
"context": "int(\"ddddd\" + DecryptHelper.getEncr... | null | [] | package com.vontroy.pku_ss_cloud_class.utils;
/**
* Created by LinkedME06 on 16/10/29.
*/
public class DecryptHelper {
/**
* 密码+随机码加密
*
* @param password
* @param rnd
* @return
*/
public static String getEncryptedPassword(String password, String rnd) {
return Decrypt.MD5(Decrypt.MD5(password) + rnd);
}
/**
* 密码加密
*
* @param password
* @return
*/
public static String getEncryptedPassword(String password) {
return Decrypt.SHA1(password);
}
public static void main(String[] args) {
System.out.print("ddddd" + DecryptHelper.getEncryptedPassword("<PASSWORD>", "<PASSWORD>"));
// System.out.print("ddddd" +DecryptHelper.getEncryptedPassword("<PASSWORD>"));
}
}
| 806 | 0.618504 | 0.56147 | 35 | 21.542856 | 26.621519 | 106 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.2 | false | false | 8 |
bee979e4df627bd24bae44ca3e63e6839a1012fb | 17,652,315,599,068 | fb9b73bd6c59bac7b9f84d60d60932206ff40f74 | /BusReservationThreading/src/BusReservation.java | 085b5ae1a4960eb554e406b331dddf5ce1663d60 | [] | no_license | KaushikVeluruWorld/KaushikJava | https://github.com/KaushikVeluruWorld/KaushikJava | e92d583236900f154566ae68d79271c04c74aff8 | 17dce8a14dbcfc5df09367b3b356cecd07fe0d13 | refs/heads/master | 2016-09-05T10:06:26.940000 | 2015-03-09T07:33:44 | 2015-03-09T07:33:44 | 26,847,050 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
public class BusReservation implements Runnable{
public int ticketsAvailable=3;
public void run()
{
PersonThread pr=(PersonThread)Thread.currentThread();
boolean ticketsBooked=bookTickets(pr.getSeatsNeeded(), pr.getName());
if(ticketsBooked)
{
System.out.println("Congrats "+pr.getName()+" "+pr.getSeatsNeeded()+" booked");
}
else
System.out.println("Sorry "+pr.getName()+" requestd seats ("+pr.getSeatsNeeded()+") are not available");
System.out.println("Seats remaining: "+ticketsAvailable);
}
public synchronized boolean bookTickets(int seats, String name)
{
boolean isBooked=false;
System.out.println("Hello "+Thread.currentThread().getName()+" Total seats available: "+ticketsAvailable);
if(seats<=ticketsAvailable)
{
ticketsAvailable=ticketsAvailable-seats;
isBooked=true;
}
return isBooked;
}
}
| UTF-8 | Java | 872 | java | BusReservation.java | Java | [] | null | [] |
public class BusReservation implements Runnable{
public int ticketsAvailable=3;
public void run()
{
PersonThread pr=(PersonThread)Thread.currentThread();
boolean ticketsBooked=bookTickets(pr.getSeatsNeeded(), pr.getName());
if(ticketsBooked)
{
System.out.println("Congrats "+pr.getName()+" "+pr.getSeatsNeeded()+" booked");
}
else
System.out.println("Sorry "+pr.getName()+" requestd seats ("+pr.getSeatsNeeded()+") are not available");
System.out.println("Seats remaining: "+ticketsAvailable);
}
public synchronized boolean bookTickets(int seats, String name)
{
boolean isBooked=false;
System.out.println("Hello "+Thread.currentThread().getName()+" Total seats available: "+ticketsAvailable);
if(seats<=ticketsAvailable)
{
ticketsAvailable=ticketsAvailable-seats;
isBooked=true;
}
return isBooked;
}
}
| 872 | 0.709862 | 0.708716 | 35 | 23.885714 | 30.942131 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.085714 | false | false | 8 |
6c1ff584ea8d4db04257fc9204cdb45ed8056fa8 | 11,269,994,196,480 | 756ee660b9fb322279e8950e8d3ea268cb8f6051 | /app/src/main/java/de/hs_niederrhein/chat/hsnrchat/ChatActivity.java | e59704dcbf14251b5be1cf8ce43ceb9ac5ba6ac1 | [] | no_license | vimac001/HSNRChat | https://github.com/vimac001/HSNRChat | 5af7cffd9339d6f9adb7824239b8a14e040fe7ab | 1f0a6dd5bf166d7effaa547017eefe82875adb4c | refs/heads/master | 2021-01-10T01:27:46.991000 | 2016-01-19T14:02:17 | 2016-01-19T14:02:17 | 44,809,111 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package de.hs_niederrhein.chat.hsnrchat;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.io.IOException;
import java.security.Timestamp;
import java.util.ArrayList;
import java.util.List;
import de.hs_niederrhein.chat.hsnrchat.Database.DatabaseOpenHelper;
import de.hs_niederrhein.chat.hsnrchat.Networking.Exception.ClientErrorException;
import de.hs_niederrhein.chat.hsnrchat.Networking.Exception.ClientNotAutheticatedException;
import de.hs_niederrhein.chat.hsnrchat.Networking.Exception.ConnectionTimeoutException;
import de.hs_niederrhein.chat.hsnrchat.Networking.Exception.InvalidResponseStatusException;
import de.hs_niederrhein.chat.hsnrchat.Networking.Exception.InvalidSSIDException;
import de.hs_niederrhein.chat.hsnrchat.Networking.Exception.RoomNotFoundException;
import de.hs_niederrhein.chat.hsnrchat.Networking.Exception.ServerErrorException;
import de.hs_niederrhein.chat.hsnrchat.Networking.Exception.UserNotFoundException;
import de.hs_niederrhein.chat.hsnrchat.Networking.User;
import de.hs_niederrhein.chat.hsnrchat.types.Faculty;
import de.hs_niederrhein.chat.hsnrchat.types.Finisher;
import de.hs_niederrhein.chat.hsnrchat.types.Message;
public class ChatActivity extends AppCompatActivity {
private int facID;
private int lastUpdate;
private List<Message> messages = new ArrayList<>();
private ArrayAdapter<Message> messageAdapter;
private DatabaseOpenHelper db = new DatabaseOpenHelper(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Finisher.register(this);
setContentView(R.layout.activity_chat);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
this.lastUpdate = 0;
//Thread starten um neue Nachrichten zu überwachen
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while(!Thread.currentThread().isInterrupted()){
try {
populateMessages();
Thread.sleep(1000,0);
} catch (IOException e) {
e.printStackTrace();
} catch (ClientNotAutheticatedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();
Intent intent = getIntent();
if(intent.hasExtra("facID")){
this.facID = intent.getIntExtra("facID",0);
}
ListView listView = (ListView) findViewById(R.id.chat_listview);
listView.smoothScrollToPosition(messages.size());
populateMessageListView();
registerClick();
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.fac:
changeToMainActivity();
return true;
case R.id.location:
changeToLocationActivity();
return true;
case R.id.logout:
Finisher.finishApp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void changeToMainActivity(){
Intent changeToMainActivity = new Intent(this, MainActivity.class);
startActivity(changeToMainActivity);
}
private void changeToLocationActivity(){
Intent changeToLocationActivity = new Intent(this, LocationActivity.class);
startActivity(changeToLocationActivity);
}
private long getUserID() throws IOException, ClientNotAutheticatedException {
return ClientServerCommunicator.get(this).getUserId();
}
public void populateMessages() throws IOException, ClientNotAutheticatedException {
boolean isRight;
SQLiteDatabase read = db.getReadableDatabase();
String where_clause = db.facNummer + "=" + this.facID + " AND " + db.timeStamp + " > " + this.lastUpdate ;
Cursor c = read.query(db.messages, new String[]{db.facNummer, db.message, db.userID, db.timeStamp}, where_clause,null,null,null, db.timeStamp);
if(c.getCount() > 0){
while(c.moveToNext()){
//Vergleichen ob es der eigene User ist oder nicht
if(getUserID() == c.getLong(c.getColumnIndex(db.userID)) ){
isRight = true;
}
else{
isRight = false;
}
messages.add(new Message(
(long)c.getInt(c.getColumnIndex(db.facNummer)),
(long)c.getLong(c.getColumnIndex(db.userID)),
c.getString(c.getColumnIndex(db.message)),
isRight));
this.lastUpdate = c.getInt(c.getColumnIndex(db.timeStamp));
}
}
}
private void populateMessageListView() {
this.messageAdapter = new ChatAdapter();
ListView listView_chat = (ListView)findViewById(R.id.chat_listview);
listView_chat.setAdapter(messageAdapter);
}
private void registerClick() {
Button btSend = (Button)findViewById(R.id.chat_btsend);
btSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText editText = (EditText) findViewById(R.id.chat_edit);
if (editText.getText().toString() != "") {
//Nachricht an Server schicken
try {
sendMessageToServer(editText.getText().toString());
} catch (IOException e) {
e.printStackTrace();
} catch (ClientErrorException e) {
e.printStackTrace();
} catch (InvalidSSIDException e) {
e.printStackTrace();
} catch (InvalidResponseStatusException e) {
e.printStackTrace();
} catch (ServerErrorException e) {
e.printStackTrace();
} catch (ConnectionTimeoutException e) {
e.printStackTrace();
} catch (RoomNotFoundException e) {
e.printStackTrace();
} catch (ClientNotAutheticatedException e) {
e.printStackTrace();
}
//Editfeld leeren
editText.setText("");
//Tastatur schließen
hideKeyboard(ChatActivity.this);
//Um immer nach unten zu scrollen
ListView listView = (ListView) findViewById(R.id.chat_listview);
listView.smoothScrollToPosition(messages.size());
}
}
});
}
public void sendMessageToServer(String message) throws IOException, ClientErrorException, InvalidSSIDException, InvalidResponseStatusException, ServerErrorException, ConnectionTimeoutException, RoomNotFoundException, ClientNotAutheticatedException {
ClientServerCommunicator.get(this).sendMessage((short) this.facID, message);
}
public static void hideKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
View view = activity.getCurrentFocus();
if(view == null) {
view = new View(activity);
}
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
private class ChatAdapter extends ArrayAdapter<Message> {
public ChatAdapter() {
super(ChatActivity.this, R.layout.item_chat_right, messages);
}
@Override
public void add(Message msg){
super.add(msg);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
Message currentMessage = messages.get(position);
if(currentMessage.getIsRight() == true)
itemView = getLayoutInflater().inflate(R.layout.item_chat_right, parent, false);
else
itemView = getLayoutInflater().inflate(R.layout.item_chat_left,parent,false);
User currentUser = null;
try {
currentUser = ClientServerCommunicator.get().resolveUser(currentMessage.getUserID());
} catch (ServerErrorException e) {
e.printStackTrace();
} catch (InvalidSSIDException e) {
e.printStackTrace();
} catch (UserNotFoundException e) {
e.printStackTrace();
} catch (ClientNotAutheticatedException e) {
e.printStackTrace();
} catch (ClientErrorException e) {
e.printStackTrace();
} catch (ConnectionTimeoutException e) {
e.printStackTrace();
} catch (InvalidResponseStatusException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String textToShow = currentUser.getDisplayName() + ": " + currentMessage.getMessage();
TextView textLayout = (TextView) itemView.findViewById(R.id.id_text);
textLayout.setText(textToShow);
return itemView;
}
}
}
| UTF-8 | Java | 10,694 | java | ChatActivity.java | Java | [] | null | [] | package de.hs_niederrhein.chat.hsnrchat;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.io.IOException;
import java.security.Timestamp;
import java.util.ArrayList;
import java.util.List;
import de.hs_niederrhein.chat.hsnrchat.Database.DatabaseOpenHelper;
import de.hs_niederrhein.chat.hsnrchat.Networking.Exception.ClientErrorException;
import de.hs_niederrhein.chat.hsnrchat.Networking.Exception.ClientNotAutheticatedException;
import de.hs_niederrhein.chat.hsnrchat.Networking.Exception.ConnectionTimeoutException;
import de.hs_niederrhein.chat.hsnrchat.Networking.Exception.InvalidResponseStatusException;
import de.hs_niederrhein.chat.hsnrchat.Networking.Exception.InvalidSSIDException;
import de.hs_niederrhein.chat.hsnrchat.Networking.Exception.RoomNotFoundException;
import de.hs_niederrhein.chat.hsnrchat.Networking.Exception.ServerErrorException;
import de.hs_niederrhein.chat.hsnrchat.Networking.Exception.UserNotFoundException;
import de.hs_niederrhein.chat.hsnrchat.Networking.User;
import de.hs_niederrhein.chat.hsnrchat.types.Faculty;
import de.hs_niederrhein.chat.hsnrchat.types.Finisher;
import de.hs_niederrhein.chat.hsnrchat.types.Message;
public class ChatActivity extends AppCompatActivity {
private int facID;
private int lastUpdate;
private List<Message> messages = new ArrayList<>();
private ArrayAdapter<Message> messageAdapter;
private DatabaseOpenHelper db = new DatabaseOpenHelper(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Finisher.register(this);
setContentView(R.layout.activity_chat);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
this.lastUpdate = 0;
//Thread starten um neue Nachrichten zu überwachen
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while(!Thread.currentThread().isInterrupted()){
try {
populateMessages();
Thread.sleep(1000,0);
} catch (IOException e) {
e.printStackTrace();
} catch (ClientNotAutheticatedException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();
Intent intent = getIntent();
if(intent.hasExtra("facID")){
this.facID = intent.getIntExtra("facID",0);
}
ListView listView = (ListView) findViewById(R.id.chat_listview);
listView.smoothScrollToPosition(messages.size());
populateMessageListView();
registerClick();
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.fac:
changeToMainActivity();
return true;
case R.id.location:
changeToLocationActivity();
return true;
case R.id.logout:
Finisher.finishApp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void changeToMainActivity(){
Intent changeToMainActivity = new Intent(this, MainActivity.class);
startActivity(changeToMainActivity);
}
private void changeToLocationActivity(){
Intent changeToLocationActivity = new Intent(this, LocationActivity.class);
startActivity(changeToLocationActivity);
}
private long getUserID() throws IOException, ClientNotAutheticatedException {
return ClientServerCommunicator.get(this).getUserId();
}
public void populateMessages() throws IOException, ClientNotAutheticatedException {
boolean isRight;
SQLiteDatabase read = db.getReadableDatabase();
String where_clause = db.facNummer + "=" + this.facID + " AND " + db.timeStamp + " > " + this.lastUpdate ;
Cursor c = read.query(db.messages, new String[]{db.facNummer, db.message, db.userID, db.timeStamp}, where_clause,null,null,null, db.timeStamp);
if(c.getCount() > 0){
while(c.moveToNext()){
//Vergleichen ob es der eigene User ist oder nicht
if(getUserID() == c.getLong(c.getColumnIndex(db.userID)) ){
isRight = true;
}
else{
isRight = false;
}
messages.add(new Message(
(long)c.getInt(c.getColumnIndex(db.facNummer)),
(long)c.getLong(c.getColumnIndex(db.userID)),
c.getString(c.getColumnIndex(db.message)),
isRight));
this.lastUpdate = c.getInt(c.getColumnIndex(db.timeStamp));
}
}
}
private void populateMessageListView() {
this.messageAdapter = new ChatAdapter();
ListView listView_chat = (ListView)findViewById(R.id.chat_listview);
listView_chat.setAdapter(messageAdapter);
}
private void registerClick() {
Button btSend = (Button)findViewById(R.id.chat_btsend);
btSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText editText = (EditText) findViewById(R.id.chat_edit);
if (editText.getText().toString() != "") {
//Nachricht an Server schicken
try {
sendMessageToServer(editText.getText().toString());
} catch (IOException e) {
e.printStackTrace();
} catch (ClientErrorException e) {
e.printStackTrace();
} catch (InvalidSSIDException e) {
e.printStackTrace();
} catch (InvalidResponseStatusException e) {
e.printStackTrace();
} catch (ServerErrorException e) {
e.printStackTrace();
} catch (ConnectionTimeoutException e) {
e.printStackTrace();
} catch (RoomNotFoundException e) {
e.printStackTrace();
} catch (ClientNotAutheticatedException e) {
e.printStackTrace();
}
//Editfeld leeren
editText.setText("");
//Tastatur schließen
hideKeyboard(ChatActivity.this);
//Um immer nach unten zu scrollen
ListView listView = (ListView) findViewById(R.id.chat_listview);
listView.smoothScrollToPosition(messages.size());
}
}
});
}
public void sendMessageToServer(String message) throws IOException, ClientErrorException, InvalidSSIDException, InvalidResponseStatusException, ServerErrorException, ConnectionTimeoutException, RoomNotFoundException, ClientNotAutheticatedException {
ClientServerCommunicator.get(this).sendMessage((short) this.facID, message);
}
public static void hideKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
View view = activity.getCurrentFocus();
if(view == null) {
view = new View(activity);
}
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
private class ChatAdapter extends ArrayAdapter<Message> {
public ChatAdapter() {
super(ChatActivity.this, R.layout.item_chat_right, messages);
}
@Override
public void add(Message msg){
super.add(msg);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
Message currentMessage = messages.get(position);
if(currentMessage.getIsRight() == true)
itemView = getLayoutInflater().inflate(R.layout.item_chat_right, parent, false);
else
itemView = getLayoutInflater().inflate(R.layout.item_chat_left,parent,false);
User currentUser = null;
try {
currentUser = ClientServerCommunicator.get().resolveUser(currentMessage.getUserID());
} catch (ServerErrorException e) {
e.printStackTrace();
} catch (InvalidSSIDException e) {
e.printStackTrace();
} catch (UserNotFoundException e) {
e.printStackTrace();
} catch (ClientNotAutheticatedException e) {
e.printStackTrace();
} catch (ClientErrorException e) {
e.printStackTrace();
} catch (ConnectionTimeoutException e) {
e.printStackTrace();
} catch (InvalidResponseStatusException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String textToShow = currentUser.getDisplayName() + ": " + currentMessage.getMessage();
TextView textLayout = (TextView) itemView.findViewById(R.id.id_text);
textLayout.setText(textToShow);
return itemView;
}
}
}
| 10,694 | 0.617565 | 0.616536 | 280 | 37.185715 | 30.000854 | 253 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.603571 | false | false | 8 |
68bea6642fd61253f2d6ce22de540382d8363e3c | 11,501,922,486,924 | f70f602eecede376489cbd098dd9b058714b4bf5 | /EmergeBL/src/main/java/emerge/ebuild/EbuildReader.java | 36d794007ce596e0acafe93195bbe05ba5ffb851 | [] | no_license | jameskirk/emerge | https://github.com/jameskirk/emerge | 36e45e9aad252b8ac60963d9018ac35fd0c13da2 | c072089f93f5c1aaa3a959fbbde8f95ddd8caf31 | refs/heads/master | 2016-08-05T12:43:13.983000 | 2015-01-28T16:11:58 | 2015-01-28T16:11:58 | 29,972,491 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package emerge.ebuild;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
import emerge.conf.Configuration;
import emerge.entity.Keyword;
import emerge.entity.KeywordGroup;
import emerge.misc.EmergeException;
import emerge.misc.FileHelper;
public class EbuildReader {
public EbuildReader() {
}
/**
* ebuildId can be /app-arch/p7zip-2.5.0-r2.ebuild
* @param ebuildId
*/
public EbuildFile read(String ebuildId) throws EmergeException {
// read path to local ebuild repository from conf
String localRepository = Configuration.ebuildRepositoryDir;
EbuildFile ebuildFile = new EbuildFile();
ebuildFile.setPackageId(ebuildId);
String fileAsString = FileHelper.readFile(localRepository + FileHelper.getEbuildPath(ebuildId) + ".ebuild");
ebuildFile.setDescription(readVariable(fileAsString, EbuildKeyword.DESCRIPTION.name()).replace(EbuildKeyword.DESCRIPTION.name() + "=\"", "").replace(
"\"", ""));
ebuildFile.setHomepage(readVariable(fileAsString, EbuildKeyword.HOMEPAGE.name()).replace(EbuildKeyword.HOMEPAGE.name() + "=\"", "").replace("\"", ""));
ebuildFile.setLicense(readVariable(fileAsString, EbuildKeyword.LICENSE.name()).replace(EbuildKeyword.LICENSE.name() + "=\"", "").replace("\"", ""));
String keywordsValue = readVariable(fileAsString, EbuildKeyword.KEYWORDS.name()).replace(EbuildKeyword.KEYWORDS.name() + "=\"", "").replace("\"", "");
List<Keyword> processedKeywords = new ArrayList<Keyword>();
Arrays.asList(keywordsValue.split("( )+")).stream().forEach(x -> processedKeywords.add(new Keyword(x)));
ebuildFile.setKeywords(processedKeywords);
String iuseValue = readVariable(fileAsString, EbuildKeyword.IUSE.name()).replace(EbuildKeyword.IUSE.name() + "=\"", "").replace("\"", "");
List<Keyword> processedIuse = new ArrayList<Keyword>();
Arrays.asList(iuseValue.split("( )+")).stream().forEach(x -> processedIuse.add(new Keyword(x)));
ebuildFile.setIuse(processedIuse);
// TODO: REQUIRED_USE
String srcUri = readVariable(fileAsString, EbuildKeyword.SRC_URI.name()).replace(EbuildKeyword.SRC_URI.name() + "=\"", "").replace("\"", "");
srcUri = srcUri.replaceAll("^\\s+|\\s+$", "");
if (!srcUri.contains(" ")) {
// link
ebuildFile.getSrcUriList().add(new KeywordGroup(Collections.emptyList(), srcUri));
} else {
// x86 : link
// amd64 : link2
for (String srcUriItem : readSrcUri(srcUri)) {
String useString = srcUriItem.split("\\?")[0].replace("\t", "");
List<String> useList = Arrays.asList(useString.split("( )+"));
String uri = srcUriItem.substring(srcUriItem.split("\\?")[0].length() + 1).replaceAll("\\s+", "");
ebuildFile.getSrcUriList().add(new KeywordGroup(useList, uri));
}
}
// optional
String registryName = readVariable(fileAsString, EbuildKeyword.REGISTRY_NAME.name());
if (registryName != null) {
ebuildFile.setRegistryName(registryName.replace(EbuildKeyword.REGISTRY_NAME.name() + "=\"", "").replace("\"", ""));
}
return ebuildFile;
}
private String readVariable(String fileAsString, String variable) {
Pattern p = Pattern.compile("((" + variable + "){1})((=\"){1})(.|\\s)+?([\"]{1})");
return FileHelper.findByPattern(fileAsString, p);
}
private List<String> readSrcUri(String srcUriValue) {
Pattern p = Pattern.compile("((.)+)(\\s+)(\\?{1})(\\s+)(\\S+)");
return FileHelper.findAllByPattern(srcUriValue, p);
}
}
| UTF-8 | Java | 3,466 | java | EbuildReader.java | Java | [] | null | [] | package emerge.ebuild;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
import emerge.conf.Configuration;
import emerge.entity.Keyword;
import emerge.entity.KeywordGroup;
import emerge.misc.EmergeException;
import emerge.misc.FileHelper;
public class EbuildReader {
public EbuildReader() {
}
/**
* ebuildId can be /app-arch/p7zip-2.5.0-r2.ebuild
* @param ebuildId
*/
public EbuildFile read(String ebuildId) throws EmergeException {
// read path to local ebuild repository from conf
String localRepository = Configuration.ebuildRepositoryDir;
EbuildFile ebuildFile = new EbuildFile();
ebuildFile.setPackageId(ebuildId);
String fileAsString = FileHelper.readFile(localRepository + FileHelper.getEbuildPath(ebuildId) + ".ebuild");
ebuildFile.setDescription(readVariable(fileAsString, EbuildKeyword.DESCRIPTION.name()).replace(EbuildKeyword.DESCRIPTION.name() + "=\"", "").replace(
"\"", ""));
ebuildFile.setHomepage(readVariable(fileAsString, EbuildKeyword.HOMEPAGE.name()).replace(EbuildKeyword.HOMEPAGE.name() + "=\"", "").replace("\"", ""));
ebuildFile.setLicense(readVariable(fileAsString, EbuildKeyword.LICENSE.name()).replace(EbuildKeyword.LICENSE.name() + "=\"", "").replace("\"", ""));
String keywordsValue = readVariable(fileAsString, EbuildKeyword.KEYWORDS.name()).replace(EbuildKeyword.KEYWORDS.name() + "=\"", "").replace("\"", "");
List<Keyword> processedKeywords = new ArrayList<Keyword>();
Arrays.asList(keywordsValue.split("( )+")).stream().forEach(x -> processedKeywords.add(new Keyword(x)));
ebuildFile.setKeywords(processedKeywords);
String iuseValue = readVariable(fileAsString, EbuildKeyword.IUSE.name()).replace(EbuildKeyword.IUSE.name() + "=\"", "").replace("\"", "");
List<Keyword> processedIuse = new ArrayList<Keyword>();
Arrays.asList(iuseValue.split("( )+")).stream().forEach(x -> processedIuse.add(new Keyword(x)));
ebuildFile.setIuse(processedIuse);
// TODO: REQUIRED_USE
String srcUri = readVariable(fileAsString, EbuildKeyword.SRC_URI.name()).replace(EbuildKeyword.SRC_URI.name() + "=\"", "").replace("\"", "");
srcUri = srcUri.replaceAll("^\\s+|\\s+$", "");
if (!srcUri.contains(" ")) {
// link
ebuildFile.getSrcUriList().add(new KeywordGroup(Collections.emptyList(), srcUri));
} else {
// x86 : link
// amd64 : link2
for (String srcUriItem : readSrcUri(srcUri)) {
String useString = srcUriItem.split("\\?")[0].replace("\t", "");
List<String> useList = Arrays.asList(useString.split("( )+"));
String uri = srcUriItem.substring(srcUriItem.split("\\?")[0].length() + 1).replaceAll("\\s+", "");
ebuildFile.getSrcUriList().add(new KeywordGroup(useList, uri));
}
}
// optional
String registryName = readVariable(fileAsString, EbuildKeyword.REGISTRY_NAME.name());
if (registryName != null) {
ebuildFile.setRegistryName(registryName.replace(EbuildKeyword.REGISTRY_NAME.name() + "=\"", "").replace("\"", ""));
}
return ebuildFile;
}
private String readVariable(String fileAsString, String variable) {
Pattern p = Pattern.compile("((" + variable + "){1})((=\"){1})(.|\\s)+?([\"]{1})");
return FileHelper.findByPattern(fileAsString, p);
}
private List<String> readSrcUri(String srcUriValue) {
Pattern p = Pattern.compile("((.)+)(\\s+)(\\?{1})(\\s+)(\\S+)");
return FileHelper.findAllByPattern(srcUriValue, p);
}
}
| 3,466 | 0.694749 | 0.689844 | 84 | 40.261906 | 42.194313 | 152 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.416667 | false | false | 8 |
694163a3e3077d2d1f996c0199c43009b1784f79 | 24,094,766,566,109 | 7e1511cdceeec0c0aad2b9b916431fc39bc71d9b | /flakiness-predicter/input_data/original_tests/apache-incubator-dubbo/nonFlakyMethods/org.apache.dubbo.remoting.zookeeper.zkclient.ZkclientZookeeperClientTest-testGetChildren.java | 6e505b2d84c300f48256302d6a668f3181c5e197 | [
"BSD-3-Clause"
] | permissive | Taher-Ghaleb/FlakeFlagger | https://github.com/Taher-Ghaleb/FlakeFlagger | 6fd7c95d2710632fd093346ce787fd70923a1435 | 45f3d4bc5b790a80daeb4d28ec84f5e46433e060 | refs/heads/main | 2023-07-14T16:57:24.507000 | 2021-08-26T14:50:16 | 2021-08-26T14:50:16 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | @Test public void testGetChildren() throws IOException {
String path="/dubbo/org.apache.dubbo.demo.DemoService/parentProviders";
zkclientZookeeperClient.create(path,false);
for (int i=0; i < 5; i++) {
zkclientZookeeperClient.createEphemeral(path + "/server" + i);
}
List<String> zookeeperClientChildren=zkclientZookeeperClient.getChildren(path);
assertThat(zookeeperClientChildren,hasSize(5));
}
| UTF-8 | Java | 412 | java | org.apache.dubbo.remoting.zookeeper.zkclient.ZkclientZookeeperClientTest-testGetChildren.java | Java | [] | null | [] | @Test public void testGetChildren() throws IOException {
String path="/dubbo/org.apache.dubbo.demo.DemoService/parentProviders";
zkclientZookeeperClient.create(path,false);
for (int i=0; i < 5; i++) {
zkclientZookeeperClient.createEphemeral(path + "/server" + i);
}
List<String> zookeeperClientChildren=zkclientZookeeperClient.getChildren(path);
assertThat(zookeeperClientChildren,hasSize(5));
}
| 412 | 0.764563 | 0.757282 | 9 | 44.777779 | 27.107924 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 8 |
07cd918d732923675741a19363b6cf11bb89bfc2 | 10,247,792,001,330 | a98625b08432e2e3fd37d8bd6bb6cdf953017999 | /src/main/java/com/dw/service/PosPrinterService.java | 20347cde04d504cec9d55ac70051cb4b8fe4eec5 | [] | no_license | lodichang/Dwpos | https://github.com/lodichang/Dwpos | 62f5622de46e83f7bb4a5593d94ca672356ed87b | ddc6049cca73c265abc4e172a16bbfa0fddd84c9 | refs/heads/master | 2020-03-19T07:43:18.981000 | 2018-06-05T08:33:47 | 2018-06-05T08:33:47 | 136,143,385 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.dw.service;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dw.entity.PosPrinter;
import com.dw.mapper.PosPrinterMapper;
import org.springframework.stereotype.Service;
@Service
public class PosPrinterService extends ServiceImpl<PosPrinterMapper, PosPrinter> {
}
| UTF-8 | Java | 301 | java | PosPrinterService.java | Java | [] | null | [] | package com.dw.service;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dw.entity.PosPrinter;
import com.dw.mapper.PosPrinterMapper;
import org.springframework.stereotype.Service;
@Service
public class PosPrinterService extends ServiceImpl<PosPrinterMapper, PosPrinter> {
}
| 301 | 0.827243 | 0.827243 | 14 | 20.5 | 25.728666 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.428571 | false | false | 8 |
b6689f25895ff0ae6e23d6c0a93b3cc9b06c288a | 532,575,977,703 | ca482f8dccff7a91c6c0f2a6ed0428c9fc412c03 | /meiguo-manager/src/main/java/com/meiguo/chengjiumanager/dao/ChengjiuDao.java | 6d988bd298f93cb4fa46a32285f9290996920e93 | [] | no_license | tangminnan/dianziyan | https://github.com/tangminnan/dianziyan | 6a0a7ec508d77e0ea42952e431238ab903f0a3ba | 8b8078523e1ff8b9b2db831503d204569b0b144d | refs/heads/master | 2020-03-31T12:31:17.604000 | 2019-01-28T02:14:47 | 2019-01-28T02:14:47 | 152,219,256 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.meiguo.chengjiumanager.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import com.meiguo.chengjiumanager.domain.ChengjiuDO;
/**
* 成就列表
* @author wjl
* @email bushuo@163.com
* @date 2018-10-11 15:54:27
*/
@Mapper
public interface ChengjiuDao {
ChengjiuDO get(Integer chengjiuId);
List<ChengjiuDO> list(Map<String,Object> map);
int count(Map<String,Object> map);
int save(ChengjiuDO chengjiu);
int update(ChengjiuDO chengjiu);
int remove(Integer chengjiu_id);
int batchRemove(Integer[] chengjiuIds);
}
| UTF-8 | Java | 600 | java | ChengjiuDao.java | Java | [
{
"context": "manager.domain.ChengjiuDO;\n\n/**\n * 成就列表\n * @author wjl\n * @email bushuo@163.com\n * @date 2018-10-11 15:5",
"end": 215,
"score": 0.9996792674064636,
"start": 212,
"tag": "USERNAME",
"value": "wjl"
},
{
"context": ".ChengjiuDO;\n\n/**\n * 成就列表\n * @author wjl\n * @e... | null | [] | package com.meiguo.chengjiumanager.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import com.meiguo.chengjiumanager.domain.ChengjiuDO;
/**
* 成就列表
* @author wjl
* @email <EMAIL>
* @date 2018-10-11 15:54:27
*/
@Mapper
public interface ChengjiuDao {
ChengjiuDO get(Integer chengjiuId);
List<ChengjiuDO> list(Map<String,Object> map);
int count(Map<String,Object> map);
int save(ChengjiuDO chengjiu);
int update(ChengjiuDO chengjiu);
int remove(Integer chengjiu_id);
int batchRemove(Integer[] chengjiuIds);
}
| 593 | 0.734797 | 0.706081 | 35 | 15.914286 | 17.130377 | 52 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8 | false | false | 8 |
25773e4ea089875c373f395e6c391dba3526147c | 1,133,871,367,713 | 27dc541bf8ce73fda1b6a40ef471ae59304c0262 | /CoreBanking/src/test/java/testNGTesing/DesiredCapabilityDemo_TODO.java | db24b4f0e3845d81378991914ec7a39dbdbedf66 | [] | no_license | shesingh/SeleniumJavaFramework1 | https://github.com/shesingh/SeleniumJavaFramework1 | 8dda3b6e73d0b748ba99c813fd9beac0f79689f8 | fa6befe9556dadfd2bd8674baa1ef17a17897468 | refs/heads/master | 2020-04-25T11:36:51.617000 | 2019-03-29T18:44:00 | 2019-03-29T18:44:00 | 172,750,574 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* This class covers:
* To DO ...Do this from Automation Step by Step - Raghav Pal
*/
package testNGTesing;
public class DesiredCapabilityDemo_TODO {
}
| UTF-8 | Java | 170 | java | DesiredCapabilityDemo_TODO.java | Java | [
{
"context": " * To DO ...Do this from Automation Step by Step - Raghav Pal\r\n */\r\n\r\npackage testNGTesing;\r\n\r\npublic class Des",
"end": 88,
"score": 0.9996103644371033,
"start": 78,
"tag": "NAME",
"value": "Raghav Pal"
}
] | null | [] | /*
* This class covers:
* To DO ...Do this from Automation Step by Step - <NAME>
*/
package testNGTesing;
public class DesiredCapabilityDemo_TODO {
}
| 166 | 0.664706 | 0.664706 | 10 | 15 | 20.119642 | 61 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.1 | false | false | 8 |
6535c58f16a75138291a87a460bae57b096526b9 | 10,084,583,218,772 | 861f45a5341fcc31b2149d0422a966bd7a2dcf54 | /src/main/java/frc/robot/commands/defaultcommands/DefaultDriveCommand.java | ca8e6edf595c02fde21d081460c00df3a86439ff | [] | no_license | thomasjosif/FRC_2019_Robot | https://github.com/thomasjosif/FRC_2019_Robot | e6b697f57cbb3ad75bab1870d8232e726ba72f68 | 371e6d3fdac46cf8a651463ff6e5444ee8004c36 | refs/heads/master | 2020-05-09T23:02:56.469000 | 2019-03-28T14:41:24 | 2019-03-28T14:41:24 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package frc.robot.commands.defaultcommands;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import frc.robot.Robot;
import frc.robot.commands.autonomouscommands.RotateToHeadingCommand;
import frc.robot.constants.RobotConst;
import frc.robot.oi.OI;
import frc.robot.subsystems.CameraSubsystem;
import frc.robot.subsystems.DriveSubsystem;
public class DefaultDriveCommand extends Command {
private DriveSubsystem c_drive;
public DefaultDriveCommand() {
c_drive = Robot.getDriveSubsystem();
requires(c_drive);
}
@Override
protected void execute() {
double throttle = OI.getDriverThrottle();
double turn = OI.getDriverTurn();
double leftSpeed = 0;
double rightSpeed = 0;
if (Math.abs(throttle) < RobotConst.DRIVE_THORTTLE_TRIGGER_VALUE) {
throttle = 0;
}
if (Math.abs(turn) < RobotConst.DRIVE_TURN_TRIGGER_VALUE) {
turn = 0;
}
leftSpeed = throttle - turn;
rightSpeed = throttle + turn;
c_drive.setRawSpeeds(leftSpeed*0.7, -rightSpeed*0.7);
if(OI.getDriver().getPOV() != -1){
System.out.println("Starting rotate command");
Scheduler.getInstance().add(new RotateToHeadingCommand(OI.getDriver().getPOV()));
}
if(OI.getDriverRequestionHatchLED()){
CameraSubsystem camera = Robot.m_camera;
Scheduler.getInstance().add(new RotateToHeadingCommand(c_drive.getPigeonHeading() - camera.getDegreesOff()));
}
}
@Override
protected boolean isFinished() {
return false;
}
} | UTF-8 | Java | 1,682 | java | DefaultDriveCommand.java | Java | [] | null | [] | package frc.robot.commands.defaultcommands;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import frc.robot.Robot;
import frc.robot.commands.autonomouscommands.RotateToHeadingCommand;
import frc.robot.constants.RobotConst;
import frc.robot.oi.OI;
import frc.robot.subsystems.CameraSubsystem;
import frc.robot.subsystems.DriveSubsystem;
public class DefaultDriveCommand extends Command {
private DriveSubsystem c_drive;
public DefaultDriveCommand() {
c_drive = Robot.getDriveSubsystem();
requires(c_drive);
}
@Override
protected void execute() {
double throttle = OI.getDriverThrottle();
double turn = OI.getDriverTurn();
double leftSpeed = 0;
double rightSpeed = 0;
if (Math.abs(throttle) < RobotConst.DRIVE_THORTTLE_TRIGGER_VALUE) {
throttle = 0;
}
if (Math.abs(turn) < RobotConst.DRIVE_TURN_TRIGGER_VALUE) {
turn = 0;
}
leftSpeed = throttle - turn;
rightSpeed = throttle + turn;
c_drive.setRawSpeeds(leftSpeed*0.7, -rightSpeed*0.7);
if(OI.getDriver().getPOV() != -1){
System.out.println("Starting rotate command");
Scheduler.getInstance().add(new RotateToHeadingCommand(OI.getDriver().getPOV()));
}
if(OI.getDriverRequestionHatchLED()){
CameraSubsystem camera = Robot.m_camera;
Scheduler.getInstance().add(new RotateToHeadingCommand(c_drive.getPigeonHeading() - camera.getDegreesOff()));
}
}
@Override
protected boolean isFinished() {
return false;
}
} | 1,682 | 0.651605 | 0.646254 | 57 | 28.526316 | 25.857304 | 121 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.473684 | false | false | 8 |
59fee55c7bc3e3a05faae0a467ae25514a223653 | 6,914,897,351,471 | 5cfad68e8a71265822d98bb851badfb0bb9ffd50 | /src/annotations/Annotation.java | d75ab2f215e2c0a4e93459d93b06a4ec986edff6 | [] | no_license | 68889/JavaFundamention | https://github.com/68889/JavaFundamention | ec066f3bdf769a903a56fff0739e54ce069311a5 | b8bf40c91536710ccbc751667f4c4290fca9d58b | refs/heads/master | 2020-12-15T13:59:14.150000 | 2020-01-23T08:18:54 | 2020-01-23T08:18:54 | 235,122,877 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
public class Annotation implements FunctionalInterface_ {
int a = 1;
int b = 3;
String result = "3";
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("a=" + a).append("\n");
sb.append("b=" + b).append("\n");
sb.append("result=" + result).append("\n");
return sb.toString();
}
// Javadoc comment
/**
* @deprecated
* explanation of why it
* was deprecated
*/
@Deprecated
public static void deprecatedMethod() {
System.out.println("deprecatedMethod()");
}
@SuppressWarnings("unused")
public static void suppressWarning() {
String s;
}
@SafeVarargs
static <T> void safeVarages(T... args) {
for (T arg: args) {
System.out.println(arg);
}
}
@Override
public void abstractMethod() {
}
static class RetentionFoo implements Foo {
@Override
public Class<? extends java.lang.annotation.Annotation> annotationType() {
return null;
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Foo {}
@Foo
public static void fooMethod() {
}
}
| UTF-8 | Java | 1,505 | java | Annotation.java | Java | [] | null | [] | package annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
public class Annotation implements FunctionalInterface_ {
int a = 1;
int b = 3;
String result = "3";
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("a=" + a).append("\n");
sb.append("b=" + b).append("\n");
sb.append("result=" + result).append("\n");
return sb.toString();
}
// Javadoc comment
/**
* @deprecated
* explanation of why it
* was deprecated
*/
@Deprecated
public static void deprecatedMethod() {
System.out.println("deprecatedMethod()");
}
@SuppressWarnings("unused")
public static void suppressWarning() {
String s;
}
@SafeVarargs
static <T> void safeVarages(T... args) {
for (T arg: args) {
System.out.println(arg);
}
}
@Override
public void abstractMethod() {
}
static class RetentionFoo implements Foo {
@Override
public Class<? extends java.lang.annotation.Annotation> annotationType() {
return null;
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Foo {}
@Foo
public static void fooMethod() {
}
}
| 1,505 | 0.57608 | 0.574086 | 66 | 20.80303 | 18.328831 | 82 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.257576 | false | false | 8 |
b906b2c40dbc4af5feb6d27450891f54be36426c | 12,730,283,077,311 | a159752f6f74716bec9a676be8d1c1c42033839b | /outboundsvr/src/main/java/com/garyzhangscm/cwms/outbound/model/PickType.java | c1a298da7a3036250e952f4ad32f36fab5e6c464 | [] | no_license | garyzhangscm/cwms | https://github.com/garyzhangscm/cwms | bdf71fd145e5f8a95cdad3520c1196b32649dd8a | 73b053bce2b86d42e16255d5fb4fe5f8f99d4665 | refs/heads/master | 2023-08-05T02:52:46.243000 | 2023-08-01T04:47:29 | 2023-08-01T04:47:29 | 199,084,976 | 1 | 0 | null | false | 2023-08-01T04:33:45 | 2019-07-26T22:01:04 | 2023-07-31T21:17:29 | 2023-08-01T04:33:43 | 77,965 | 1 | 0 | 0 | Java | false | false | package com.garyzhangscm.cwms.outbound.model;
public enum PickType {
OUTBOUND,
EMERGENCY_REPLENISHMENT,
TRIGGER_REPLENISHMENT,
WORK_ORDER
}
| UTF-8 | Java | 157 | java | PickType.java | Java | [] | null | [] | package com.garyzhangscm.cwms.outbound.model;
public enum PickType {
OUTBOUND,
EMERGENCY_REPLENISHMENT,
TRIGGER_REPLENISHMENT,
WORK_ORDER
}
| 157 | 0.738854 | 0.738854 | 8 | 18.625 | 13.96368 | 45 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 8 |
8bb91d272a22fd6e75f553190216f482eea9f887 | 16,432,544,886,196 | 31c6bd3fcd2f6f7d1adbf90485e9f60eb58b7413 | /app/src/main/java/com/maxmobile/workstatus/ReceiversAndServices/UpdateStatusReceiver.java | cfaead42e069f60060236318fd5e7e7fd3c8f059 | [] | no_license | MaxVitruk/WorkStatusAndroid | https://github.com/MaxVitruk/WorkStatusAndroid | c06e716266b4c65bfa1e0afbc74d07b9d6dc7453 | 961b82ded43e112d8845f37ec7573929ecb91953 | refs/heads/master | 2016-09-10T19:25:04.419000 | 2015-05-28T15:08:17 | 2015-05-28T15:08:17 | 34,669,295 | 3 | 0 | null | false | 2015-05-28T15:08:18 | 2015-04-27T13:47:46 | 2015-05-07T13:30:41 | 2015-05-28T15:08:17 | 3,440 | 1 | 0 | 0 | Java | null | null | package com.maxmobile.workstatus.ReceiversAndServices;
import android.app.AlarmManager;
import android.app.KeyguardManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.Vibrator;
import android.util.Log;
import android.widget.Toast;
import com.maxmobile.workstatus.ChangeStatusActivity;
import com.maxmobile.workstatus.HelperClasses.AppState;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class UpdateStatusReceiver extends BroadcastReceiver {
final public static String ONE_TIME = "onetime";
final public static String TAG = "Alarm Manager ";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() != null) {
if (intent.getAction().equals("TimeForAlarm")) {
setAlarm(AppState.getMyContext(), intent.getIntExtra("hour", 9), intent.getIntExtra("minute", 0));
} else if ( intent.getAction().equals("CancelAlarm")) {
{
cancelAlarm(context);
}
}
}else {
KeyguardManager km = (KeyguardManager) AppState.getMyContext().getSystemService(Context.KEYGUARD_SERVICE);
final KeyguardManager.KeyguardLock kl = km.newKeyguardLock("MyKeyguardLock");
kl.disableKeyguard();
PowerManager pm = (PowerManager) AppState.getMyContext().
getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP
| PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
wakeLock.acquire();
Vibrator v = (Vibrator) AppState.getMyContext().getSystemService(Context.VIBRATOR_SERVICE);
// Start without a delay
// Vibrate for 100 milliseconds
// Sleep for 50 milliseconds
long[] pattern = {0, 500, 100, 500, 100};
//-1 - vibrate 1 time
v.vibrate(pattern, -1);
// Здесь можно делать обработку.
Bundle extras = intent.getExtras();
StringBuilder msgStr = new StringBuilder();
if (extras != null && extras.getBoolean(ONE_TIME, Boolean.FALSE)) {
// проверяем параметр ONE_TIME, если это одиночный будильник,
// выводим соответствующее сообщение.
msgStr.append("Одноразовый будильник: ");
} else {
msgStr.append("Будильник: ");
}
Format formatter = new SimpleDateFormat("hh:mm:ss a");
msgStr.append(formatter.format(new Date()));
Toast.makeText(context, msgStr, Toast.LENGTH_LONG).show();
Log.i(TAG, msgStr.toString());
// Разблокируем поток.
wakeLock.release();
intent = new Intent(context, ChangeStatusActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
public void setAlarm(Context context, int hour, int minute) {
cancelAlarm(context);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, UpdateStatusReceiver.class);
intent.putExtra(ONE_TIME, Boolean.FALSE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
Calendar cal = Calendar.getInstance();
if(hour<cal.HOUR_OF_DAY){
cal.set(Calendar.DAY_OF_WEEK,Calendar.DAY_OF_WEEK + 1);
}
cal.set(Calendar.HOUR_OF_DAY,hour);
cal.set(Calendar.MINUTE,minute);
cal.set(Calendar.SECOND, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000 * 60 * 2, pi);// Millisec * Second * Minute
Log.i(TAG, cal.toString());
}
public void cancelAlarm(Context context) {
Intent intent = new Intent(context, UpdateStatusReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender); //cancel alarm
Log.i(TAG, "canceled !");
}
public void setOnetimeTimer(Context context) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, UpdateStatusReceiver.class);
intent.putExtra(ONE_TIME, Boolean.TRUE); // Задаем параметр интента
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pi);
}
}
| UTF-8 | Java | 5,113 | java | UpdateStatusReceiver.java | Java | [] | null | [] | package com.maxmobile.workstatus.ReceiversAndServices;
import android.app.AlarmManager;
import android.app.KeyguardManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.Vibrator;
import android.util.Log;
import android.widget.Toast;
import com.maxmobile.workstatus.ChangeStatusActivity;
import com.maxmobile.workstatus.HelperClasses.AppState;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class UpdateStatusReceiver extends BroadcastReceiver {
final public static String ONE_TIME = "onetime";
final public static String TAG = "Alarm Manager ";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() != null) {
if (intent.getAction().equals("TimeForAlarm")) {
setAlarm(AppState.getMyContext(), intent.getIntExtra("hour", 9), intent.getIntExtra("minute", 0));
} else if ( intent.getAction().equals("CancelAlarm")) {
{
cancelAlarm(context);
}
}
}else {
KeyguardManager km = (KeyguardManager) AppState.getMyContext().getSystemService(Context.KEYGUARD_SERVICE);
final KeyguardManager.KeyguardLock kl = km.newKeyguardLock("MyKeyguardLock");
kl.disableKeyguard();
PowerManager pm = (PowerManager) AppState.getMyContext().
getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP
| PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
wakeLock.acquire();
Vibrator v = (Vibrator) AppState.getMyContext().getSystemService(Context.VIBRATOR_SERVICE);
// Start without a delay
// Vibrate for 100 milliseconds
// Sleep for 50 milliseconds
long[] pattern = {0, 500, 100, 500, 100};
//-1 - vibrate 1 time
v.vibrate(pattern, -1);
// Здесь можно делать обработку.
Bundle extras = intent.getExtras();
StringBuilder msgStr = new StringBuilder();
if (extras != null && extras.getBoolean(ONE_TIME, Boolean.FALSE)) {
// проверяем параметр ONE_TIME, если это одиночный будильник,
// выводим соответствующее сообщение.
msgStr.append("Одноразовый будильник: ");
} else {
msgStr.append("Будильник: ");
}
Format formatter = new SimpleDateFormat("hh:mm:ss a");
msgStr.append(formatter.format(new Date()));
Toast.makeText(context, msgStr, Toast.LENGTH_LONG).show();
Log.i(TAG, msgStr.toString());
// Разблокируем поток.
wakeLock.release();
intent = new Intent(context, ChangeStatusActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
public void setAlarm(Context context, int hour, int minute) {
cancelAlarm(context);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, UpdateStatusReceiver.class);
intent.putExtra(ONE_TIME, Boolean.FALSE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
Calendar cal = Calendar.getInstance();
if(hour<cal.HOUR_OF_DAY){
cal.set(Calendar.DAY_OF_WEEK,Calendar.DAY_OF_WEEK + 1);
}
cal.set(Calendar.HOUR_OF_DAY,hour);
cal.set(Calendar.MINUTE,minute);
cal.set(Calendar.SECOND, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000 * 60 * 2, pi);// Millisec * Second * Minute
Log.i(TAG, cal.toString());
}
public void cancelAlarm(Context context) {
Intent intent = new Intent(context, UpdateStatusReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender); //cancel alarm
Log.i(TAG, "canceled !");
}
public void setOnetimeTimer(Context context) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, UpdateStatusReceiver.class);
intent.putExtra(ONE_TIME, Boolean.TRUE); // Задаем параметр интента
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pi);
}
}
| 5,113 | 0.64329 | 0.63561 | 162 | 29.543209 | 30.958176 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.691358 | false | false | 8 |
8940f74ebc38e52a7d6cef218c209b9bedcdef38 | 7,816,840,481,137 | e28b9e6477879f338b9861bfdafbf89702ea65b5 | /spring-annotation/src/test/java/com/willow/annotation/AppTest.java | cd3822b6ae59c3e26ca0d86390bdb38dc630b6d9 | [] | no_license | yangliuwilow/myProjectCode | https://github.com/yangliuwilow/myProjectCode | ef8bbbd2e11630cdfa58c705dba826cd225406d7 | db216cc3764a4ca822ccc38c14c57cb97e23aff5 | refs/heads/master | 2020-03-24T07:04:17.806000 | 2018-07-30T10:00:02 | 2018-07-30T10:00:02 | 142,551,565 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.willow.annotation;
import com.willow.bean.Person;
import com.willow.config.SpringConfig;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class AppTest {
/**
* 注解的方式
*/
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
@Test
public void test03() {
/**
* 获取容器中所有的bean
*/
String[] beanDefinitionNames = annotationConfigApplicationContext.getBeanDefinitionNames();
for (String beanName : beanDefinitionNames) {
System.out.println("########beanDefinitionNames_Annotation_bean_name:" + beanName);
}
Person person = annotationConfigApplicationContext.getBean(Person.class);
Person person01 = annotationConfigApplicationContext.getBean(Person.class);
System.out.println("判断bean相等:"+ person == person01 +""); // @Scope("prototype") 不相等 ,单例:singleton 时候相等
annotationConfigApplicationContext.close();
}
}
| UTF-8 | Java | 1,142 | java | AppTest.java | Java | [] | null | [] | package com.willow.annotation;
import com.willow.bean.Person;
import com.willow.config.SpringConfig;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class AppTest {
/**
* 注解的方式
*/
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
@Test
public void test03() {
/**
* 获取容器中所有的bean
*/
String[] beanDefinitionNames = annotationConfigApplicationContext.getBeanDefinitionNames();
for (String beanName : beanDefinitionNames) {
System.out.println("########beanDefinitionNames_Annotation_bean_name:" + beanName);
}
Person person = annotationConfigApplicationContext.getBean(Person.class);
Person person01 = annotationConfigApplicationContext.getBean(Person.class);
System.out.println("判断bean相等:"+ person == person01 +""); // @Scope("prototype") 不相等 ,单例:singleton 时候相等
annotationConfigApplicationContext.close();
}
}
| 1,142 | 0.709945 | 0.70442 | 32 | 32.9375 | 38.142773 | 135 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.375 | false | false | 8 |
fe998ea413f3e2974dcd50f5ac6fc755b5a17a8b | 17,617,955,865,078 | 4c8c7826d959ff39243a8bb22dc2786957da13b5 | /src/net/highwayfrogs/editor/file/patch/commands/PatchCommandMultiply.java | 943c5ad0522bc913fee80dedacb716a56085dfb0 | [] | no_license | Kneesnap/FrogLord | https://github.com/Kneesnap/FrogLord | ebdf274ab407ced35637a63c4c01d672655aa24e | dae15901bd46113a61f171dff3f8d0893f6517ec | refs/heads/master | 2023-05-24T11:52:35.668000 | 2023-05-22T00:27:50 | 2023-05-22T00:27:50 | 144,334,705 | 118 | 9 | null | false | 2023-05-15T05:50:15 | 2018-08-10T21:43:06 | 2023-05-11T21:31:41 | 2023-05-15T05:50:14 | 11,889 | 100 | 6 | 6 | Java | false | false | package net.highwayfrogs.editor.file.patch.commands;
import net.highwayfrogs.editor.file.patch.PatchRuntime;
import net.highwayfrogs.editor.file.patch.PatchValue;
import net.highwayfrogs.editor.file.patch.reference.PatchValueReference;
import java.util.List;
/**
* Multiply a variable.
* multiply <targetVar> <valueToMultiplyBy>
* Created by Kneesnap on 1/15/2020.
*/
public class PatchCommandMultiply extends PatchCommand {
public PatchCommandMultiply() {
super("multiply");
}
@Override
public void execute(PatchRuntime runtime, List<PatchValueReference> args) {
PatchValue value = runtime.getVariable(getValueText(args, 0));
PatchValue otherValue = getValue(runtime, args, 1);
if (value.isDecimal() || otherValue.isDecimal()) {
value.setDecimal((value.isDecimal() ? value.getAsDecimal() : value.getAsInteger()) * (otherValue.isDecimal() ? otherValue.getAsDecimal() : otherValue.getAsInteger()));
} else if (value.isInteger() && otherValue.isInteger()) {
value.setInteger(value.getAsInteger() * otherValue.getAsInteger());
} else {
throw new RuntimeException("Cannot multiply '" + value + "' by '" + otherValue + "'.");
}
}
}
| UTF-8 | Java | 1,248 | java | PatchCommandMultiply.java | Java | [
{
"context": "iply <targetVar> <valueToMultiplyBy>\n * Created by Kneesnap on 1/15/2020.\n */\npublic class PatchCommandMultip",
"end": 356,
"score": 0.9996297955513,
"start": 348,
"tag": "USERNAME",
"value": "Kneesnap"
}
] | null | [] | package net.highwayfrogs.editor.file.patch.commands;
import net.highwayfrogs.editor.file.patch.PatchRuntime;
import net.highwayfrogs.editor.file.patch.PatchValue;
import net.highwayfrogs.editor.file.patch.reference.PatchValueReference;
import java.util.List;
/**
* Multiply a variable.
* multiply <targetVar> <valueToMultiplyBy>
* Created by Kneesnap on 1/15/2020.
*/
public class PatchCommandMultiply extends PatchCommand {
public PatchCommandMultiply() {
super("multiply");
}
@Override
public void execute(PatchRuntime runtime, List<PatchValueReference> args) {
PatchValue value = runtime.getVariable(getValueText(args, 0));
PatchValue otherValue = getValue(runtime, args, 1);
if (value.isDecimal() || otherValue.isDecimal()) {
value.setDecimal((value.isDecimal() ? value.getAsDecimal() : value.getAsInteger()) * (otherValue.isDecimal() ? otherValue.getAsDecimal() : otherValue.getAsInteger()));
} else if (value.isInteger() && otherValue.isInteger()) {
value.setInteger(value.getAsInteger() * otherValue.getAsInteger());
} else {
throw new RuntimeException("Cannot multiply '" + value + "' by '" + otherValue + "'.");
}
}
}
| 1,248 | 0.689904 | 0.682692 | 32 | 38 | 38.559208 | 179 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.53125 | false | false | 8 |
3b98e25022614512fa83371120953001000d17b9 | 21,449,066,697,148 | d49d3d18097fb3a6fc4577a2aee6d942d767e55b | /android/src/nl/tomsanders/wakeupservice/StatusCheckReceiver.java | 10b9f0834a7840607c541e00311abe7c0e9d6b3d | [] | no_license | mnstrspeed/remotewakeupservice | https://github.com/mnstrspeed/remotewakeupservice | 887c9c85c4772333c49930c82e7ff383b13209b5 | 60584e88406c3c9bd7f76286a8bb6ba2c5bcbb37 | refs/heads/master | 2016-09-05T19:50:06.548000 | 2014-02-12T16:40:48 | 2014-02-12T16:40:48 | 16,771,061 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package nl.tomsanders.wakeupservice;
import java.io.IOException;
import java.net.URL;
import java.util.Calendar;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.AlarmClock;
import android.util.DisplayMetrics;
import android.util.Log;
public class StatusCheckReceiver extends BroadcastReceiver
{
@Override
public void onReceive(final Context context, Intent intent)
{
Log.d("nl.tomsanders.wakeupservice", "hello there");
final boolean stop = intent.getBooleanExtra("stop", false);
final long startTime = intent.getLongExtra("startTime", 0L);
if (stop)
{
Log.d("nl.tomsanders.wakeupservice", "aye cap, sinking ship");
stopRepeating(context);
cancelNotification(context);
}
else
{
new Thread(new Runnable() {
@Override
public void run()
{
checkStatus(context, startTime);
}
}).start();
}
}
private void cancelNotification(Context context)
{
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(0);
}
private void checkStatus(Context context, long startTime)
{
String url = "http://188.226.148.202/status.php?since=" + startTime;
try
{
String output = getPageContent(url);
Log.d("nl.tomsanders.wakeupservice", "Status: " + output);
String ip = "";
String useragent = "";
boolean activated = !output.equals("0");
if (activated)
{
String[] fields = output.split("\t");
ip = fields[1];
useragent = fields[2];
setAlarm(context, 1);
setAlarm(context, 6);
stopRepeating(context);
}
showNotification(context, activated, ip, useragent);
}
catch (Exception e)
{
Log.e("nl.tomsanders.wakeupservice", "woops?");
e.printStackTrace();
}
}
private String getPageContent(String url) throws IOException,
ClientProtocolException
{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
return EntityUtils.toString(response.getEntity());
}
private void setAlarm(Context context, int minutesFromNow)
{
Calendar now = Calendar.getInstance();
now.add(Calendar.MINUTE, minutesFromNow);
Intent alarmIntent = new Intent(AlarmClock.ACTION_SET_ALARM);
alarmIntent.putExtra(AlarmClock.EXTRA_MESSAGE, "Your Wake-Up Service");
alarmIntent.putExtra(AlarmClock.EXTRA_HOUR, now.get(Calendar.HOUR_OF_DAY));
alarmIntent.putExtra(AlarmClock.EXTRA_MINUTES, now.get(Calendar.MINUTE));
alarmIntent.putExtra(AlarmClock.EXTRA_SKIP_UI, true);
alarmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
context.startActivity(alarmIntent);
Log.d("nl.tomsanders.wakeupservice", "Setting alarm for " + now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE));
}
private void stopRepeating(Context context)
{
Intent intent = new Intent(context, StatusCheckReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
private void showNotification(Context context, boolean activated, String ip, String useragent)
{
String status = activated ? "Activity detected" : "Nothing yet";
// Stop intent
Intent intent = new Intent("ACTION_STOP",
Uri.parse("wakeupservice:" + System.currentTimeMillis()));
intent.setClass(context, StatusCheckReceiver.class);
intent.putExtra("stop", true);
PendingIntent stopIntent = PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder notificationBase = new Notification.Builder(context)
.setContentTitle("Wake-Up Service")
.setContentText(status)
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(stopIntent);
Notification notification;
if (activated)
{
Bitmap mapImage = getMapImage(context, ip);
notification = new Notification.BigPictureStyle(notificationBase)
.setSummaryText("Used from " + getBrowserPlatform(useragent))
.bigPicture(mapImage).build();
}
else
{
notification = notificationBase.build();
}
notification.flags |= Notification.FLAG_NO_CLEAR;
notificationManager.notify(0, notification);
}
private String getBrowserPlatform(String ua)
{
ua = ua.toLowerCase();
String platform = "unknown platform";
String browser = "unknown browser";
if (ua.contains("windows")) {
platform = "Windows";
} else if (ua.contains("linux")) {
platform = "Linux";
} else if (ua.contains("android")) {
if (ua.contains("mobile")) {
platform = "Android (phone)";
} else {
platform = "Android (tablet)";
}
} else if (ua.contains("iphone")) {
platform = "Apple iPhone";
} else if (ua.contains("ipad")) {
platform = "Apple iPad";
} else if (ua.contains("apple")) {
platform = "Mac OS X";
}
if (ua.contains("chrome")) {
browser = "Chrome";
} else if (ua.contains("msie")) {
browser = "Internet Explorer";
} else if (ua.contains("firefox")) {
browser = "Firefox";
} else if (ua.contains("apple")) {
browser = "Safari";
}
return browser + " on " + platform;
}
private Bitmap getMapImage(Context context, String ip)
{
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
int imageHeight = Math.round(256 * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
int imageWidth = displayMetrics.widthPixels;
try
{
String location = getPageContent("http://188.226.148.202/iplookup.php?ip=" + ip);
Log.d("nl.tomsanders.wakeupservice", "showing " + location);
URL mapURL = new URL("http://maps.google.com/maps/api/staticmap?markers=" +
location + "&zoom=6&size=" + imageWidth + "x" + imageHeight + "&sensor=false");
return BitmapFactory.decodeStream(mapURL.openConnection().getInputStream());
}
catch (Exception e)
{
Log.e("nl.tomsanders.wakeupservice", "couldn't load map image");
e.printStackTrace();
// Return empty bitmap
return Bitmap.createBitmap(displayMetrics, imageWidth, imageHeight, null);
}
}
}
| UTF-8 | Java | 6,921 | java | StatusCheckReceiver.java | Java | [
{
"context": "ontext, long startTime)\n\t{\n\t\tString url = \"http://188.226.148.202/status.php?since=\" + startTime;\n\t\ttry\n\t\t{\n\t\t\tStri",
"end": 1720,
"score": 0.9994948506355286,
"start": 1705,
"tag": "IP_ADDRESS",
"value": "188.226.148.202"
},
{
"context": "\t\tString lo... | null | [] | package nl.tomsanders.wakeupservice;
import java.io.IOException;
import java.net.URL;
import java.util.Calendar;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.AlarmClock;
import android.util.DisplayMetrics;
import android.util.Log;
public class StatusCheckReceiver extends BroadcastReceiver
{
@Override
public void onReceive(final Context context, Intent intent)
{
Log.d("nl.tomsanders.wakeupservice", "hello there");
final boolean stop = intent.getBooleanExtra("stop", false);
final long startTime = intent.getLongExtra("startTime", 0L);
if (stop)
{
Log.d("nl.tomsanders.wakeupservice", "aye cap, sinking ship");
stopRepeating(context);
cancelNotification(context);
}
else
{
new Thread(new Runnable() {
@Override
public void run()
{
checkStatus(context, startTime);
}
}).start();
}
}
private void cancelNotification(Context context)
{
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(0);
}
private void checkStatus(Context context, long startTime)
{
String url = "http://192.168.127.12/status.php?since=" + startTime;
try
{
String output = getPageContent(url);
Log.d("nl.tomsanders.wakeupservice", "Status: " + output);
String ip = "";
String useragent = "";
boolean activated = !output.equals("0");
if (activated)
{
String[] fields = output.split("\t");
ip = fields[1];
useragent = fields[2];
setAlarm(context, 1);
setAlarm(context, 6);
stopRepeating(context);
}
showNotification(context, activated, ip, useragent);
}
catch (Exception e)
{
Log.e("nl.tomsanders.wakeupservice", "woops?");
e.printStackTrace();
}
}
private String getPageContent(String url) throws IOException,
ClientProtocolException
{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
return EntityUtils.toString(response.getEntity());
}
private void setAlarm(Context context, int minutesFromNow)
{
Calendar now = Calendar.getInstance();
now.add(Calendar.MINUTE, minutesFromNow);
Intent alarmIntent = new Intent(AlarmClock.ACTION_SET_ALARM);
alarmIntent.putExtra(AlarmClock.EXTRA_MESSAGE, "Your Wake-Up Service");
alarmIntent.putExtra(AlarmClock.EXTRA_HOUR, now.get(Calendar.HOUR_OF_DAY));
alarmIntent.putExtra(AlarmClock.EXTRA_MINUTES, now.get(Calendar.MINUTE));
alarmIntent.putExtra(AlarmClock.EXTRA_SKIP_UI, true);
alarmIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
context.startActivity(alarmIntent);
Log.d("nl.tomsanders.wakeupservice", "Setting alarm for " + now.get(Calendar.HOUR_OF_DAY) + ":" + now.get(Calendar.MINUTE));
}
private void stopRepeating(Context context)
{
Intent intent = new Intent(context, StatusCheckReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
}
private void showNotification(Context context, boolean activated, String ip, String useragent)
{
String status = activated ? "Activity detected" : "Nothing yet";
// Stop intent
Intent intent = new Intent("ACTION_STOP",
Uri.parse("wakeupservice:" + System.currentTimeMillis()));
intent.setClass(context, StatusCheckReceiver.class);
intent.putExtra("stop", true);
PendingIntent stopIntent = PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder notificationBase = new Notification.Builder(context)
.setContentTitle("Wake-Up Service")
.setContentText(status)
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(stopIntent);
Notification notification;
if (activated)
{
Bitmap mapImage = getMapImage(context, ip);
notification = new Notification.BigPictureStyle(notificationBase)
.setSummaryText("Used from " + getBrowserPlatform(useragent))
.bigPicture(mapImage).build();
}
else
{
notification = notificationBase.build();
}
notification.flags |= Notification.FLAG_NO_CLEAR;
notificationManager.notify(0, notification);
}
private String getBrowserPlatform(String ua)
{
ua = ua.toLowerCase();
String platform = "unknown platform";
String browser = "unknown browser";
if (ua.contains("windows")) {
platform = "Windows";
} else if (ua.contains("linux")) {
platform = "Linux";
} else if (ua.contains("android")) {
if (ua.contains("mobile")) {
platform = "Android (phone)";
} else {
platform = "Android (tablet)";
}
} else if (ua.contains("iphone")) {
platform = "Apple iPhone";
} else if (ua.contains("ipad")) {
platform = "Apple iPad";
} else if (ua.contains("apple")) {
platform = "Mac OS X";
}
if (ua.contains("chrome")) {
browser = "Chrome";
} else if (ua.contains("msie")) {
browser = "Internet Explorer";
} else if (ua.contains("firefox")) {
browser = "Firefox";
} else if (ua.contains("apple")) {
browser = "Safari";
}
return browser + " on " + platform;
}
private Bitmap getMapImage(Context context, String ip)
{
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
int imageHeight = Math.round(256 * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
int imageWidth = displayMetrics.widthPixels;
try
{
String location = getPageContent("http://188.226.148.202/iplookup.php?ip=" + ip);
Log.d("nl.tomsanders.wakeupservice", "showing " + location);
URL mapURL = new URL("http://maps.google.com/maps/api/staticmap?markers=" +
location + "&zoom=6&size=" + imageWidth + "x" + imageHeight + "&sensor=false");
return BitmapFactory.decodeStream(mapURL.openConnection().getInputStream());
}
catch (Exception e)
{
Log.e("nl.tomsanders.wakeupservice", "couldn't load map image");
e.printStackTrace();
// Return empty bitmap
return Bitmap.createBitmap(displayMetrics, imageWidth, imageHeight, null);
}
}
}
| 6,920 | 0.716659 | 0.711169 | 228 | 29.355263 | 25.822287 | 126 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.600877 | false | false | 8 |
9c74bd512a6c5b18f0ca7049075e23acaa8f5885 | 20,435,454,429,955 | 5903bd43d88aaa8cb3f89597fa8aab911df8fb11 | /app/src/main/java/com/sophon/videostudy/decode/MyExtractor.java | 26cf38091ad7fff46298747b541ac81257235abf | [] | no_license | ruizhang81/videoStudy | https://github.com/ruizhang81/videoStudy | 012d4d7c435edd268b2498136f39392d487013bc | cdad2f6874ed3b17863c2a09e7dcdc9d7107548c | refs/heads/main | 2023-05-14T13:35:22.947000 | 2021-06-13T07:16:42 | 2021-06-13T07:16:42 | 376,200,768 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.sophon.videostudy.decode;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import java.io.IOException;
import java.nio.ByteBuffer;
public class MyExtractor {
MediaFormat audioFormat;
int audioTrackId;
int videoTrackId;
MediaFormat videoFormat;
MediaExtractor mediaExtractor;
long curSampleTime;
int curSampleFlags;
public MyExtractor(String path) {
try {
mediaExtractor = new MediaExtractor();
// 设置数据源
mediaExtractor.setDataSource(path);
} catch (IOException e) {
e.printStackTrace();
}
//拿到所有的轨道
int count = mediaExtractor.getTrackCount();
for (int i = 0; i < count; i++) {
//根据下标拿到 MediaFormat
MediaFormat format = mediaExtractor.getTrackFormat(i);
//拿到 mime 类型
String mime = format.getString(MediaFormat.KEY_MIME);
//拿到视频轨
if (mime.startsWith("video")) {
videoTrackId = i;
videoFormat = format;
} else if (mime.startsWith("audio")) {
//拿到音频轨
audioTrackId = i;
audioFormat = format;
}
}
}
public void release() {
mediaExtractor.release();
}
public void selectTrack(int trackId) {
mediaExtractor.selectTrack(trackId);
}
/**
* 读取一帧的数据
*
* @param buffer
* @return
*/
public int readBuffer(boolean isVideo,ByteBuffer buffer) {
//先清空数据
buffer.clear();
//选择要解析的轨道
mediaExtractor.selectTrack( isVideo ? videoTrackId : audioTrackId);
// mediaExtractor.selectTrack(videoTrackId);
//读取当前帧的数据
int buffercount = mediaExtractor.readSampleData(buffer, 0);
if (buffercount < 0) {
return -1;
}
//记录当前时间戳
curSampleTime = mediaExtractor.getSampleTime();
//记录当前帧的标志位
curSampleFlags = mediaExtractor.getSampleFlags();
//进入下一帧
mediaExtractor.advance();
return buffercount;
}
} | UTF-8 | Java | 2,290 | java | MyExtractor.java | Java | [] | null | [] | package com.sophon.videostudy.decode;
import android.media.MediaExtractor;
import android.media.MediaFormat;
import java.io.IOException;
import java.nio.ByteBuffer;
public class MyExtractor {
MediaFormat audioFormat;
int audioTrackId;
int videoTrackId;
MediaFormat videoFormat;
MediaExtractor mediaExtractor;
long curSampleTime;
int curSampleFlags;
public MyExtractor(String path) {
try {
mediaExtractor = new MediaExtractor();
// 设置数据源
mediaExtractor.setDataSource(path);
} catch (IOException e) {
e.printStackTrace();
}
//拿到所有的轨道
int count = mediaExtractor.getTrackCount();
for (int i = 0; i < count; i++) {
//根据下标拿到 MediaFormat
MediaFormat format = mediaExtractor.getTrackFormat(i);
//拿到 mime 类型
String mime = format.getString(MediaFormat.KEY_MIME);
//拿到视频轨
if (mime.startsWith("video")) {
videoTrackId = i;
videoFormat = format;
} else if (mime.startsWith("audio")) {
//拿到音频轨
audioTrackId = i;
audioFormat = format;
}
}
}
public void release() {
mediaExtractor.release();
}
public void selectTrack(int trackId) {
mediaExtractor.selectTrack(trackId);
}
/**
* 读取一帧的数据
*
* @param buffer
* @return
*/
public int readBuffer(boolean isVideo,ByteBuffer buffer) {
//先清空数据
buffer.clear();
//选择要解析的轨道
mediaExtractor.selectTrack( isVideo ? videoTrackId : audioTrackId);
// mediaExtractor.selectTrack(videoTrackId);
//读取当前帧的数据
int buffercount = mediaExtractor.readSampleData(buffer, 0);
if (buffercount < 0) {
return -1;
}
//记录当前时间戳
curSampleTime = mediaExtractor.getSampleTime();
//记录当前帧的标志位
curSampleFlags = mediaExtractor.getSampleFlags();
//进入下一帧
mediaExtractor.advance();
return buffercount;
}
} | 2,290 | 0.575188 | 0.573308 | 83 | 24.650602 | 18.709209 | 75 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.445783 | false | false | 8 |
7405f83ac3527f8499092046c18d2113413bf314 | 9,302,899,189,852 | bcf4a326d11e424537e396d5bc443457e5a4cfee | /px-checkout/src/main/java/com/mercadopago/android/px/internal/features/review_and_confirm/components/items/ReviewItem.java | 08cf79c99de262df683144b1b09d37edc42684a4 | [
"MIT"
] | permissive | mercadopago/px-android | https://github.com/mercadopago/px-android | a80e54596c235ae852bd7d0fb99354ef9104aed4 | b715075dd4cf865f30f6448f3c00d6e9033a1c21 | refs/heads/master | 2022-07-20T04:25:40.695000 | 2022-07-15T16:23:14 | 2022-07-15T16:23:14 | 49,529,486 | 115 | 99 | MIT | false | 2022-07-15T16:02:24 | 2016-01-12T21:18:39 | 2022-03-22T17:09:01 | 2022-07-15T16:02:24 | 59,390 | 94 | 76 | 42 | Java | false | false | package com.mercadopago.android.px.internal.features.review_and_confirm.components.items;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.mercadopago.android.px.internal.features.review_and_confirm.models.ItemModel;
import com.mercadopago.android.px.internal.util.TextUtil;
import com.mercadopago.android.px.internal.view.ActionDispatcher;
import com.mercadopago.android.px.internal.view.Component;
import com.mercadopago.android.px.internal.view.RendererFactory;
public class ReviewItem extends Component<ReviewItem.Props, Void> {
static {
RendererFactory.register(ReviewItem.class, ReviewItemRenderer.class);
}
public ReviewItem(@NonNull final Props props) {
super(props);
}
public ReviewItem(@NonNull final Props props, @NonNull final ActionDispatcher dispatcher) {
super(props, dispatcher);
}
public boolean hasItemImage() {
return TextUtil.isNotEmpty(props.itemModel.imageUrl);
}
public boolean hasIcon() {
return props.icon != null;
}
public static class Props {
final ItemModel itemModel;
@DrawableRes final
Integer icon;
final String quantityLabel;
final String unitPriceLabel;
public Props(final ItemModel itemModel,
@DrawableRes @Nullable final Integer icon,
final String quantityLabel,
final String unitPriceLabel) {
this.itemModel = itemModel;
this.icon = icon;
this.quantityLabel = quantityLabel;
this.unitPriceLabel = unitPriceLabel;
}
}
}
| UTF-8 | Java | 1,668 | java | ReviewItem.java | Java | [] | null | [] | package com.mercadopago.android.px.internal.features.review_and_confirm.components.items;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.mercadopago.android.px.internal.features.review_and_confirm.models.ItemModel;
import com.mercadopago.android.px.internal.util.TextUtil;
import com.mercadopago.android.px.internal.view.ActionDispatcher;
import com.mercadopago.android.px.internal.view.Component;
import com.mercadopago.android.px.internal.view.RendererFactory;
public class ReviewItem extends Component<ReviewItem.Props, Void> {
static {
RendererFactory.register(ReviewItem.class, ReviewItemRenderer.class);
}
public ReviewItem(@NonNull final Props props) {
super(props);
}
public ReviewItem(@NonNull final Props props, @NonNull final ActionDispatcher dispatcher) {
super(props, dispatcher);
}
public boolean hasItemImage() {
return TextUtil.isNotEmpty(props.itemModel.imageUrl);
}
public boolean hasIcon() {
return props.icon != null;
}
public static class Props {
final ItemModel itemModel;
@DrawableRes final
Integer icon;
final String quantityLabel;
final String unitPriceLabel;
public Props(final ItemModel itemModel,
@DrawableRes @Nullable final Integer icon,
final String quantityLabel,
final String unitPriceLabel) {
this.itemModel = itemModel;
this.icon = icon;
this.quantityLabel = quantityLabel;
this.unitPriceLabel = unitPriceLabel;
}
}
}
| 1,668 | 0.704436 | 0.704436 | 52 | 31.076923 | 26.497349 | 95 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.557692 | false | false | 8 |
fcd6b54d6a5f8aa10f1de04971ffcafb6bed7e9e | 28,424,093,602,289 | 64123fa90e93e595bd34eaad2cf6302cfcd41e8b | /src/main/java/com/km/service/ProcessModule/controller/ProcessController.java | 669bc9bdefdde050c77d26f976c6b1b81cf09ce7 | [] | no_license | zhouyimian/DataETLPlatform | https://github.com/zhouyimian/DataETLPlatform | f16abba2fcca6dac2f454ef8b18257872ed13240 | a69d692fba3b550f481aa99aeec0aae35cc2d79a | refs/heads/master | 2022-07-04T18:03:37.902000 | 2020-04-09T14:52:47 | 2020-04-09T14:52:47 | 213,187,340 | 2 | 0 | null | false | 2022-07-01T21:24:58 | 2019-10-06T14:53:16 | 2020-04-09T14:53:12 | 2022-07-01T21:24:58 | 326 | 0 | 0 | 6 | Java | false | false | package com.km.service.ProcessModule.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.km.data.common.util.Configuration;
import com.km.service.ConfigureModule.service.ConfigureService;
import com.km.service.ProcessModule.domain.Process;
import com.km.service.ProcessModule.dto.ProcessUseridDto;
import com.km.service.ProcessModule.service.ProcessService;
import com.km.service.UserModule.domain.User;
import com.km.service.common.exception.serviceException;
import com.km.utils.LoadConfigureUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
@RestController
public class ProcessController {
@Autowired
private ProcessService processService;
@Autowired
private ConfigureService configureService;
@RequestMapping(value = "/getAllProcess", method = RequestMethod.POST)
public Object getAllProcess(HttpServletRequest req) {
int pageSize = Integer.parseInt(req.getParameter("pageSize"));
int pageNumber = Integer.parseInt(req.getParameter("pageNumber"));
List<ProcessUseridDto> list = processService.getAllProcess(pageSize, pageNumber);
JSONArray processDesc = richProcess(list);
int totalSize = processService.getProcessCount();
int totalPages = totalSize / pageSize + (totalSize % pageSize == 0 ? 0 : 1);
JSONObject message = new JSONObject();
message.put("pageSize", pageSize);
message.put("pageNumber", pageNumber);
message.put("totalPages", totalPages);
message.put("processDesc", processDesc);
return JSONObject.toJSON(message);
}
@RequestMapping(value = "/getAllPlugins", method = RequestMethod.POST)
public Object getAllPlugins(HttpServletRequest req) {
Map<String, Configuration> reader = LoadConfigureUtil.getReaderPlugNameToConf();
Map<String, Configuration> writer = LoadConfigureUtil.getWriterPlugNameToConf();
Map<String, Configuration> etl = LoadConfigureUtil.getEtlPlugNameToConf();
JSONObject message = new JSONObject();
message.put("readerPlugins", parseMap(reader));
message.put("writerPlugins", parseMap(writer));
message.put("etlPlugins", parseMap(etl));
return JSONObject.toJSON(message);
}
@RequestMapping(value = "/getOneProcess", method = RequestMethod.POST)
public Object getOneProcessDesc(HttpServletRequest req) {
String processId = req.getParameter("processId");
Process process = processService.getProcessByProcessId(processId);
return JSONObject.toJSON(process);
}
@RequestMapping(value = "/addProcess", method = RequestMethod.POST)
public Object addProcess(HttpServletRequest req) {
String processName = req.getParameter("processName");
String content = req.getParameter("processContent");
String processContent = JSONObject.parseArray(content).toString();
User user = (User) req.getAttribute("user");
String userId = user.getUserId();
processService.addProcess(processName, processContent, userId);
JSONObject message = new JSONObject();
message.put("message", "创建流程成功");
return JSONObject.toJSON(message);
}
@RequestMapping(value = "/deleteProcess", method = RequestMethod.POST)
public Object deleteProcess(HttpServletRequest req) {
String processId = req.getParameter("processId");
processService.deleteProcess(processId);
JSONObject message = new JSONObject();
message.put("message", "删除流程成功");
return JSONObject.toJSON(message);
}
@RequestMapping(value = "/updateProcess", method = RequestMethod.POST)
public Object updateProcess(HttpServletRequest req) {
String processId = req.getParameter("processId");
String processName = req.getParameter("processName");
String content = req.getParameter("processContent");
String processContent = JSONObject.parseArray(content).toString();
processService.updateProcess(processId, processName, processContent);
JSONObject message = new JSONObject();
message.put("message", "更新流程成功");
return JSONObject.toJSON(message);
}
/**
* 导出流程
*
* @param req
* @return
*/
@RequestMapping(value = "/exportProcess", method = RequestMethod.POST)
public Object exportProcess(HttpServletRequest req) {
String ids = req.getParameter("processIds");
JSONArray processIds = JSONArray.parseArray(ids);
JSONArray processJSONArray = new JSONArray();
for (int i = 0; i < processIds.size(); i++) {
Process process = processService.getProcessByProcessId(processIds.get(i).toString());
JSONObject message = new JSONObject();
message.put("processName", process.getProcessName());
message.put("processContent", process.getProcessContent());
processJSONArray.add(message);
}
JSONObject message = new JSONObject();
message.put("contents", processJSONArray.toJSONString());
return JSONObject.toJSON(message);
}
/**
* 导入流程
*
* @param req
* @return
*/
@RequestMapping(value = "/importProcess", method = RequestMethod.POST)
public Object importProcess(HttpServletRequest req) {
String contents = req.getParameter("processes");
JSONArray processContents = JSONArray.parseArray(contents);
User user = (User) req.getAttribute("user");
String userId = user.getUserId();
for (int i = 0; i < processContents.size(); i++) {
JSONObject oneProcess = processContents.getJSONObject(i);
String processName = oneProcess.getString("processName");
String processContent = oneProcess.getString("processContent");
processService.addProcess(processName, processContent, userId);
}
JSONObject message = new JSONObject();
message.put("message", "导入流程成功");
return JSONObject.toJSON(message);
}
@RequestMapping(value = "/copyProcess", method = RequestMethod.POST)
public Object copyProcess(HttpServletRequest req) {
String processId = req.getParameter("processId");
String newProcessName = req.getParameter("newProcessName");
User user = (User) req.getAttribute("user");
Process process = processService.getProcessByProcessId(processId);
processService.addProcess(newProcessName, process.getProcessContent(), user.getUserId());
JSONObject message = new JSONObject();
message.put("message", "复制流程成功");
return JSONObject.toJSON(message);
}
@RequestMapping(value = "/batchDeleteProcess", method = RequestMethod.POST)
public Object batchDeleteProcess(HttpServletRequest req) {
String ids = req.getParameter("processIds");
User user = (User) req.getAttribute("user");
JSONArray processIds = JSONArray.parseArray(ids);
JSONObject message = new JSONObject();
boolean isNotPermission = false;
for (int i = 0; i < processIds.size(); i++) {
Process process = processService.getProcessByProcessId(processIds.getString(i));
if (!process.getUserId().equals(user.getUserId())) {
isNotPermission = true;
break;
}
}
if (isNotPermission) {
throw new serviceException("要删除的流程中有部分流程无删除权限!");
} else {
for (int i = 0; i < processIds.size(); i++)
processService.deleteProcess(processIds.get(i).toString());
message.put("message", "批量删除流程成功");
}
return JSONObject.toJSON(message);
}
private Object parseMap(Map<String, Configuration> configurationMap) {
JSONArray array = new JSONArray();
for (Map.Entry<String, Configuration> entry : configurationMap.entrySet()) {
Configuration value = entry.getValue();
array.add(JSONObject.parseObject(value.toJSON()));
}
return JSONObject.toJSON(array);
}
@RequestMapping(value = "/getAllPrivateProcess", method = RequestMethod.POST)
public Object getAllPrivateProcess(HttpServletRequest req) {
User user = (User) req.getAttribute("user");
JSONObject message = new JSONObject();
JSONArray processDesc;
List<ProcessUseridDto> list;
int pageSize;
int pageNumber;
int totalPages;
if (req.getParameter("pageSize") == null && req.getParameter("pageNumber") == null) {
list = processService.getAllPrivateProcess(user.getUserId());
pageSize = list.size();
pageNumber = 1;
totalPages = 1;
} else {
pageSize = Integer.parseInt(req.getParameter("pageSize"));
pageNumber = Integer.parseInt(req.getParameter("pageNumber"));
list = processService.getPagePrivateProcess(user.getUserId(), pageSize, pageNumber);
int totalSize = processService.getPrivateProcessCount(user.getUserId());
totalPages = totalSize / pageSize + (totalSize % pageSize == 0 ? 0 : 1);
}
processDesc = richProcess(list);
message.put("pageSize", pageSize);
message.put("pageNumber", pageNumber);
message.put("totalPages", totalPages);
message.put("processDesc", processDesc);
return JSONObject.toJSON(message);
}
private JSONArray richProcess(List<ProcessUseridDto> list) {
JSONArray result = new JSONArray();
for (ProcessUseridDto dto : list) {
JSONObject object = JSONObject.parseObject(JSONObject.toJSON(dto).toString());
JSONArray jsonArray = JSONArray.parseArray(dto.getProcessContent());
int size = jsonArray.size();
object.put("input", jsonArray.getJSONObject(0).getString("pluginName"));
object.put("output", jsonArray.getJSONObject(size - 1).getString("pluginName"));
result.add(object);
}
return result;
}
}
| UTF-8 | Java | 10,497 | java | ProcessController.java | Java | [] | null | [] | package com.km.service.ProcessModule.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.km.data.common.util.Configuration;
import com.km.service.ConfigureModule.service.ConfigureService;
import com.km.service.ProcessModule.domain.Process;
import com.km.service.ProcessModule.dto.ProcessUseridDto;
import com.km.service.ProcessModule.service.ProcessService;
import com.km.service.UserModule.domain.User;
import com.km.service.common.exception.serviceException;
import com.km.utils.LoadConfigureUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
@RestController
public class ProcessController {
@Autowired
private ProcessService processService;
@Autowired
private ConfigureService configureService;
@RequestMapping(value = "/getAllProcess", method = RequestMethod.POST)
public Object getAllProcess(HttpServletRequest req) {
int pageSize = Integer.parseInt(req.getParameter("pageSize"));
int pageNumber = Integer.parseInt(req.getParameter("pageNumber"));
List<ProcessUseridDto> list = processService.getAllProcess(pageSize, pageNumber);
JSONArray processDesc = richProcess(list);
int totalSize = processService.getProcessCount();
int totalPages = totalSize / pageSize + (totalSize % pageSize == 0 ? 0 : 1);
JSONObject message = new JSONObject();
message.put("pageSize", pageSize);
message.put("pageNumber", pageNumber);
message.put("totalPages", totalPages);
message.put("processDesc", processDesc);
return JSONObject.toJSON(message);
}
@RequestMapping(value = "/getAllPlugins", method = RequestMethod.POST)
public Object getAllPlugins(HttpServletRequest req) {
Map<String, Configuration> reader = LoadConfigureUtil.getReaderPlugNameToConf();
Map<String, Configuration> writer = LoadConfigureUtil.getWriterPlugNameToConf();
Map<String, Configuration> etl = LoadConfigureUtil.getEtlPlugNameToConf();
JSONObject message = new JSONObject();
message.put("readerPlugins", parseMap(reader));
message.put("writerPlugins", parseMap(writer));
message.put("etlPlugins", parseMap(etl));
return JSONObject.toJSON(message);
}
@RequestMapping(value = "/getOneProcess", method = RequestMethod.POST)
public Object getOneProcessDesc(HttpServletRequest req) {
String processId = req.getParameter("processId");
Process process = processService.getProcessByProcessId(processId);
return JSONObject.toJSON(process);
}
@RequestMapping(value = "/addProcess", method = RequestMethod.POST)
public Object addProcess(HttpServletRequest req) {
String processName = req.getParameter("processName");
String content = req.getParameter("processContent");
String processContent = JSONObject.parseArray(content).toString();
User user = (User) req.getAttribute("user");
String userId = user.getUserId();
processService.addProcess(processName, processContent, userId);
JSONObject message = new JSONObject();
message.put("message", "创建流程成功");
return JSONObject.toJSON(message);
}
@RequestMapping(value = "/deleteProcess", method = RequestMethod.POST)
public Object deleteProcess(HttpServletRequest req) {
String processId = req.getParameter("processId");
processService.deleteProcess(processId);
JSONObject message = new JSONObject();
message.put("message", "删除流程成功");
return JSONObject.toJSON(message);
}
@RequestMapping(value = "/updateProcess", method = RequestMethod.POST)
public Object updateProcess(HttpServletRequest req) {
String processId = req.getParameter("processId");
String processName = req.getParameter("processName");
String content = req.getParameter("processContent");
String processContent = JSONObject.parseArray(content).toString();
processService.updateProcess(processId, processName, processContent);
JSONObject message = new JSONObject();
message.put("message", "更新流程成功");
return JSONObject.toJSON(message);
}
/**
* 导出流程
*
* @param req
* @return
*/
@RequestMapping(value = "/exportProcess", method = RequestMethod.POST)
public Object exportProcess(HttpServletRequest req) {
String ids = req.getParameter("processIds");
JSONArray processIds = JSONArray.parseArray(ids);
JSONArray processJSONArray = new JSONArray();
for (int i = 0; i < processIds.size(); i++) {
Process process = processService.getProcessByProcessId(processIds.get(i).toString());
JSONObject message = new JSONObject();
message.put("processName", process.getProcessName());
message.put("processContent", process.getProcessContent());
processJSONArray.add(message);
}
JSONObject message = new JSONObject();
message.put("contents", processJSONArray.toJSONString());
return JSONObject.toJSON(message);
}
/**
* 导入流程
*
* @param req
* @return
*/
@RequestMapping(value = "/importProcess", method = RequestMethod.POST)
public Object importProcess(HttpServletRequest req) {
String contents = req.getParameter("processes");
JSONArray processContents = JSONArray.parseArray(contents);
User user = (User) req.getAttribute("user");
String userId = user.getUserId();
for (int i = 0; i < processContents.size(); i++) {
JSONObject oneProcess = processContents.getJSONObject(i);
String processName = oneProcess.getString("processName");
String processContent = oneProcess.getString("processContent");
processService.addProcess(processName, processContent, userId);
}
JSONObject message = new JSONObject();
message.put("message", "导入流程成功");
return JSONObject.toJSON(message);
}
@RequestMapping(value = "/copyProcess", method = RequestMethod.POST)
public Object copyProcess(HttpServletRequest req) {
String processId = req.getParameter("processId");
String newProcessName = req.getParameter("newProcessName");
User user = (User) req.getAttribute("user");
Process process = processService.getProcessByProcessId(processId);
processService.addProcess(newProcessName, process.getProcessContent(), user.getUserId());
JSONObject message = new JSONObject();
message.put("message", "复制流程成功");
return JSONObject.toJSON(message);
}
@RequestMapping(value = "/batchDeleteProcess", method = RequestMethod.POST)
public Object batchDeleteProcess(HttpServletRequest req) {
String ids = req.getParameter("processIds");
User user = (User) req.getAttribute("user");
JSONArray processIds = JSONArray.parseArray(ids);
JSONObject message = new JSONObject();
boolean isNotPermission = false;
for (int i = 0; i < processIds.size(); i++) {
Process process = processService.getProcessByProcessId(processIds.getString(i));
if (!process.getUserId().equals(user.getUserId())) {
isNotPermission = true;
break;
}
}
if (isNotPermission) {
throw new serviceException("要删除的流程中有部分流程无删除权限!");
} else {
for (int i = 0; i < processIds.size(); i++)
processService.deleteProcess(processIds.get(i).toString());
message.put("message", "批量删除流程成功");
}
return JSONObject.toJSON(message);
}
private Object parseMap(Map<String, Configuration> configurationMap) {
JSONArray array = new JSONArray();
for (Map.Entry<String, Configuration> entry : configurationMap.entrySet()) {
Configuration value = entry.getValue();
array.add(JSONObject.parseObject(value.toJSON()));
}
return JSONObject.toJSON(array);
}
@RequestMapping(value = "/getAllPrivateProcess", method = RequestMethod.POST)
public Object getAllPrivateProcess(HttpServletRequest req) {
User user = (User) req.getAttribute("user");
JSONObject message = new JSONObject();
JSONArray processDesc;
List<ProcessUseridDto> list;
int pageSize;
int pageNumber;
int totalPages;
if (req.getParameter("pageSize") == null && req.getParameter("pageNumber") == null) {
list = processService.getAllPrivateProcess(user.getUserId());
pageSize = list.size();
pageNumber = 1;
totalPages = 1;
} else {
pageSize = Integer.parseInt(req.getParameter("pageSize"));
pageNumber = Integer.parseInt(req.getParameter("pageNumber"));
list = processService.getPagePrivateProcess(user.getUserId(), pageSize, pageNumber);
int totalSize = processService.getPrivateProcessCount(user.getUserId());
totalPages = totalSize / pageSize + (totalSize % pageSize == 0 ? 0 : 1);
}
processDesc = richProcess(list);
message.put("pageSize", pageSize);
message.put("pageNumber", pageNumber);
message.put("totalPages", totalPages);
message.put("processDesc", processDesc);
return JSONObject.toJSON(message);
}
private JSONArray richProcess(List<ProcessUseridDto> list) {
JSONArray result = new JSONArray();
for (ProcessUseridDto dto : list) {
JSONObject object = JSONObject.parseObject(JSONObject.toJSON(dto).toString());
JSONArray jsonArray = JSONArray.parseArray(dto.getProcessContent());
int size = jsonArray.size();
object.put("input", jsonArray.getJSONObject(0).getString("pluginName"));
object.put("output", jsonArray.getJSONObject(size - 1).getString("pluginName"));
result.add(object);
}
return result;
}
}
| 10,497 | 0.671584 | 0.670234 | 238 | 42.57563 | 26.859903 | 97 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.831933 | false | false | 8 |
ac2c56a8d70ff5bafc2896705c4ae47b1687f8f3 | 16,982,300,720,692 | 050f8390bdae668d7dc82a9f999c91333f83bc1d | /APP_PERSONAS/src/main/java/co/com/bancolombia/certificacion/app/tasks/administrarfacturas/ConsultarFacturaProgramadas.java | e40f56239b30645919e15b43d5a6658b3ef5f942 | [] | no_license | julianvilla26/pruebaOSP | https://github.com/julianvilla26/pruebaOSP | 0f035117f7b586198dc658c929a3a971ba59ad54 | 0d63f7fd381f6a2bcb2647c16c176f747a31a326 | refs/heads/master | 2020-09-02T11:58:13.329000 | 2019-11-02T21:30:55 | 2019-11-02T21:30:55 | 219,215,714 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package co.com.bancolombia.certificacion.app.tasks.administrarfacturas;
import co.com.bancolombia.certificacion.app.models.administrarfacturas.Factura;
import co.com.bancolombia.certificacion.app.utilidades.administradores.Verificar;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.actions.Click;
import java.util.ArrayList;
import java.util.List;
import static co.com.bancolombia.certificacion.app.models.builders.FacturaBuilder.factura;
import static co.com.bancolombia.certificacion.app.userinterface.pages.administrarfacturas.ConsultaDetalleFacturaPage.*;
import static co.com.bancolombia.certificacion.app.userinterface.pages.administrarfacturas.ProgramarPagarFacturasPage.OPT_PROGRAMADAS;
import static co.com.bancolombia.certificacion.app.utilidades.constantes.ModeloConstantes.MODELO_FACTURA;
public class ConsultarFacturaProgramadas implements Task {
@Override
public <T extends Actor> void performAs(T actor) {
actor.attemptsTo(
Click.on(OPT_PROGRAMADAS)
);
int iterador = 0;
List<Factura> listaFactura = new ArrayList<>();
while (Verificar.elementoVisible(actor, LBL_DESCRIPCION_PROGRAMADA_FACTURA.of(String.valueOf(iterador)))) {
listaFactura.add(factura()
.conDescripcionFactura(LBL_DESCRIPCION_PROGRAMADA_FACTURA.of(String.valueOf(iterador)).resolveFor(actor).getText())
.conEmpresaServicio(LBL_EMPRESA_CONVENIO_FACTURA_PROGRAMADA.of(String.valueOf(iterador)).resolveFor(actor).getText())
.conFechaFactura(LBL_FECHA_FACTURA_PROGRAMADA.of(String.valueOf(iterador)).resolveFor(actor).getText())
.conValor(LBL_VALOR_FACTURA_PROGRAMADA.of(String.valueOf(iterador)).resolveFor(actor).getText())
.build()
);
iterador++;
}
actor.remember(MODELO_FACTURA, listaFactura);
}
} | UTF-8 | Java | 1,971 | java | ConsultarFacturaProgramadas.java | Java | [] | null | [] | package co.com.bancolombia.certificacion.app.tasks.administrarfacturas;
import co.com.bancolombia.certificacion.app.models.administrarfacturas.Factura;
import co.com.bancolombia.certificacion.app.utilidades.administradores.Verificar;
import net.serenitybdd.screenplay.Actor;
import net.serenitybdd.screenplay.Task;
import net.serenitybdd.screenplay.actions.Click;
import java.util.ArrayList;
import java.util.List;
import static co.com.bancolombia.certificacion.app.models.builders.FacturaBuilder.factura;
import static co.com.bancolombia.certificacion.app.userinterface.pages.administrarfacturas.ConsultaDetalleFacturaPage.*;
import static co.com.bancolombia.certificacion.app.userinterface.pages.administrarfacturas.ProgramarPagarFacturasPage.OPT_PROGRAMADAS;
import static co.com.bancolombia.certificacion.app.utilidades.constantes.ModeloConstantes.MODELO_FACTURA;
public class ConsultarFacturaProgramadas implements Task {
@Override
public <T extends Actor> void performAs(T actor) {
actor.attemptsTo(
Click.on(OPT_PROGRAMADAS)
);
int iterador = 0;
List<Factura> listaFactura = new ArrayList<>();
while (Verificar.elementoVisible(actor, LBL_DESCRIPCION_PROGRAMADA_FACTURA.of(String.valueOf(iterador)))) {
listaFactura.add(factura()
.conDescripcionFactura(LBL_DESCRIPCION_PROGRAMADA_FACTURA.of(String.valueOf(iterador)).resolveFor(actor).getText())
.conEmpresaServicio(LBL_EMPRESA_CONVENIO_FACTURA_PROGRAMADA.of(String.valueOf(iterador)).resolveFor(actor).getText())
.conFechaFactura(LBL_FECHA_FACTURA_PROGRAMADA.of(String.valueOf(iterador)).resolveFor(actor).getText())
.conValor(LBL_VALOR_FACTURA_PROGRAMADA.of(String.valueOf(iterador)).resolveFor(actor).getText())
.build()
);
iterador++;
}
actor.remember(MODELO_FACTURA, listaFactura);
}
} | 1,971 | 0.739219 | 0.738711 | 38 | 50.894737 | 44.340069 | 137 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.526316 | false | false | 8 |
2d127f62824f48857b681be91f11dd7dabbd1266 | 20,504,173,894,257 | 4e5a4b6de9a466ace340f6058158abe2efa381a9 | /ngp_prom/prom_module/src/main/java/com/heepay/prom/modules/prom/service/PromWechatService.java | ec3fb1ae8639f7e8eaf8aec15383784df5541d8e | [] | no_license | Yigexuetu/openSource | https://github.com/Yigexuetu/openSource | c8c776c6d4d1c6a5393eaffa63635f63e9cc3125 | 097e7e457cbd27d5e34669bc335733cd3a7dbd69 | refs/heads/master | 2021-12-21T13:39:19.983000 | 2017-09-28T06:40:47 | 2017-09-28T06:40:47 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
* Copyright © since 2008. All Rights Reserved
* 汇元银通(北京)在线支付技术有限公司 www.heepay.com
*/
package com.heepay.prom.modules.prom.service;
import com.heepay.prom.common.persistence.Page;
import com.heepay.prom.common.service.CrudService;
import com.heepay.prom.modules.prom.dao.PromWechatDao;
import com.heepay.prom.modules.prom.entity.PromWechat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
*
* 描 述:用户管理(微信)Service
*
* 创 建 者: @author wangdong
* 创建时间:
* 创建描述:
*
* 修 改 者:
* 修改时间:
* 修改描述:
*
* 审 核 者:
* 审核时间:
* 审核描述:
*
*/
@Service
@Transactional(readOnly = true)
public class PromWechatService extends CrudService<PromWechatDao, PromWechat> {
@Autowired
private PromWechatDao promWechatDao;
public PromWechat get(String id) {
return super.get(id);
}
public List<PromWechat> findList(PromWechat promWechat) {
return super.findList(promWechat);
}
public Page<PromWechat> findPage(Page<PromWechat> page, PromWechat promWechat) {
return super.findPage(page, promWechat);
}
@Transactional(readOnly = false)
public void save(PromWechat promWechat) {
promWechat.setCreateAuthor("APP自动录入");
promWechatDao.insert(promWechat);
}
@Transactional(readOnly = false)
public int update(PromWechat promWechat) {
promWechat.setUpdateAuthor("APP自动录入");
return promWechatDao.update(promWechat);
}
@Transactional(readOnly = false)
public void delete(PromWechat promWechat) {
super.delete(promWechat);
}
public Integer findExit(PromWechat promWechat) {
return promWechatDao.findExit(promWechat);
}
} | UTF-8 | Java | 1,915 | java | PromWechatService.java | Java | [
{
"context": "\n *\n * 描 述:用户管理(微信)Service\n *\n * 创 建 者: @author wangdong\n * 创建时间:\n * 创建描述:\n *\n * 修 改 者:\n * 修改时间:\n * 修改描述:\n",
"end": 616,
"score": 0.996969997882843,
"start": 608,
"tag": "USERNAME",
"value": "wangdong"
}
] | null | [] | /**
* Copyright © since 2008. All Rights Reserved
* 汇元银通(北京)在线支付技术有限公司 www.heepay.com
*/
package com.heepay.prom.modules.prom.service;
import com.heepay.prom.common.persistence.Page;
import com.heepay.prom.common.service.CrudService;
import com.heepay.prom.modules.prom.dao.PromWechatDao;
import com.heepay.prom.modules.prom.entity.PromWechat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
*
* 描 述:用户管理(微信)Service
*
* 创 建 者: @author wangdong
* 创建时间:
* 创建描述:
*
* 修 改 者:
* 修改时间:
* 修改描述:
*
* 审 核 者:
* 审核时间:
* 审核描述:
*
*/
@Service
@Transactional(readOnly = true)
public class PromWechatService extends CrudService<PromWechatDao, PromWechat> {
@Autowired
private PromWechatDao promWechatDao;
public PromWechat get(String id) {
return super.get(id);
}
public List<PromWechat> findList(PromWechat promWechat) {
return super.findList(promWechat);
}
public Page<PromWechat> findPage(Page<PromWechat> page, PromWechat promWechat) {
return super.findPage(page, promWechat);
}
@Transactional(readOnly = false)
public void save(PromWechat promWechat) {
promWechat.setCreateAuthor("APP自动录入");
promWechatDao.insert(promWechat);
}
@Transactional(readOnly = false)
public int update(PromWechat promWechat) {
promWechat.setUpdateAuthor("APP自动录入");
return promWechatDao.update(promWechat);
}
@Transactional(readOnly = false)
public void delete(PromWechat promWechat) {
super.delete(promWechat);
}
public Integer findExit(PromWechat promWechat) {
return promWechatDao.findExit(promWechat);
}
} | 1,915 | 0.730068 | 0.72779 | 73 | 23.068493 | 22.540878 | 81 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.643836 | false | false | 8 |
483fa64404764464c96039f3d0d2c05cf6d2cd63 | 10,625,749,143,067 | f88e64915acff03663cd5646f0727548805f65c3 | /src/com/glc/design_pattern/seven_design_philosophy/_6_liskov_principle/negtive/AppTest.java | e19880c6e25b81ee117834cac76245813b001d29 | [] | no_license | Richard-lc/java2009 | https://github.com/Richard-lc/java2009 | 3d833863055744f16e8916458137fc9eaa2b182d | ddf8bb252b89f6ac9aac5bcf3b491471dfe918dd | refs/heads/master | 2023-02-02T19:19:10.180000 | 2020-12-17T05:57:54 | 2020-12-17T05:57:54 | 320,174,736 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.glc.design_pattern.seven_design_philosophy._6_liskov_principle.negtive;
//需求:将长方形的宽改成比长大 1
//在父类Rectangular下,业务场景符合逻辑。现有子类Square,替换后如何。
//反例:正方形不是长方形
class Rectangular {
private Integer width;
private Integer length;
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
public Integer getLength() {
return length;
}
public void setLength(Integer length) {
this.length = length;
}
}
class Square extends Rectangular {
private Integer sideWidth;
@Override
public Integer getWidth() {
return sideWidth;
}
@Override
public void setWidth(Integer width) {
this.sideWidth = width;
}
@Override
public Integer getLength() {
return sideWidth;
}
@Override
public void setLength(Integer length) {
this.sideWidth = length;
}
}
class Utils {
public void transform(Rectangular graph) {
while (graph.getWidth() <= graph.getLength()) {
graph.setWidth(graph.getWidth() + 1);
System.out.println("长:" + graph.getLength() + " : " +
"宽:" + graph.getWidth());
}
}
}
public class AppTest {
public static void main(String[] args) {
// Rectangular graph = new Rectangular();
Rectangular graph = new Square();
graph.setWidth(20);
graph.setLength(30);
Utils utils = new Utils();
utils.transform(graph);
}
}
/*
替换后运行将是无限死循环。
要知道,在向上转型的时候,方法的调用只和new的对象有关,才会造成不同的结果。
在使用场景下,需要考虑替换后业务逻辑是否受影响。
由此引出里氏替换原则的使用需要考虑的条件:
是否有is-a关系
子类可以扩展父类的功能,但是不能改变父类原有的功能。
这样的反例还有很多,如:鸵鸟非鸟,
还有咱们老祖宗早就说过的的春秋战国时期--白马非马说,都是一个道理。
*/ | UTF-8 | Java | 2,241 | java | AppTest.java | Java | [] | null | [] | package com.glc.design_pattern.seven_design_philosophy._6_liskov_principle.negtive;
//需求:将长方形的宽改成比长大 1
//在父类Rectangular下,业务场景符合逻辑。现有子类Square,替换后如何。
//反例:正方形不是长方形
class Rectangular {
private Integer width;
private Integer length;
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
public Integer getLength() {
return length;
}
public void setLength(Integer length) {
this.length = length;
}
}
class Square extends Rectangular {
private Integer sideWidth;
@Override
public Integer getWidth() {
return sideWidth;
}
@Override
public void setWidth(Integer width) {
this.sideWidth = width;
}
@Override
public Integer getLength() {
return sideWidth;
}
@Override
public void setLength(Integer length) {
this.sideWidth = length;
}
}
class Utils {
public void transform(Rectangular graph) {
while (graph.getWidth() <= graph.getLength()) {
graph.setWidth(graph.getWidth() + 1);
System.out.println("长:" + graph.getLength() + " : " +
"宽:" + graph.getWidth());
}
}
}
public class AppTest {
public static void main(String[] args) {
// Rectangular graph = new Rectangular();
Rectangular graph = new Square();
graph.setWidth(20);
graph.setLength(30);
Utils utils = new Utils();
utils.transform(graph);
}
}
/*
替换后运行将是无限死循环。
要知道,在向上转型的时候,方法的调用只和new的对象有关,才会造成不同的结果。
在使用场景下,需要考虑替换后业务逻辑是否受影响。
由此引出里氏替换原则的使用需要考虑的条件:
是否有is-a关系
子类可以扩展父类的功能,但是不能改变父类原有的功能。
这样的反例还有很多,如:鸵鸟非鸟,
还有咱们老祖宗早就说过的的春秋战国时期--白马非马说,都是一个道理。
*/ | 2,241 | 0.608403 | 0.604482 | 86 | 19.767443 | 18.297716 | 83 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.232558 | false | false | 8 |
1e901dd5b206ffb420d89ea38e3dc53a344233f6 | 26,757,646,289,371 | 5ba411690268c82c794b49410dd68f9735b83342 | /src/main/java/br/biblioteca/livros/controladores/Index.java | 824ea68fe15a55975801f2e190e570a42644591e | [] | no_license | carloscubas/Cadastro-Livros | https://github.com/carloscubas/Cadastro-Livros | ca4d882185fa903882d94c62d6e71e14d955c1c0 | 28b1d0d62134c3eb234c967a676ccb31c0eea77b | refs/heads/master | 2022-07-09T01:47:13.972000 | 2020-04-25T01:54:29 | 2020-04-25T01:54:29 | 113,673,042 | 0 | 0 | null | false | 2020-04-12T19:26:00 | 2017-12-09T13:53:06 | 2020-04-12T13:01:13 | 2020-04-12T19:26:00 | 2,214 | 0 | 0 | 0 | Java | false | false | package br.biblioteca.livros.controladores;
import br.biblioteca.livros.entities.Livro;
import br.biblioteca.livros.repository.LivroRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
@RestController
public class Index {
@Autowired
private LivroRepository livroRepository;
@GetMapping("/")
public ModelAndView home() {
return new ModelAndView("index");
}
@RequestMapping("/livros")
public ModelAndView livros() {
Iterable<Livro> livros = livroRepository.findAll();
return new ModelAndView("livros", "livros", livros);
}
}
| UTF-8 | Java | 846 | java | Index.java | Java | [] | null | [] | package br.biblioteca.livros.controladores;
import br.biblioteca.livros.entities.Livro;
import br.biblioteca.livros.repository.LivroRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
@RestController
public class Index {
@Autowired
private LivroRepository livroRepository;
@GetMapping("/")
public ModelAndView home() {
return new ModelAndView("index");
}
@RequestMapping("/livros")
public ModelAndView livros() {
Iterable<Livro> livros = livroRepository.findAll();
return new ModelAndView("livros", "livros", livros);
}
}
| 846 | 0.761229 | 0.761229 | 28 | 29.178572 | 23.55397 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 8 |
951f3c497a442347b403706d7873cc298a784927 | 1,683,627,249,334 | 91febf7d3c6197ddaeeba6e5d1568b61160f25ef | /Capbook2/src/main/java/com/cg/capbook/beans/Comments.java | 1bd4234eae970dcb9cf44c13e00150bff03805ab | [] | no_license | 27072015/capbook2 | https://github.com/27072015/capbook2 | cfb04607e4ef21778e6a5957e67dca84afeb97ca | e1526e1b54299b59dd1e3171888a1b71907588ae | refs/heads/master | 2020-05-03T03:46:46.554000 | 2019-03-29T13:01:20 | 2019-03-29T13:01:20 | 178,405,674 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cg.capbook.beans;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class Comments {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int commentid;
@ManyToOne
private Status status;
public Comments() {
}
public Comments(int commentid, Status status) {
super();
this.commentid = commentid;
this.status = status;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + commentid;
result = prime * result + ((status == null) ? 0 : status.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Comments other = (Comments) obj;
if (commentid != other.commentid)
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
return true;
}
public int getCommentid() {
return commentid;
}
public void setCommentid(int commentid) {
this.commentid = commentid;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
@Override
public String toString() {
return "Comments [commentid=" + commentid + ", status=" + status + "]";
}
}
| UTF-8 | Java | 1,502 | java | Comments.java | Java | [] | null | [] | package com.cg.capbook.beans;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class Comments {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int commentid;
@ManyToOne
private Status status;
public Comments() {
}
public Comments(int commentid, Status status) {
super();
this.commentid = commentid;
this.status = status;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + commentid;
result = prime * result + ((status == null) ? 0 : status.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Comments other = (Comments) obj;
if (commentid != other.commentid)
return false;
if (status == null) {
if (other.status != null)
return false;
} else if (!status.equals(other.status))
return false;
return true;
}
public int getCommentid() {
return commentid;
}
public void setCommentid(int commentid) {
this.commentid = commentid;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
@Override
public String toString() {
return "Comments [commentid=" + commentid + ", status=" + status + "]";
}
}
| 1,502 | 0.678429 | 0.675766 | 72 | 18.861111 | 16.225243 | 72 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.930556 | false | false | 8 |
1189a109bf5d4c60a9eb7625dd445abb62102ffc | 6,605,659,763,746 | 7254ad0504f8f239b64e3136fe8d090232cf9fb6 | /src/Practice/Date_Time.java | 0c483431b4dcdb1cb9c4b2a22b29213afa079188 | [] | no_license | basimbd/ShopManager_Java | https://github.com/basimbd/ShopManager_Java | cf66fe9bb57da62e5afb50542c0ddd522931ddcd | 57d248f3bc09e3afa3c1f9b851b4e08f79223b89 | refs/heads/main | 2023-03-09T06:08:47.518000 | 2021-02-25T19:01:13 | 2021-02-25T19:01:13 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 Practice;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Calendar;
import javafx.scene.control.DatePicker;
public class Date_Time {
public static String getDateAndTime() {
Calendar now = Calendar.getInstance();
System.out.println(now);
String hour=Integer.toString(LocalDateTime.now().getHour());
if(hour.length()==1) hour="0"+hour;
String min=Integer.toString(LocalDateTime.now().getMinute());
if(min.length()==1) min="0"+min;
String second=Integer.toString(LocalDateTime.now().getSecond());
if(second.length()==1) second="0"+second;
return LocalDate.now()+" "+hour+"."+min+"."+second;
}
public static void main(String[] args) {
String str;
str = getDateAndTime();
System.out.println(str);
}
}
| UTF-8 | Java | 1,024 | java | Date_Time.java | Java | [] | null | [] | /*
* 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 Practice;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Calendar;
import javafx.scene.control.DatePicker;
public class Date_Time {
public static String getDateAndTime() {
Calendar now = Calendar.getInstance();
System.out.println(now);
String hour=Integer.toString(LocalDateTime.now().getHour());
if(hour.length()==1) hour="0"+hour;
String min=Integer.toString(LocalDateTime.now().getMinute());
if(min.length()==1) min="0"+min;
String second=Integer.toString(LocalDateTime.now().getSecond());
if(second.length()==1) second="0"+second;
return LocalDate.now()+" "+hour+"."+min+"."+second;
}
public static void main(String[] args) {
String str;
str = getDateAndTime();
System.out.println(str);
}
}
| 1,024 | 0.666016 | 0.660156 | 35 | 28.257143 | 21.993952 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1 | false | false | 8 |
739e04e87f0730f436e2b1234b5a672bf3f0a109 | 6,605,659,765,515 | 16deca99d9b935169155701aab9bdbdc79c4859a | /Libgdx with video Tests/html3DTest/core/src/com/byrfb/geometry/cartesian/Line.java | b9c72b8586890ce2d1a399b8fb1c50377d81bbfc | [] | no_license | recaifurkan/My-Java-Repos | https://github.com/recaifurkan/My-Java-Repos | 0b90fc05cf7de08eb669661bfe16c269df77ac3e | 0b8c51d710a31509e42dc4885810c20f7b3c6ae6 | refs/heads/master | 2023-01-18T20:50:26.891000 | 2021-05-31T06:51:06 | 2021-05-31T06:51:06 | 189,587,588 | 0 | 0 | null | false | 2023-01-12T11:52:08 | 2019-05-31T12:06:20 | 2021-05-31T06:51:08 | 2023-01-12T11:52:08 | 323,234 | 0 | 0 | 24 | Python | false | false | package com.byrfb.geometry.cartesian;
import java.util.ArrayList;
import java.util.List;
public class Line {
public static List<Point> line(Point startPoint,Point endPoint) {
return line(startPoint.x(),startPoint.y(),startPoint.z(),endPoint.x(),endPoint.y(),endPoint.z());
}
/*
Alttaki metot başlangıç ve bitiş koordinatları verilen çizginin noktalarının arrayini geri döndürür
*/
public static List<Point> line(float x1, float y1, float z1, float x2, float y2, float z2) {
List<Point> points = new ArrayList<Point>();
// points.add(new Point(x1, y1, z1));
double dx = Math.abs(x2 - x1);
double dy = Math.abs(y2 - y1);
double dz = Math.abs(z2 - z1);
double xs;
double ys;
double zs;
if (x2 > x1)
xs = 1;
else
xs = -1;
if (y2 > y1)
ys = 1;
else
ys = -1;
if (z2 > z1)
zs = 1;
else
zs = -1;
if (dx >= dy && dx >= dz) {
double p1 = 2 * dy - dx;
double p2 = 2 * dz - dx;
for (int i = 0; i < dx ; i++) {
x1 += xs;
if (p1 >= 0) {
y1 += ys;
p1 -= 2 * dx;
}
if (p2 >= 0) {
z1 += zs;
p2 -= 2 * dx;
}
p1 += 2 * dy;
p2 += 2 * dz;
points.add(new Point(x1, y1, z1));
}
}
else if (dy >= dx && dy >= dz) {
double p1 = 2 * dx - dy;
double p2 = 2 * dz - dy;
for (int i = 0; i < dy ; i++) {
y1 += ys;
if (p1 >= 0) {
x1 += xs;
p1 -= 2 * dy;
}
if (p2 >= 0) {
z1 += zs;
p2 -= 2 * dy;
}
p1 += 2 * dx;
p2 += 2 * dz;
points.add(new Point(x1, y1, z1));
}
}
else {
double p1 = 2 * dy - dz;
double p2 = 2 * dx - dz;
for (int i = 0; i < dz ; i++) {
z1 += zs;
if (p1 >= 0) {
y1 += ys;
p1 -= 2 * dz;
}
if (p2 >= 0) {
x1 += xs;
p2 -= 2 * dz;
}
p1 += 2 * dy;
p2 += 2 * dx;
points.add(new Point(x1, y1, z1));
}
}
return points;
}
//
// // Driving axis is X-axis"
//
// // Driving axis is Y-axis"
//
// // Driving axis is Z-axis"
// return ListOfPoints
}
| UTF-8 | Java | 2,118 | java | Line.java | Java | [] | null | [] | package com.byrfb.geometry.cartesian;
import java.util.ArrayList;
import java.util.List;
public class Line {
public static List<Point> line(Point startPoint,Point endPoint) {
return line(startPoint.x(),startPoint.y(),startPoint.z(),endPoint.x(),endPoint.y(),endPoint.z());
}
/*
Alttaki metot başlangıç ve bitiş koordinatları verilen çizginin noktalarının arrayini geri döndürür
*/
public static List<Point> line(float x1, float y1, float z1, float x2, float y2, float z2) {
List<Point> points = new ArrayList<Point>();
// points.add(new Point(x1, y1, z1));
double dx = Math.abs(x2 - x1);
double dy = Math.abs(y2 - y1);
double dz = Math.abs(z2 - z1);
double xs;
double ys;
double zs;
if (x2 > x1)
xs = 1;
else
xs = -1;
if (y2 > y1)
ys = 1;
else
ys = -1;
if (z2 > z1)
zs = 1;
else
zs = -1;
if (dx >= dy && dx >= dz) {
double p1 = 2 * dy - dx;
double p2 = 2 * dz - dx;
for (int i = 0; i < dx ; i++) {
x1 += xs;
if (p1 >= 0) {
y1 += ys;
p1 -= 2 * dx;
}
if (p2 >= 0) {
z1 += zs;
p2 -= 2 * dx;
}
p1 += 2 * dy;
p2 += 2 * dz;
points.add(new Point(x1, y1, z1));
}
}
else if (dy >= dx && dy >= dz) {
double p1 = 2 * dx - dy;
double p2 = 2 * dz - dy;
for (int i = 0; i < dy ; i++) {
y1 += ys;
if (p1 >= 0) {
x1 += xs;
p1 -= 2 * dy;
}
if (p2 >= 0) {
z1 += zs;
p2 -= 2 * dy;
}
p1 += 2 * dx;
p2 += 2 * dz;
points.add(new Point(x1, y1, z1));
}
}
else {
double p1 = 2 * dy - dz;
double p2 = 2 * dx - dz;
for (int i = 0; i < dz ; i++) {
z1 += zs;
if (p1 >= 0) {
y1 += ys;
p1 -= 2 * dz;
}
if (p2 >= 0) {
x1 += xs;
p2 -= 2 * dz;
}
p1 += 2 * dy;
p2 += 2 * dx;
points.add(new Point(x1, y1, z1));
}
}
return points;
}
//
// // Driving axis is X-axis"
//
// // Driving axis is Y-axis"
//
// // Driving axis is Z-axis"
// return ListOfPoints
}
| 2,118 | 0.460845 | 0.415282 | 132 | 14.962121 | 17.890833 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.507576 | false | false | 8 |
235abb7156b0457f078ef9ddcea1dcd8b1e2556e | 3,186,865,800,837 | 4e13d133c527e2b9575eb92f632fbfb232a6c902 | /src/main/java/com/jsilgado/gorrion/domain/CompositeKeyIncurrido.java | 95f9f9b1a63dbff7d203fbae37d83fc668418688 | [] | no_license | jsilgado/gorrion | https://github.com/jsilgado/gorrion | 39d0ff2cd9a87ec08c2c371389763077802fc690 | 1d04008214a272bc4feb2d26525405beefdc8f3f | refs/heads/master | 2020-03-08T11:47:44.455000 | 2018-04-05T08:11:51 | 2018-04-05T08:11:51 | 128,108,118 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.jsilgado.gorrion.domain;
import java.io.Serializable;
import java.util.Date;
public class CompositeKeyIncurrido implements Serializable {
/**
* Descripcion del campo
*/
private static final long serialVersionUID = 1908436225565459235L;
private Long nroEmpleado;
private Date fecha;
private String comentarioTarea;
/**
* @return Valor de la propiedad nroEmpleado
*/
public Long getNroEmpleado() {
return nroEmpleado;
}
/**
* @param nroEmpleado
* Valor de la propiedad nroEmpleado a setear
*/
public void setNroEmpleado( final Long nroEmpleado ) {
this.nroEmpleado = nroEmpleado;
}
/**
* @return Valor de la propiedad fecha
*/
public Date getFecha() {
return fecha;
}
/**
* @param fecha
* Valor de la propiedad fecha a setear
*/
public void setFecha( final Date fecha ) {
this.fecha = fecha;
}
/**
* @return Valor de la propiedad comentarioTarea
*/
public String getComentarioTarea() {
return comentarioTarea;
}
/**
* @param comentarioTarea
* Valor de la propiedad comentarioTarea a setear
*/
public void setComentarioTarea( final String comentarioTarea ) {
this.comentarioTarea = comentarioTarea;
}
}
| UTF-8 | Java | 1,227 | java | CompositeKeyIncurrido.java | Java | [] | null | [] | package com.jsilgado.gorrion.domain;
import java.io.Serializable;
import java.util.Date;
public class CompositeKeyIncurrido implements Serializable {
/**
* Descripcion del campo
*/
private static final long serialVersionUID = 1908436225565459235L;
private Long nroEmpleado;
private Date fecha;
private String comentarioTarea;
/**
* @return Valor de la propiedad nroEmpleado
*/
public Long getNroEmpleado() {
return nroEmpleado;
}
/**
* @param nroEmpleado
* Valor de la propiedad nroEmpleado a setear
*/
public void setNroEmpleado( final Long nroEmpleado ) {
this.nroEmpleado = nroEmpleado;
}
/**
* @return Valor de la propiedad fecha
*/
public Date getFecha() {
return fecha;
}
/**
* @param fecha
* Valor de la propiedad fecha a setear
*/
public void setFecha( final Date fecha ) {
this.fecha = fecha;
}
/**
* @return Valor de la propiedad comentarioTarea
*/
public String getComentarioTarea() {
return comentarioTarea;
}
/**
* @param comentarioTarea
* Valor de la propiedad comentarioTarea a setear
*/
public void setComentarioTarea( final String comentarioTarea ) {
this.comentarioTarea = comentarioTarea;
}
}
| 1,227 | 0.692747 | 0.677262 | 64 | 18.171875 | 20.149096 | 67 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.015625 | false | false | 8 |
25607b797d8f38eee418e3cd3bef104695fff11f | 24,833,500,925,036 | bfa3539652e8db59c6de76911ee2160facd52369 | /App/Swoosh/app/src/main/java/com/oskarjansson/swoosh/LoginActivity.java | 291cfe8caa17e739fa0bb53630e2ed57aad5d88a | [] | no_license | IAmBullsaw/Swoosh | https://github.com/IAmBullsaw/Swoosh | 3cab5f35c178e4458ef599ca7c9c0dce14c3a93a | 3d9a37d9c6a626a7a912ac59781e4022d4b4d68e | refs/heads/master | 2021-01-19T00:41:18.514000 | 2016-12-11T17:36:54 | 2016-12-11T17:36:54 | 73,178,848 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.oskarjansson.swoosh;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.firebase.ui.auth.AuthUI;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class LoginActivity extends AppCompatActivity {
private int RC_SIGN_IN = 0;
// For Firebase
private FirebaseAuth firebaseAuth;
private FirebaseUser firebaseUser;
// private int called = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
// called += 1;
// Cache all data if we go offline
// Also, this solves the problem of not pushing data if we go offline.
// if (called <= 1) { // TODO: Make sure to only call this ONCE and firstly
// firebaseDatabase.setPersistenceEnabled(true);
// }
firebaseAuth = FirebaseAuth.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser == null ) {
// User was not signed in, prompt user to sign in
startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(), RC_SIGN_IN);
} else {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra(Constants.SWOOSH_USER_UID,firebaseUser.getUid());
startActivity(intent);
finish();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Check which request we're responding to
if (requestCode == RC_SIGN_IN) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
Log.d("LoginActivity","RESULT_OK");
firebaseUser = firebaseAuth.getCurrentUser();
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra(Constants.SWOOSH_USER_UID,firebaseUser.getUid());
startActivity(intent);
finish();
} else if ( resultCode == RESULT_CANCELED ) {
Log.d("LoginActivity","RESULT_CANCELED");
// Todo: Do something about this"
finish();
} else if ( resultCode == RESULT_FIRST_USER) {
Log.d("LoginActivity","RESULT_FIRST_USER");
} else {
Log.d("LoginActivity","Else: " + resultCode);
finish();
}
}
}
}
| UTF-8 | Java | 2,921 | java | LoginActivity.java | Java | [
{
"context": "package com.oskarjansson.swoosh;\n\nimport android.content.Context;\nimport a",
"end": 24,
"score": 0.9803569316864014,
"start": 12,
"tag": "USERNAME",
"value": "oskarjansson"
}
] | null | [] | package com.oskarjansson.swoosh;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.firebase.ui.auth.AuthUI;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class LoginActivity extends AppCompatActivity {
private int RC_SIGN_IN = 0;
// For Firebase
private FirebaseAuth firebaseAuth;
private FirebaseUser firebaseUser;
// private int called = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
// called += 1;
// Cache all data if we go offline
// Also, this solves the problem of not pushing data if we go offline.
// if (called <= 1) { // TODO: Make sure to only call this ONCE and firstly
// firebaseDatabase.setPersistenceEnabled(true);
// }
firebaseAuth = FirebaseAuth.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser == null ) {
// User was not signed in, prompt user to sign in
startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().build(), RC_SIGN_IN);
} else {
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra(Constants.SWOOSH_USER_UID,firebaseUser.getUid());
startActivity(intent);
finish();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Check which request we're responding to
if (requestCode == RC_SIGN_IN) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
Log.d("LoginActivity","RESULT_OK");
firebaseUser = firebaseAuth.getCurrentUser();
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra(Constants.SWOOSH_USER_UID,firebaseUser.getUid());
startActivity(intent);
finish();
} else if ( resultCode == RESULT_CANCELED ) {
Log.d("LoginActivity","RESULT_CANCELED");
// Todo: Do something about this"
finish();
} else if ( resultCode == RESULT_FIRST_USER) {
Log.d("LoginActivity","RESULT_FIRST_USER");
} else {
Log.d("LoginActivity","Else: " + resultCode);
finish();
}
}
}
}
| 2,921 | 0.631633 | 0.629921 | 79 | 35.974682 | 25.349693 | 105 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.696203 | false | false | 8 |
b04c5648c70ee7874754fdc90ea707b756d93586 | 8,521,215,151,428 | 3d6130d465ee022a4d6230fbf10959da7461f591 | /BinaryS.java | 224983cf3d29b64184cef6ffbf2c86f1caf5749f | [] | no_license | Thommond/Data-Structure-Practice | https://github.com/Thommond/Data-Structure-Practice | 8e3d74d29526237c525d6fd94ae5fe2099853c63 | 15c589395992c179f02211b1c956fc15f1669cd6 | refs/heads/main | 2023-04-19T20:59:05.273000 | 2021-05-04T02:25:12 | 2021-05-04T02:25:12 | 364,117,489 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | import java.util.*;
class BinaryS {
public static int search(int[] arr, int key, int l, int h) {
int mid = (l + h) / 2;
if (h < l) {
return -1;
}
if (key == arr[mid]) {
return mid;
// If num is less then middle search lower half
} else if (key < arr[mid]) {
return search(arr, key, l, mid - 1);
// Otherwise search upper half of arr
} else {
return search(arr, key, mid + 1, h);
}
}
// Implemented my bubble sort.
public static int[] sort(int[] arr) {
int len = arr.length;
int swap = 0;
for (int i=0; i < len; i++) {
for (int j=1; j < (len-i); j++) {
if (arr[j-1] > arr[j]) {
// swap elements
swap = arr[j-1];
arr[j-1] = arr[j];
arr[j] = swap;
}
}
}
return arr;
}
public static void main(String args[]) {
// Initializations
int[] arr = {1, 4, 19, 2, 5, 77, 32, 34, 9, 11};
BinaryS b = new BinaryS();
int[] newArr = b.sort(arr);
int len = newArr.length - 1;
// Printing outputs to user
System.out.println("Array after sorting.\n");
System.out.println(Arrays.toString(newArr) + "\n");
int num = b.search(newArr, 19, 0, len);
System.out.println("Found at : " + num);
}
}
| UTF-8 | Java | 1,291 | java | BinaryS.java | Java | [] | null | [] | import java.util.*;
class BinaryS {
public static int search(int[] arr, int key, int l, int h) {
int mid = (l + h) / 2;
if (h < l) {
return -1;
}
if (key == arr[mid]) {
return mid;
// If num is less then middle search lower half
} else if (key < arr[mid]) {
return search(arr, key, l, mid - 1);
// Otherwise search upper half of arr
} else {
return search(arr, key, mid + 1, h);
}
}
// Implemented my bubble sort.
public static int[] sort(int[] arr) {
int len = arr.length;
int swap = 0;
for (int i=0; i < len; i++) {
for (int j=1; j < (len-i); j++) {
if (arr[j-1] > arr[j]) {
// swap elements
swap = arr[j-1];
arr[j-1] = arr[j];
arr[j] = swap;
}
}
}
return arr;
}
public static void main(String args[]) {
// Initializations
int[] arr = {1, 4, 19, 2, 5, 77, 32, 34, 9, 11};
BinaryS b = new BinaryS();
int[] newArr = b.sort(arr);
int len = newArr.length - 1;
// Printing outputs to user
System.out.println("Array after sorting.\n");
System.out.println(Arrays.toString(newArr) + "\n");
int num = b.search(newArr, 19, 0, len);
System.out.println("Found at : " + num);
}
}
| 1,291 | 0.508133 | 0.48567 | 69 | 17.710144 | 17.890245 | 62 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.652174 | false | false | 8 |
cb3201e6b1543515bd7a349841a0cc162e80da86 | 7,241,314,911,957 | 9ebe42f5d875b0fa65de4d2793841db9b6c50fb9 | /face/src/PartsOfSpeech.java | 3a369f408ea731163ab45609c0c661db1fd91b43 | [] | no_license | sakshikapoor/ChatBotAI | https://github.com/sakshikapoor/ChatBotAI | 43999348e1bbfa1949656b6b6bbcaef19803a53f | 1b9fc616b26eca20a40f2e89bd568c377e2dbec7 | refs/heads/master | 2021-08-31T13:23:13.533000 | 2017-12-21T13:00:44 | 2017-12-21T13:00:44 | 114,973,270 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class PartsOfSpeech {
public String part(String word) throws SQLException
{
String pt="";
// System.out.println(word);
Connection conn=null;
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
}
try {
conn = DriverManager
.getConnection("jdbc:mysql://localhost:3306/sessions?useSSL=false","root", "root");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
}
Statement st=conn.createStatement();
String select="select wordtype from entries where word='"+word+"';";
//st.execute(select);
ResultSet rs=st.executeQuery(select);
while(rs.next())
{
pt = rs.getString(1);
//System.out.println("xx"+pt+"xx");
}
return pt;
}
}
| UTF-8 | Java | 1,030 | java | PartsOfSpeech.java | Java | [] | null | [] |
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class PartsOfSpeech {
public String part(String word) throws SQLException
{
String pt="";
// System.out.println(word);
Connection conn=null;
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
}
try {
conn = DriverManager
.getConnection("jdbc:mysql://localhost:3306/sessions?useSSL=false","root", "root");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
}
Statement st=conn.createStatement();
String select="select wordtype from entries where word='"+word+"';";
//st.execute(select);
ResultSet rs=st.executeQuery(select);
while(rs.next())
{
pt = rs.getString(1);
//System.out.println("xx"+pt+"xx");
}
return pt;
}
}
| 1,030 | 0.646602 | 0.641748 | 47 | 20.893618 | 20.466095 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.829787 | false | false | 8 |
fd8d74865e14dbedd990c9608a5f94c6f40f8783 | 32,882,269,661,380 | c191bcce28471da87534c09eab303d0a6f659f68 | /gluecodium/src/test/resources/smoke/structs/output/android/com/example/smoke/Route.java | aef4b5fa4004dd7223f96c2b5baeab3a20fda6ce | [
"Apache-2.0"
] | permissive | Dschoordsch/gluecodium | https://github.com/Dschoordsch/gluecodium | 5652e88132e0f58a2ebff9e8872e60a7df804486 | a7b3833ce840284cadf968b6f8441888f970c134 | refs/heads/master | 2020-12-26T21:40:40.220000 | 2020-01-31T08:46:54 | 2020-01-31T08:46:54 | 237,653,099 | 1 | 0 | Apache-2.0 | true | 2020-02-01T17:44:34 | 2020-02-01T17:44:33 | 2020-01-31T08:46:58 | 2020-02-01T17:43:11 | 19,339 | 0 | 0 | 0 | null | false | false | /*
*
*/
package com.example.smoke;
import android.support.annotation.NonNull;
public final class Route {
public static final String DEFAULT_DESCRIPTION = "Nonsense";
public static final RouteType DEFAULT_TYPE = RouteType.EQUESTRIAN;
@NonNull
public String description;
@NonNull
public RouteType type;
public Route(@NonNull final String description, @NonNull final RouteType type) {
this.description = description;
this.type = type;
}
} | UTF-8 | Java | 486 | java | Route.java | Java | [] | null | [] | /*
*
*/
package com.example.smoke;
import android.support.annotation.NonNull;
public final class Route {
public static final String DEFAULT_DESCRIPTION = "Nonsense";
public static final RouteType DEFAULT_TYPE = RouteType.EQUESTRIAN;
@NonNull
public String description;
@NonNull
public RouteType type;
public Route(@NonNull final String description, @NonNull final RouteType type) {
this.description = description;
this.type = type;
}
} | 486 | 0.707819 | 0.707819 | 18 | 26.055555 | 24.721724 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 8 |
d6ec370793c97295062832002b6cb004014f3793 | 28,286,654,644,032 | 2060139ceb5b5871a248f1594e86fcb6e54e6675 | /NTClient/src/main/java/com/easy/ntclient/ssl/SSLHttpClient.java | 9278a11f4671d4a1ce85f9e9292f94b8e5e4546d | [] | no_license | tankmyb/EasyNT | https://github.com/tankmyb/EasyNT | 12ad22f585e27f7bbe94e8da1228cbe75b2247df | 943084192a5e36f526cdd48247d1e496ccb20656 | refs/heads/master | 2020-08-08T21:33:32.222000 | 2015-02-17T03:07:35 | 2015-02-17T03:07:35 | 30,899,505 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.easy.ntclient.ssl;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class SSLHttpClient {
private static String CLIENT_KEY_STORE = "sslclientkeys";
private static String CLIENT_TRUST_KEY_STORE = "sslclienttrust";
private static String CLIENT_KEY_STORE_PASSWORD = "client";
private static String CLIENT_TRUST_KEY_STORE_PASSWORD = "client";
private static String CLIENT_KEY_PASS = "client";
private CloseableHttpClient httpclient;
public SSLHttpClient(){
init();
}
private void init() {
InputStream instream = null;
InputStream keyStoreInput = null;
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore
.getDefaultType());
instream = SSLHttpClient.class
.getResourceAsStream(CLIENT_TRUST_KEY_STORE);
trustStore.load(instream,
CLIENT_TRUST_KEY_STORE_PASSWORD.toCharArray());
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStoreInput = SSLHttpClient.class
.getResourceAsStream(CLIENT_KEY_STORE);
keyStore.load(keyStoreInput,
CLIENT_KEY_STORE_PASSWORD.toCharArray());
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts
.custom()
.loadTrustMaterial(trustStore,
new TrustSelfSignedStrategy())
.loadKeyMaterial(keyStore, CLIENT_KEY_PASS.toCharArray())
.build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[] { "SSLv3" },
null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
httpclient = HttpClients.custom().setSSLSocketFactory(sslsf)
.build();
} catch (Exception e) {
} finally {
try {
if (instream != null) {
instream.close();
}
if (keyStoreInput != null) {
keyStoreInput.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public String get(String url){
String ret=null;
CloseableHttpResponse response=null;
HttpGet httpPost = new HttpGet(url);
//httpPost.setHeader("keepalive","false");
httpPost.setHeader("Connection", "close");
try {
response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
ret = EntityUtils.toString(entity, "UTF-8");
}
EntityUtils.consume(entity);
}catch(Exception e){
e.printStackTrace();
}finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
public final static void main(String[] args) throws Exception {
SSLHttpClient client = new SSLHttpClient();
String ret = client.get("https://127.0.0.1:8888/aa?name=1aaaaa");
System.out.println(ret);
}
}
| UTF-8 | Java | 3,275 | java | SSLHttpClient.java | Java | [
{
"context": "rivate static String CLIENT_KEY_STORE_PASSWORD = \"client\";\n\tprivate static String CLIENT_TRUST_KEY_STORE_P",
"end": 817,
"score": 0.9985419511795044,
"start": 811,
"tag": "PASSWORD",
"value": "client"
},
{
"context": " static String CLIENT_TRUST_KEY_STORE_PASSWORD =... | null | [] | package com.easy.ntclient.ssl;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class SSLHttpClient {
private static String CLIENT_KEY_STORE = "sslclientkeys";
private static String CLIENT_TRUST_KEY_STORE = "sslclienttrust";
private static String CLIENT_KEY_STORE_PASSWORD = "<PASSWORD>";
private static String CLIENT_TRUST_KEY_STORE_PASSWORD = "<PASSWORD>";
private static String CLIENT_KEY_PASS = "<PASSWORD>";
private CloseableHttpClient httpclient;
public SSLHttpClient(){
init();
}
private void init() {
InputStream instream = null;
InputStream keyStoreInput = null;
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore
.getDefaultType());
instream = SSLHttpClient.class
.getResourceAsStream(CLIENT_TRUST_KEY_STORE);
trustStore.load(instream,
CLIENT_TRUST_KEY_STORE_PASSWORD.toCharArray());
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStoreInput = SSLHttpClient.class
.getResourceAsStream(CLIENT_KEY_STORE);
keyStore.load(keyStoreInput,
CLIENT_KEY_STORE_PASSWORD.toCharArray());
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts
.custom()
.loadTrustMaterial(trustStore,
new TrustSelfSignedStrategy())
.loadKeyMaterial(keyStore, CLIENT_KEY_PASS.toCharArray())
.build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[] { "SSLv3" },
null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
httpclient = HttpClients.custom().setSSLSocketFactory(sslsf)
.build();
} catch (Exception e) {
} finally {
try {
if (instream != null) {
instream.close();
}
if (keyStoreInput != null) {
keyStoreInput.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public String get(String url){
String ret=null;
CloseableHttpResponse response=null;
HttpGet httpPost = new HttpGet(url);
//httpPost.setHeader("keepalive","false");
httpPost.setHeader("Connection", "close");
try {
response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
ret = EntityUtils.toString(entity, "UTF-8");
}
EntityUtils.consume(entity);
}catch(Exception e){
e.printStackTrace();
}finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return ret;
}
public final static void main(String[] args) throws Exception {
SSLHttpClient client = new SSLHttpClient();
String ret = client.get("https://127.0.0.1:8888/aa?name=1aaaaa");
System.out.println(ret);
}
}
| 3,287 | 0.715725 | 0.71145 | 110 | 28.772728 | 20.382105 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.963636 | false | false | 8 |
2828c6246860fe08b91d7585e511eb244488e1ee | 19,172,734,054,101 | 69de9958cbb9cd072eb837169d4d51afbfc84b0d | /cs/src/main/java/com/bsd/cse/zk/listbox/ZKListboxs.java | 6be6aa7e89307bd1b97c31e17394cb21f667f5ac | [] | no_license | bento0013/BB | https://github.com/bento0013/BB | 2bc7db95285eeba32669116cc3c27ece058d795a | caf52e18d3975818a40fafe6881d64b5ee2813be | refs/heads/master | 2016-09-05T13:46:07.169000 | 2014-11-22T17:49:32 | 2014-11-22T17:49:32 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.bsd.cse.zk.listbox;
import com.bsd.cse.model.security.Role;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listitem;
/**
*
* @author bento
*/
public class ZKListboxs {
private static Log LOG = LogFactory.getLog(ZKListboxs.class);
public static void addRoleToListbox(Set<Role> data,Listbox box)
{
for(Role role:data)
{
Listitem item = new Listitem(role.getRoleName(), role);
box.appendChild(item);
}
}
public static void removeRoleFromListbox(Set<Role> selRoles,Listbox src)
{
Set<Listitem> deleteItem = new HashSet<Listitem>();
for(Role role:selRoles)
{
List<Listitem> items = (List<Listitem>)src.getChildren();
for(Listitem item : items)
{
Role roleItem = (Role)item.getValue();
if(ObjectUtils.equals(roleItem.getId(), role.getId()))
{
deleteItem.add(item);
break;
}
}
}
src.getChildren().removeAll(deleteItem);
}
}
| UTF-8 | Java | 1,440 | java | ZKListboxs.java | Java | [
{
"context": "\nimport org.zkoss.zul.Listitem;\n\n/**\n *\n * @author bento\n */\npublic class ZKListboxs {\n private static ",
"end": 459,
"score": 0.9996222257614136,
"start": 454,
"tag": "USERNAME",
"value": "bento"
}
] | null | [] | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.bsd.cse.zk.listbox;
import com.bsd.cse.model.security.Role;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listitem;
/**
*
* @author bento
*/
public class ZKListboxs {
private static Log LOG = LogFactory.getLog(ZKListboxs.class);
public static void addRoleToListbox(Set<Role> data,Listbox box)
{
for(Role role:data)
{
Listitem item = new Listitem(role.getRoleName(), role);
box.appendChild(item);
}
}
public static void removeRoleFromListbox(Set<Role> selRoles,Listbox src)
{
Set<Listitem> deleteItem = new HashSet<Listitem>();
for(Role role:selRoles)
{
List<Listitem> items = (List<Listitem>)src.getChildren();
for(Listitem item : items)
{
Role roleItem = (Role)item.getValue();
if(ObjectUtils.equals(roleItem.getId(), role.getId()))
{
deleteItem.add(item);
break;
}
}
}
src.getChildren().removeAll(deleteItem);
}
}
| 1,440 | 0.594444 | 0.594444 | 52 | 26.692308 | 22.142492 | 76 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.480769 | false | false | 8 |
8e5bac58d0bd2cbd4d3a8bc97fc36f3de2a0d1dd | 8,100,308,384,712 | 91546d0f6dc26b59e9e18831d40222530b0f7bc5 | /app/src/main/java/com/etsdk/app/huov7/adapter/ServiceQqGroupAdapter.java | ac826c4bcc610cfd3a7c65d6624e197a73bca0c6 | [] | no_license | 18300602795/fxyouxi2 | https://github.com/18300602795/fxyouxi2 | 851bb0753c164020c4fa28e54868e9582811bf02 | 5d7c4a070282cfdcd57defd413706b9e178ff11c | refs/heads/master | 2020-03-14T00:59:00.990000 | 2018-04-28T03:19:14 | 2018-04-28T03:19:14 | 131,368,122 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.etsdk.app.huov7.adapter;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.etsdk.app.huov7.R;
import com.game.sdk.log.L;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by liu hong liang on 2017/3/1.
*/
public class ServiceQqGroupAdapter extends BaseAdapter {
private List<String> serviceQqGroupList = new ArrayList<>();
private String[] serviceQqGroupKey;
public List<String> getServiceQqGroupList() {
return serviceQqGroupList;
}
public void setServiceQqGroupList(String[] serviceQqGroupList, String[] qqgroupkey) {
for(String qqGroup: serviceQqGroupList){
this.serviceQqGroupList.add(qqGroup);
}
this.serviceQqGroupKey = qqgroupkey;
notifyDataSetChanged();
}
@Override
public int getCount() {
return serviceQqGroupList==null?0:serviceQqGroupList.size();
}
@Override
public Object getItem(int position) {
return serviceQqGroupList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.syz_item_qq_group, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final String serviceQq = serviceQqGroupList.get(position);
viewHolder.qqGroupIndex.setText((serviceQqGroupList.size()-position)+"");
viewHolder.tvQqGroupHint.setText("QQ群("+(position+1)+")");
viewHolder.qqGroupTV.setText(serviceQq);
L.i("333", "QQ群:" + serviceQqGroupKey[position]);
viewHolder.qqGroupStatus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if((position+1)<=serviceQqGroupKey.length){
joinQQGroup(v.getContext(),serviceQqGroupKey[position]);
}
}
});
// if("1".equals(serviceQq.getStatus())){
// viewHolder.qqGroupStatus.setText("已满");
// viewHolder.qqGroupStatus.setEnabled(false);
// viewHolder.qqGroupStatus.setClickable(false);
// }else{
viewHolder.qqGroupStatus.setText("申请加入");
viewHolder.qqGroupStatus.setEnabled(true);
viewHolder.qqGroupStatus.setClickable(true);
// }
return convertView;
}
class ViewHolder {
@BindView(R.id.qqGroupIndex)
TextView qqGroupIndex;
@BindView(R.id.linearLayout1)
LinearLayout linearLayout1;
@BindView(R.id.tv_qq_group_hint)
TextView tvQqGroupHint;
@BindView(R.id.qqGroupTV)
TextView qqGroupTV;
@BindView(R.id.qqGroupStatus)
Button qqGroupStatus;
ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
/****************
*
* 发起添加群流程。群号:测试群(594245585) 的 key 为: n62NA_2zzhPfmNicq-sZLioBGiN2v7Oq
* 调用 joinQQGroup(n62NA_2zzhPfmNicq-sZLioBGiN2v7Oq) 即可发起手Q客户端申请加群 测试群(594245585)
*
* @param key 由官网生成的key
* @return 返回true表示呼起手Q成功,返回fals表示呼起失败
******************/
public static boolean joinQQGroup(Context context,String key) {
Intent intent = new Intent();
intent.setData(Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D" + key));
// 此Flag可根据具体产品需要自定义,如设置,则在加群界面按返回,返回手Q主界面,不设置,按返回会返回到呼起产品界面 //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
try {
context.startActivity(intent);
return true;
} catch (Exception e) {
// 未安装手Q或安装的版本不支持
Toast.makeText(context,"未安装手Q或安装的版本不支持",Toast.LENGTH_SHORT).show();
return false;
}
}
}
| UTF-8 | Java | 4,719 | java | ServiceQqGroupAdapter.java | Java | [
{
"context": "import butterknife.ButterKnife;\n\n/**\n * Created by liu hong liang on 2017/3/1.\n */\n\npublic class ServiceQqGroupAdap",
"end": 585,
"score": 0.998361349105835,
"start": 571,
"tag": "NAME",
"value": "liu hong liang"
},
{
"context": "*\n *\n * 发起添加群流程。群号:测试群(5... | null | [] | package com.etsdk.app.huov7.adapter;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.etsdk.app.huov7.R;
import com.game.sdk.log.L;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created by <NAME> on 2017/3/1.
*/
public class ServiceQqGroupAdapter extends BaseAdapter {
private List<String> serviceQqGroupList = new ArrayList<>();
private String[] serviceQqGroupKey;
public List<String> getServiceQqGroupList() {
return serviceQqGroupList;
}
public void setServiceQqGroupList(String[] serviceQqGroupList, String[] qqgroupkey) {
for(String qqGroup: serviceQqGroupList){
this.serviceQqGroupList.add(qqGroup);
}
this.serviceQqGroupKey = qqgroupkey;
notifyDataSetChanged();
}
@Override
public int getCount() {
return serviceQqGroupList==null?0:serviceQqGroupList.size();
}
@Override
public Object getItem(int position) {
return serviceQqGroupList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.syz_item_qq_group, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final String serviceQq = serviceQqGroupList.get(position);
viewHolder.qqGroupIndex.setText((serviceQqGroupList.size()-position)+"");
viewHolder.tvQqGroupHint.setText("QQ群("+(position+1)+")");
viewHolder.qqGroupTV.setText(serviceQq);
L.i("333", "QQ群:" + serviceQqGroupKey[position]);
viewHolder.qqGroupStatus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if((position+1)<=serviceQqGroupKey.length){
joinQQGroup(v.getContext(),serviceQqGroupKey[position]);
}
}
});
// if("1".equals(serviceQq.getStatus())){
// viewHolder.qqGroupStatus.setText("已满");
// viewHolder.qqGroupStatus.setEnabled(false);
// viewHolder.qqGroupStatus.setClickable(false);
// }else{
viewHolder.qqGroupStatus.setText("申请加入");
viewHolder.qqGroupStatus.setEnabled(true);
viewHolder.qqGroupStatus.setClickable(true);
// }
return convertView;
}
class ViewHolder {
@BindView(R.id.qqGroupIndex)
TextView qqGroupIndex;
@BindView(R.id.linearLayout1)
LinearLayout linearLayout1;
@BindView(R.id.tv_qq_group_hint)
TextView tvQqGroupHint;
@BindView(R.id.qqGroupTV)
TextView qqGroupTV;
@BindView(R.id.qqGroupStatus)
Button qqGroupStatus;
ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
/****************
*
* 发起添加群流程。群号:测试群(594245585) 的 key 为: <KEY>
* 调用 joinQQGroup(n62NA_2zzhPfmNicq-sZLioBGiN2v7Oq) 即可发起手Q客户端申请加群 测试群(594245585)
*
* @param key 由官网生成的key
* @return 返回true表示呼起手Q成功,返回fals表示呼起失败
******************/
public static boolean joinQQGroup(Context context,String key) {
Intent intent = new Intent();
intent.setData(Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D" + key));
// 此Flag可根据具体产品需要自定义,如设置,则在加群界面按返回,返回手Q主界面,不设置,按返回会返回到呼起产品界面 //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
try {
context.startActivity(intent);
return true;
} catch (Exception e) {
// 未安装手Q或安装的版本不支持
Toast.makeText(context,"未安装手Q或安装的版本不支持",Toast.LENGTH_SHORT).show();
return false;
}
}
}
| 4,684 | 0.648228 | 0.634906 | 132 | 32.553032 | 27.014956 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.522727 | false | false | 8 |
5a30c8dccb2b56d5be05d73c21cca419c9fb4f35 | 29,472,065,610,138 | 3096be8bd93f21df539b0416135b72282203b974 | /03-builder-printer/src/main/java/com/hszy/sjms/builder/Builder.java | 71631d5105315ccc2e22c2deea19be62d18c4283 | [] | no_license | 37764844/design-pattern | https://github.com/37764844/design-pattern | afb0477f7714e0d4d0fe526627188a88e19de0da | 6a5adf08d52084074c2efe5bd34ed6ca2c27d4cb | refs/heads/master | 2022-12-30T21:40:11.769000 | 2020-10-24T07:16:39 | 2020-10-24T07:16:39 | 289,019,286 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hszy.sjms.builder;
import com.hszy.sjms.print.interfaces.ICode;
import com.hszy.sjms.print.interfaces.IProtocol;
import com.hszy.sjms.product.IProduct;
public interface Builder {
void builderCode(ICode code);
void builderProtocol(IProtocol protocol);
IProduct getPrinter();
}
| UTF-8 | Java | 303 | java | Builder.java | Java | [] | null | [] | package com.hszy.sjms.builder;
import com.hszy.sjms.print.interfaces.ICode;
import com.hszy.sjms.print.interfaces.IProtocol;
import com.hszy.sjms.product.IProduct;
public interface Builder {
void builderCode(ICode code);
void builderProtocol(IProtocol protocol);
IProduct getPrinter();
}
| 303 | 0.775578 | 0.775578 | 16 | 17.9375 | 18.219046 | 48 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.9375 | false | false | 8 |
7551daeafc3ed9a845ee4bb882d2504134f9d590 | 23,278,722,800,086 | e464ba80959460162464696bc24c4e164eb2e31a | /src/main/java/com/hunorkovacs/phy/GravityField.java | ea81009c622ba2bbf0f8f30835cb0ca2aa8c0e1f | [
"Apache-2.0"
] | permissive | kovacshuni/PHY | https://github.com/kovacshuni/PHY | 126dc03573f7122f51f8c7e6071704ee99ce24d6 | 6e5ee5d17bad0f020c6ca78060c718577fc8ac84 | refs/heads/master | 2020-05-27T13:57:56.838000 | 2014-11-28T11:08:25 | 2014-11-28T11:08:25 | 8,167,471 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.hunorkovacs.phy;
import java.util.Vector;
/**
* A uniform force field with constant magnitude and direction.
* <p>
* Its base structure is the same as the PointlikeBody.
* In addition it possesses a force vector g.
* Can move and be acted on by another force if its mass is declared to a nonzero value.
* Its method, calcuating the acting forces, had to be modified to function correctly.
* <p>
* @see PointlikeBody
*/
public class GravityField extends PointlikeBody
{
/**
* The g property of the force field. Its magnitude is measured in N*kg.
*/
private com.hunorkovacs.phy.Dimension g;
/**
* Perfect definition of the object, assigning mass, position, velocity, g, model and name.
* <p>
* It gets the main attributes, and also an instance of the PHYModel class.
* Very important to use this constructor and to specify the phymodel object.
* Otherwise the body will have no connection to other objects, declared
* to live inside a different system.
* @param m mass to be assigned
* @param p position to be assigned
* @param v speed to be assigned
* @param g g constant of the force field to be assigned
* @param phymodel the model object which holds all the other bodies
* @param name name to be assigned
*/
GravityField(double m, com.hunorkovacs.phy.Dimension p, com.hunorkovacs.phy.Dimension v, com.hunorkovacs.phy.Dimension g, PHYModel phymodel, String name)
{
super(m,p,v,phymodel,name);
this.g = g;
}
/**
* Returns the g property of the object.
* @return the vector holding x and y components of the force measured in N*kg.
*/
public com.hunorkovacs.phy.Dimension getG()
{
return g;
}
/**
* Sets the g property of the object.
* @param g the vector holding x and y components of the force measured in N*kg.
*/
public void setG(com.hunorkovacs.phy.Dimension g)
{
this.g = g;
}
/**
* Returns the applied force to a body with mass m.
* <p>
* proceeds by the formula F = m*g
* @param m the mass of the body to act on
* @return the force vector applied on the given body by this field
*/
public com.hunorkovacs.phy.Dimension act(double m)
{
return new com.hunorkovacs.phy.Dimension(g.getX()*m, g.getY()*m);
}
/**
* The modified version of the calulcateActingForces() from the PointlikeBody class for spaces.
* <p>
* I had to override this function because of the way the PointlikeBody caluclates forces.
* It involves checking forces that apply to this actual object. In case of a force,
* we should not consider the actual one as an acting force during the calculation.
* Otherwise each force would make itself accelerate.
*/
protected com.hunorkovacs.phy.Dimension calculateActingForces()
{
int i,j;
boolean identicalSets;
Vector bodyinris = new Vector();
Vector bodyinforce = new Vector();
com.hunorkovacs.phy.Dimension F = new com.hunorkovacs.phy.Dimension();
for (i=0; i<phymodel.getnRIS(); i++) if (isInsideRIS(p, phymodel.getRISAt(i))) bodyinris.add(phymodel.getRISAt(i));
outer: for (i=0; i<phymodel.getnGF(); i++){
GravityField gf = phymodel.getGFAt(i);
identicalSets = true;
for (j=0; j<phymodel.getnRIS(); j++){
RectangularIsolatorSpace ris = phymodel.getRISAt(j);
if ((isInsideRIS(gf.getPosition(), ris))^(isInsideRIS(p, ris))){
identicalSets = false;
continue outer;
}
}
if ((identicalSets)&&(!gf.equals(this))) bodyinforce.add(gf);
}
for (i=0; i<bodyinforce.size(); i++) F.setXY(F.getX()+((GravityField)bodyinforce.get(i)).act(m).getX(), F.getY()+((GravityField)bodyinforce.get(i)).act(m).getY());
return F;
}
}
| UTF-8 | Java | 4,106 | java | GravityField.java | Java | [] | null | [] | package com.hunorkovacs.phy;
import java.util.Vector;
/**
* A uniform force field with constant magnitude and direction.
* <p>
* Its base structure is the same as the PointlikeBody.
* In addition it possesses a force vector g.
* Can move and be acted on by another force if its mass is declared to a nonzero value.
* Its method, calcuating the acting forces, had to be modified to function correctly.
* <p>
* @see PointlikeBody
*/
public class GravityField extends PointlikeBody
{
/**
* The g property of the force field. Its magnitude is measured in N*kg.
*/
private com.hunorkovacs.phy.Dimension g;
/**
* Perfect definition of the object, assigning mass, position, velocity, g, model and name.
* <p>
* It gets the main attributes, and also an instance of the PHYModel class.
* Very important to use this constructor and to specify the phymodel object.
* Otherwise the body will have no connection to other objects, declared
* to live inside a different system.
* @param m mass to be assigned
* @param p position to be assigned
* @param v speed to be assigned
* @param g g constant of the force field to be assigned
* @param phymodel the model object which holds all the other bodies
* @param name name to be assigned
*/
GravityField(double m, com.hunorkovacs.phy.Dimension p, com.hunorkovacs.phy.Dimension v, com.hunorkovacs.phy.Dimension g, PHYModel phymodel, String name)
{
super(m,p,v,phymodel,name);
this.g = g;
}
/**
* Returns the g property of the object.
* @return the vector holding x and y components of the force measured in N*kg.
*/
public com.hunorkovacs.phy.Dimension getG()
{
return g;
}
/**
* Sets the g property of the object.
* @param g the vector holding x and y components of the force measured in N*kg.
*/
public void setG(com.hunorkovacs.phy.Dimension g)
{
this.g = g;
}
/**
* Returns the applied force to a body with mass m.
* <p>
* proceeds by the formula F = m*g
* @param m the mass of the body to act on
* @return the force vector applied on the given body by this field
*/
public com.hunorkovacs.phy.Dimension act(double m)
{
return new com.hunorkovacs.phy.Dimension(g.getX()*m, g.getY()*m);
}
/**
* The modified version of the calulcateActingForces() from the PointlikeBody class for spaces.
* <p>
* I had to override this function because of the way the PointlikeBody caluclates forces.
* It involves checking forces that apply to this actual object. In case of a force,
* we should not consider the actual one as an acting force during the calculation.
* Otherwise each force would make itself accelerate.
*/
protected com.hunorkovacs.phy.Dimension calculateActingForces()
{
int i,j;
boolean identicalSets;
Vector bodyinris = new Vector();
Vector bodyinforce = new Vector();
com.hunorkovacs.phy.Dimension F = new com.hunorkovacs.phy.Dimension();
for (i=0; i<phymodel.getnRIS(); i++) if (isInsideRIS(p, phymodel.getRISAt(i))) bodyinris.add(phymodel.getRISAt(i));
outer: for (i=0; i<phymodel.getnGF(); i++){
GravityField gf = phymodel.getGFAt(i);
identicalSets = true;
for (j=0; j<phymodel.getnRIS(); j++){
RectangularIsolatorSpace ris = phymodel.getRISAt(j);
if ((isInsideRIS(gf.getPosition(), ris))^(isInsideRIS(p, ris))){
identicalSets = false;
continue outer;
}
}
if ((identicalSets)&&(!gf.equals(this))) bodyinforce.add(gf);
}
for (i=0; i<bodyinforce.size(); i++) F.setXY(F.getX()+((GravityField)bodyinforce.get(i)).act(m).getX(), F.getY()+((GravityField)bodyinforce.get(i)).act(m).getY());
return F;
}
}
| 4,106 | 0.619338 | 0.618363 | 104 | 37.48077 | 35.109985 | 171 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.528846 | false | false | 8 |
c2ad3fe0ed2c2f66c45fc2211810e16497a4dd95 | 15,178,414,460,333 | bb2c241a49b1542e85e1e94c0d4daab5aab22113 | /lao-lu-web/src/main/java/com/ai/ge/client/controller/PayMain.java | 702cb98e9b9d1e23440d50120a0ab3859832d8a8 | [] | no_license | Johnnyhj/lao-lu-parent | https://github.com/Johnnyhj/lao-lu-parent | b6809229e4a229301335b0d5ab2bd1607c8ae631 | 3473f0348577a9ba01127cf165da75445e938aa1 | refs/heads/master | 2021-01-01T18:14:18.419000 | 2017-07-22T02:20:21 | 2017-07-22T02:20:21 | 98,282,656 | 1 | 0 | null | true | 2017-07-25T08:22:47 | 2017-07-25T08:22:47 | 2017-07-22T02:01:33 | 2017-07-22T02:20:48 | 7,954 | 0 | 0 | 0 | null | null | null | package com.ai.ge.client.controller;
import com.ai.ge.bus.core.AbilityConstant;
import com.ai.ge.bus.core.AbilityRegister;
import com.ai.ge.bus.core.IAbility;
import com.ai.ge.bus.core.Message;
import com.ai.ge.platform.service.pay.PayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
/**
* Created by wangying on 17/5/12.
*/
@Service
@AbilityRegister(name = "pay")
public class PayMain implements IAbility
{
private Logger logger = LoggerFactory.getLogger(PayMain.class);
@Resource
protected PayService payService;
/**
* 支付
* @param message
* @return
*/
@Override
public Message execute(Message message)
{
try {
//获取订单ID
String orderId = message.getParameter("orderId");
String rv = payService.pay(Long.parseLong(orderId),message.getRequest());
if(!"failed".equalsIgnoreCase(rv)) {
message.setBody(rv);
message.setView("pay/pay");
}
} catch (Exception e)
{
e.printStackTrace();
logger.error(e.getMessage());
message.setCode(AbilityConstant.R_ERROR_SYSTEM);
}
return message;
}
private String readParamFromRequest(HttpServletRequest request){
String rv = null;
try{
java.io.InputStream in = request.getInputStream();
int len = request.getContentLength();
byte [] buffer = new byte[len];
in.read(buffer);
rv = new String(buffer,"UTF-8");
logger.debug("【入参】\r\n" + rv);
}catch(Exception e){
logger.error("读取参数失败");
rv = null;
}
return rv;
}
}
| UTF-8 | Java | 1,896 | java | PayMain.java | Java | [
{
"context": "ervlet.http.HttpServletRequest;\n\n/**\n * Created by wangying on 17/5/12.\n */\n@Service\n@AbilityRegister(name = ",
"end": 457,
"score": 0.9995653033256531,
"start": 449,
"tag": "USERNAME",
"value": "wangying"
}
] | null | [] | package com.ai.ge.client.controller;
import com.ai.ge.bus.core.AbilityConstant;
import com.ai.ge.bus.core.AbilityRegister;
import com.ai.ge.bus.core.IAbility;
import com.ai.ge.bus.core.Message;
import com.ai.ge.platform.service.pay.PayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
/**
* Created by wangying on 17/5/12.
*/
@Service
@AbilityRegister(name = "pay")
public class PayMain implements IAbility
{
private Logger logger = LoggerFactory.getLogger(PayMain.class);
@Resource
protected PayService payService;
/**
* 支付
* @param message
* @return
*/
@Override
public Message execute(Message message)
{
try {
//获取订单ID
String orderId = message.getParameter("orderId");
String rv = payService.pay(Long.parseLong(orderId),message.getRequest());
if(!"failed".equalsIgnoreCase(rv)) {
message.setBody(rv);
message.setView("pay/pay");
}
} catch (Exception e)
{
e.printStackTrace();
logger.error(e.getMessage());
message.setCode(AbilityConstant.R_ERROR_SYSTEM);
}
return message;
}
private String readParamFromRequest(HttpServletRequest request){
String rv = null;
try{
java.io.InputStream in = request.getInputStream();
int len = request.getContentLength();
byte [] buffer = new byte[len];
in.read(buffer);
rv = new String(buffer,"UTF-8");
logger.debug("【入参】\r\n" + rv);
}catch(Exception e){
logger.error("读取参数失败");
rv = null;
}
return rv;
}
}
| 1,896 | 0.604614 | 0.600322 | 73 | 24.534246 | 20.623888 | 85 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.452055 | false | false | 8 |
1be75b6be9f26f44c2bdd80a5296b9b9da2675b6 | 24,129,126,296,438 | 1d2fda2245888413e3eef8798a61236822f022db | /org/flywaydb/core/internal/resolver/sql/SqlMigrationResolver.java | d11477ea7262dce89324a68f888208d1d2735e7a | [
"IJG"
] | permissive | SynieztroLedPar/Wu | https://github.com/SynieztroLedPar/Wu | 3b4391e916f6a5605d60663f800702f3e45d5dfc | 5f7daebc2fb430411ddb76a179005eeecde9802b | refs/heads/master | 2023-04-29T17:27:08.301000 | 2020-10-10T22:28:40 | 2020-10-10T22:28:40 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.flywaydb.core.internal.resolver.sql;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.zip.CRC32;
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.api.MigrationType;
import org.flywaydb.core.api.MigrationVersion;
import org.flywaydb.core.api.resolver.MigrationResolver;
import org.flywaydb.core.api.resolver.ResolvedMigration;
import org.flywaydb.core.internal.callback.SqlScriptFlywayCallback;
import org.flywaydb.core.internal.dbsupport.DbSupport;
import org.flywaydb.core.internal.resolver.MigrationInfoHelper;
import org.flywaydb.core.internal.resolver.ResolvedMigrationComparator;
import org.flywaydb.core.internal.resolver.ResolvedMigrationImpl;
import org.flywaydb.core.internal.util.Location;
import org.flywaydb.core.internal.util.Pair;
import org.flywaydb.core.internal.util.PlaceholderReplacer;
import org.flywaydb.core.internal.util.scanner.Resource;
import org.flywaydb.core.internal.util.scanner.Scanner;
public class SqlMigrationResolver
implements MigrationResolver
{
private final DbSupport dbSupport;
private final Scanner scanner;
private final Location location;
private final PlaceholderReplacer placeholderReplacer;
private final String encoding;
private final String sqlMigrationPrefix;
private final String repeatableSqlMigrationPrefix;
private final String sqlMigrationSeparator;
private final String sqlMigrationSuffix;
public SqlMigrationResolver(DbSupport dbSupport, Scanner scanner, Location location, PlaceholderReplacer placeholderReplacer, String encoding, String sqlMigrationPrefix, String repeatableSqlMigrationPrefix, String sqlMigrationSeparator, String sqlMigrationSuffix)
{
this.dbSupport = dbSupport;
this.scanner = scanner;
this.location = location;
this.placeholderReplacer = placeholderReplacer;
this.encoding = encoding;
this.sqlMigrationPrefix = sqlMigrationPrefix;
this.repeatableSqlMigrationPrefix = repeatableSqlMigrationPrefix;
this.sqlMigrationSeparator = sqlMigrationSeparator;
this.sqlMigrationSuffix = sqlMigrationSuffix;
}
public List<ResolvedMigration> resolveMigrations()
{
List<ResolvedMigration> migrations = new ArrayList();
scanForMigrations(migrations, this.sqlMigrationPrefix, this.sqlMigrationSeparator, this.sqlMigrationSuffix);
scanForMigrations(migrations, this.repeatableSqlMigrationPrefix, this.sqlMigrationSeparator, this.sqlMigrationSuffix);
Collections.sort(migrations, new ResolvedMigrationComparator());
return migrations;
}
public void scanForMigrations(List<ResolvedMigration> migrations, String prefix, String separator, String suffix)
{
for (Resource resource : this.scanner.scanForResources(this.location, prefix, suffix))
{
String filename = resource.getFilename();
if (!isSqlCallback(filename, suffix))
{
Pair<MigrationVersion, String> info = MigrationInfoHelper.extractVersionAndDescription(filename, prefix, separator, suffix);
ResolvedMigrationImpl migration = new ResolvedMigrationImpl();
migration.setVersion((MigrationVersion)info.getLeft());
migration.setDescription((String)info.getRight());
migration.setScript(extractScriptName(resource));
migration.setChecksum(Integer.valueOf(calculateChecksum(resource, resource.loadAsString(this.encoding))));
migration.setType(MigrationType.SQL);
migration.setPhysicalLocation(resource.getLocationOnDisk());
migration.setExecutor(new SqlMigrationExecutor(this.dbSupport, resource, this.placeholderReplacer, this.encoding));
migrations.add(migration);
}
}
}
static boolean isSqlCallback(String filename, String suffix)
{
String baseName = filename.substring(0, filename.length() - suffix.length());
return SqlScriptFlywayCallback.ALL_CALLBACKS.contains(baseName);
}
String extractScriptName(Resource resource)
{
if (this.location.getPath().isEmpty()) {
return resource.getLocation();
}
return resource.getLocation().substring(this.location.getPath().length() + 1);
}
static int calculateChecksum(Resource resource, String str)
{
CRC32 crc32 = new CRC32();
BufferedReader bufferedReader = new BufferedReader(new StringReader(str));
try
{
String line;
while ((line = bufferedReader.readLine()) != null) {
crc32.update(line.getBytes("UTF-8"));
}
}
catch (IOException e)
{
String message = "Unable to calculate checksum";
if (resource != null) {
message = message + " for " + resource.getLocation() + " (" + resource.getLocationOnDisk() + ")";
}
throw new FlywayException(message, e);
}
return (int)crc32.getValue();
}
}
/* Location: C:\Games\SteamLibrary\steamapps\common\Wurm Unlimited Dedicated Server\server.jar!\org\flywaydb\core\internal\resolver\sql\SqlMigrationResolver.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | UTF-8 | Java | 5,153 | java | SqlMigrationResolver.java | Java | [] | null | [] | package org.flywaydb.core.internal.resolver.sql;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.zip.CRC32;
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.api.MigrationType;
import org.flywaydb.core.api.MigrationVersion;
import org.flywaydb.core.api.resolver.MigrationResolver;
import org.flywaydb.core.api.resolver.ResolvedMigration;
import org.flywaydb.core.internal.callback.SqlScriptFlywayCallback;
import org.flywaydb.core.internal.dbsupport.DbSupport;
import org.flywaydb.core.internal.resolver.MigrationInfoHelper;
import org.flywaydb.core.internal.resolver.ResolvedMigrationComparator;
import org.flywaydb.core.internal.resolver.ResolvedMigrationImpl;
import org.flywaydb.core.internal.util.Location;
import org.flywaydb.core.internal.util.Pair;
import org.flywaydb.core.internal.util.PlaceholderReplacer;
import org.flywaydb.core.internal.util.scanner.Resource;
import org.flywaydb.core.internal.util.scanner.Scanner;
public class SqlMigrationResolver
implements MigrationResolver
{
private final DbSupport dbSupport;
private final Scanner scanner;
private final Location location;
private final PlaceholderReplacer placeholderReplacer;
private final String encoding;
private final String sqlMigrationPrefix;
private final String repeatableSqlMigrationPrefix;
private final String sqlMigrationSeparator;
private final String sqlMigrationSuffix;
public SqlMigrationResolver(DbSupport dbSupport, Scanner scanner, Location location, PlaceholderReplacer placeholderReplacer, String encoding, String sqlMigrationPrefix, String repeatableSqlMigrationPrefix, String sqlMigrationSeparator, String sqlMigrationSuffix)
{
this.dbSupport = dbSupport;
this.scanner = scanner;
this.location = location;
this.placeholderReplacer = placeholderReplacer;
this.encoding = encoding;
this.sqlMigrationPrefix = sqlMigrationPrefix;
this.repeatableSqlMigrationPrefix = repeatableSqlMigrationPrefix;
this.sqlMigrationSeparator = sqlMigrationSeparator;
this.sqlMigrationSuffix = sqlMigrationSuffix;
}
public List<ResolvedMigration> resolveMigrations()
{
List<ResolvedMigration> migrations = new ArrayList();
scanForMigrations(migrations, this.sqlMigrationPrefix, this.sqlMigrationSeparator, this.sqlMigrationSuffix);
scanForMigrations(migrations, this.repeatableSqlMigrationPrefix, this.sqlMigrationSeparator, this.sqlMigrationSuffix);
Collections.sort(migrations, new ResolvedMigrationComparator());
return migrations;
}
public void scanForMigrations(List<ResolvedMigration> migrations, String prefix, String separator, String suffix)
{
for (Resource resource : this.scanner.scanForResources(this.location, prefix, suffix))
{
String filename = resource.getFilename();
if (!isSqlCallback(filename, suffix))
{
Pair<MigrationVersion, String> info = MigrationInfoHelper.extractVersionAndDescription(filename, prefix, separator, suffix);
ResolvedMigrationImpl migration = new ResolvedMigrationImpl();
migration.setVersion((MigrationVersion)info.getLeft());
migration.setDescription((String)info.getRight());
migration.setScript(extractScriptName(resource));
migration.setChecksum(Integer.valueOf(calculateChecksum(resource, resource.loadAsString(this.encoding))));
migration.setType(MigrationType.SQL);
migration.setPhysicalLocation(resource.getLocationOnDisk());
migration.setExecutor(new SqlMigrationExecutor(this.dbSupport, resource, this.placeholderReplacer, this.encoding));
migrations.add(migration);
}
}
}
static boolean isSqlCallback(String filename, String suffix)
{
String baseName = filename.substring(0, filename.length() - suffix.length());
return SqlScriptFlywayCallback.ALL_CALLBACKS.contains(baseName);
}
String extractScriptName(Resource resource)
{
if (this.location.getPath().isEmpty()) {
return resource.getLocation();
}
return resource.getLocation().substring(this.location.getPath().length() + 1);
}
static int calculateChecksum(Resource resource, String str)
{
CRC32 crc32 = new CRC32();
BufferedReader bufferedReader = new BufferedReader(new StringReader(str));
try
{
String line;
while ((line = bufferedReader.readLine()) != null) {
crc32.update(line.getBytes("UTF-8"));
}
}
catch (IOException e)
{
String message = "Unable to calculate checksum";
if (resource != null) {
message = message + " for " + resource.getLocation() + " (" + resource.getLocationOnDisk() + ")";
}
throw new FlywayException(message, e);
}
return (int)crc32.getValue();
}
}
/* Location: C:\Games\SteamLibrary\steamapps\common\Wurm Unlimited Dedicated Server\server.jar!\org\flywaydb\core\internal\resolver\sql\SqlMigrationResolver.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 5,153 | 0.757811 | 0.753542 | 127 | 39.582676 | 38.674381 | 265 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.80315 | false | false | 8 |
d41b190baa5906f1cc59cf61754e01dc538421b6 | 2,903,397,952,120 | 39e779636338a05e5cb4ed9d55cffd15547dcdb1 | /BotreePosFnB/src/main/java/com/botree/restaurantapp/commonUtil/RefundBillPosPrinterMain.java | 864c99375817fec5cd2ec067bd8a83b507111566 | [] | no_license | sharobivpn/BotreeFnBServ | https://github.com/sharobivpn/BotreeFnBServ | fe0dcff3dce46b364f0e3acc6adcdce467508623 | 5b90a6970d14552a77349fad346f979f168c2a10 | refs/heads/main | 2023-08-05T09:02:31.394000 | 2021-09-18T03:44:02 | 2021-09-18T03:44:02 | 401,344,366 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /**
*
*/
package com.botree.restaurantapp.commonUtil;
/**
* @author admin
*
*/
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterJob;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaSizeName;
import javax.print.attribute.standard.OrientationRequested;
import com.botree.restaurantapp.dao.StoreAddressDAOImpl;
import com.botree.restaurantapp.dao.exception.DAOException;
import com.botree.restaurantapp.model.StoreMaster;
public class RefundBillPosPrinterMain {
/*
* public static void main(String[] args) { new PosPrinterMain().a(strName,
* secndStrng, thrdStrng, mapToHoldItems); }
*/
public void a(Object[] elements, int storeId) {
PageFormat format = new PageFormat();
Paper paper = new Paper();
StoreAddressDAOImpl addressDAOImpl = new StoreAddressDAOImpl();
double paperWidth = 3;// 3.25
double paperHeight = 3.69;// 11.69
double leftMargin = 0.12;
double rightMargin = 0.10;
double topMargin = 0;
double bottomMargin = 0.01;
StoreMaster store =null;
paper.setSize(paperWidth * 200, paperHeight * 200);
paper.setImageableArea(leftMargin * 200, topMargin * 200, (paperWidth
- leftMargin - rightMargin) * 200,
(paperHeight - topMargin - bottomMargin) * 200);
format.setPaper(paper);
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(OrientationRequested.PORTRAIT);
PrinterJob printerJob = PrinterJob.getPrinterJob();
RefundBillPrint printable = new RefundBillPrint();
RefundBillPrintArabic billPrintArabic=new RefundBillPrintArabic();
try {
store = addressDAOImpl.getStoreByStoreId(storeId);
if(store.getPrintBillPaperSize().equalsIgnoreCase("2100.00")){
aset.add(MediaSizeName.ISO_A4);
RefundBillPrintA4 printableA4 = new RefundBillPrintA4();
printableA4.setPrintData(elements, storeId);
printerJob.setPrintable(printableA4);
}
else {
aset.add(MediaSizeName.ISO_B0);
if(store.getIsArabicBill().equalsIgnoreCase("Y")){
billPrintArabic.setPrintData(elements, storeId);
printerJob.setPrintable(billPrintArabic);
}
else {
printable.setPrintData(elements, storeId);
printerJob.setPrintable(printable);
}
}
} catch (DAOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
System.out.println("Refund Print job...");
printerJob.print(aset);
} catch (Exception e) {
e.printStackTrace();
}
// System.out.println("kitchen printer name:: "+printerJob.getPrintService().getName());
/*
* //non-default printer
*/
//
}
}
| UTF-8 | Java | 2,842 | java | RefundBillPosPrinterMain.java | Java | [
{
"context": "otree.restaurantapp.commonUtil;\r\n\r\n/**\r\n * @author admin\r\n *\r\n */\r\n\r\n\r\nimport java.awt.print.PageFormat;\r\n",
"end": 84,
"score": 0.9401752948760986,
"start": 79,
"tag": "USERNAME",
"value": "admin"
}
] | null | [] | /**
*
*/
package com.botree.restaurantapp.commonUtil;
/**
* @author admin
*
*/
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterJob;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaSizeName;
import javax.print.attribute.standard.OrientationRequested;
import com.botree.restaurantapp.dao.StoreAddressDAOImpl;
import com.botree.restaurantapp.dao.exception.DAOException;
import com.botree.restaurantapp.model.StoreMaster;
public class RefundBillPosPrinterMain {
/*
* public static void main(String[] args) { new PosPrinterMain().a(strName,
* secndStrng, thrdStrng, mapToHoldItems); }
*/
public void a(Object[] elements, int storeId) {
PageFormat format = new PageFormat();
Paper paper = new Paper();
StoreAddressDAOImpl addressDAOImpl = new StoreAddressDAOImpl();
double paperWidth = 3;// 3.25
double paperHeight = 3.69;// 11.69
double leftMargin = 0.12;
double rightMargin = 0.10;
double topMargin = 0;
double bottomMargin = 0.01;
StoreMaster store =null;
paper.setSize(paperWidth * 200, paperHeight * 200);
paper.setImageableArea(leftMargin * 200, topMargin * 200, (paperWidth
- leftMargin - rightMargin) * 200,
(paperHeight - topMargin - bottomMargin) * 200);
format.setPaper(paper);
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(OrientationRequested.PORTRAIT);
PrinterJob printerJob = PrinterJob.getPrinterJob();
RefundBillPrint printable = new RefundBillPrint();
RefundBillPrintArabic billPrintArabic=new RefundBillPrintArabic();
try {
store = addressDAOImpl.getStoreByStoreId(storeId);
if(store.getPrintBillPaperSize().equalsIgnoreCase("2100.00")){
aset.add(MediaSizeName.ISO_A4);
RefundBillPrintA4 printableA4 = new RefundBillPrintA4();
printableA4.setPrintData(elements, storeId);
printerJob.setPrintable(printableA4);
}
else {
aset.add(MediaSizeName.ISO_B0);
if(store.getIsArabicBill().equalsIgnoreCase("Y")){
billPrintArabic.setPrintData(elements, storeId);
printerJob.setPrintable(billPrintArabic);
}
else {
printable.setPrintData(elements, storeId);
printerJob.setPrintable(printable);
}
}
} catch (DAOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
System.out.println("Refund Print job...");
printerJob.print(aset);
} catch (Exception e) {
e.printStackTrace();
}
// System.out.println("kitchen printer name:: "+printerJob.getPrintService().getName());
/*
* //non-default printer
*/
//
}
}
| 2,842 | 0.694933 | 0.675932 | 107 | 24.560747 | 23.7397 | 90 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.224299 | false | false | 8 |
d770e16846c935be57e5976f2a55beb41cb6937c | 10,118,943,004,125 | bfca14f3a8f26f817acb5e3abc9479390017a50a | /devemu-realm/src/main/java/org/devemu/utils/queue/QueueManager.java | bb895a80690955ecf31a503a6311433261a99d29 | [] | no_license | adheen/DevEmu_Project | https://github.com/adheen/DevEmu_Project | b77d0f667bb941ed18f64b6233f1a86df9ab4f70 | 3a005b8ae0229721dda11c51314d4e08a5f13693 | refs/heads/master | 2021-01-18T12:48:15.363000 | 2013-06-08T10:48:46 | 2013-06-08T10:48:46 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package org.devemu.utils.queue;
import org.devemu.network.server.client.ClientManager;
import org.devemu.network.server.client.RealmClient;
import org.devemu.sql.entity.manager.AccountManager;
public class QueueManager implements Runnable {
//private Thread thread;
public QueueManager() {
/*thread = new Thread(this);
thread.setDaemon(true);
thread.start();*/
}
@Override
public void run() {
RealmClient loc0 = QueueSelector.getFirst();
if(loc0 != null) {
boolean loc1 = AccountManager.getAboTime(loc0.getAcc()) > 0;
QueueSelector.removeFromQueue(loc0.getQueue(),loc1);
ClientManager.onStat(loc0);
}
/*while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
RealmClient loc0 = QueueSelector.getFirst();
if(loc0 != null) {
boolean loc1 = AccountManager.getAboTime(loc0.getAcc()) > 0;
QueueSelector.removeFromQueue(loc0.getQueue(),loc1);
ClientManager.onStat(loc0);
}
}*/
}
}
| UTF-8 | Java | 992 | java | QueueManager.java | Java | [] | null | [] | package org.devemu.utils.queue;
import org.devemu.network.server.client.ClientManager;
import org.devemu.network.server.client.RealmClient;
import org.devemu.sql.entity.manager.AccountManager;
public class QueueManager implements Runnable {
//private Thread thread;
public QueueManager() {
/*thread = new Thread(this);
thread.setDaemon(true);
thread.start();*/
}
@Override
public void run() {
RealmClient loc0 = QueueSelector.getFirst();
if(loc0 != null) {
boolean loc1 = AccountManager.getAboTime(loc0.getAcc()) > 0;
QueueSelector.removeFromQueue(loc0.getQueue(),loc1);
ClientManager.onStat(loc0);
}
/*while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
RealmClient loc0 = QueueSelector.getFirst();
if(loc0 != null) {
boolean loc1 = AccountManager.getAboTime(loc0.getAcc()) > 0;
QueueSelector.removeFromQueue(loc0.getQueue(),loc1);
ClientManager.onStat(loc0);
}
}*/
}
}
| 992 | 0.703629 | 0.683468 | 38 | 25.105263 | 20.057535 | 64 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.394737 | false | false | 8 |
6ae15140eb2b86c9953e8add9da0e04f8d14c32a | 31,937,376,838,340 | 6edda2798e8e542712018cb375579a4bd9f64161 | /mobile_app/app/src/main/java/comp3888/group5/sensordatacollector/PhoneBootReceiver.java | ceea06d0a8a10d097051caf9f85f8792bf24ef23 | [
"MIT"
] | permissive | Leaguesss/Platform-for-Collecting-IoT-Data | https://github.com/Leaguesss/Platform-for-Collecting-IoT-Data | b0ebe71d2dc7d3c527fd7dedaac21d6b73b57069 | d31db5e152531b5039e212615110dd4e7099721b | refs/heads/main | 2023-01-28T05:07:07.681000 | 2020-12-07T12:18:27 | 2020-12-07T12:18:27 | 319,307,881 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package comp3888.group5.sensordatacollector;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
public class PhoneBootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent arg1) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Intent intent = new Intent(context, SensorListenService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent);
} else {
context.startService(intent);
}
Log.i("Autostart", "started");
}
}
| UTF-8 | Java | 747 | java | PhoneBootReceiver.java | Java | [] | null | [] | package comp3888.group5.sensordatacollector;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
public class PhoneBootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent arg1) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Intent intent = new Intent(context, SensorListenService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent);
} else {
context.startService(intent);
}
Log.i("Autostart", "started");
}
}
| 747 | 0.697456 | 0.689424 | 23 | 31.47826 | 23.329157 | 78 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.565217 | false | false | 8 |
a98125eb52e640840c470891b973a58fe6d70046 | 22,591,527,991,740 | eb04182d6b3cb19f3de949bce76668b80842f88c | /src/main/java/com/erikmelker/currencyconverter/domain/Exchange.java | d32615bd79b1bbf1a9c42b82fab9a419a8f7c3e9 | [] | no_license | MelkerMossberg/currencyconverter | https://github.com/MelkerMossberg/currencyconverter | f8ec881b5017405af23bc647815f767b22b15483 | 8287e65026c2074600beb9ba977ed5c52cb2fcc6 | refs/heads/master | 2022-09-26T07:30:10.388000 | 2019-12-12T10:47:46 | 2019-12-12T10:47:46 | 227,421,335 | 0 | 0 | null | false | 2022-09-22T18:59:25 | 2019-12-11T17:20:32 | 2019-12-13T12:03:12 | 2022-09-22T18:59:23 | 106 | 0 | 0 | 1 | Java | false | false | package com.erikmelker.currencyconverter.domain;
import lombok.Data;
import java.math.BigDecimal;
import java.math.RoundingMode;
@Data
public class Exchange {
private String amount;
private String fromCurr;
private String toCurr;
private String res;
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getFromCurr() {
return fromCurr;
}
public void setFromCurr(String fromCurr) {
this.fromCurr = fromCurr;
}
public String getToCurr() {
return toCurr;
}
public void setToCurr(String toCurr) {
this.toCurr = toCurr;
}
public String getRes() {
return amount;
}
public void setRes(String toCurr) {
this.toCurr = toCurr;
}
public void setRes(BigDecimal fromPrice, BigDecimal toPrice) {
System.out.println("HIT");
BigDecimal fromDiv = fromPrice.divide(new BigDecimal(amount),4 ,RoundingMode.CEILING);
BigDecimal toDivDiv = toPrice.divide(new BigDecimal(amount),4 ,RoundingMode.CEILING);
this.res = String.valueOf((fromDiv.subtract(toDivDiv)).multiply(fromPrice));
System.out.println("Res is actually: " + res);
}
}
| UTF-8 | Java | 1,283 | java | Exchange.java | Java | [
{
"context": "package com.erikmelker.currencyconverter.domain;\n\nimport lombok.Data;\n\ni",
"end": 22,
"score": 0.9379133582115173,
"start": 12,
"tag": "USERNAME",
"value": "erikmelker"
}
] | null | [] | package com.erikmelker.currencyconverter.domain;
import lombok.Data;
import java.math.BigDecimal;
import java.math.RoundingMode;
@Data
public class Exchange {
private String amount;
private String fromCurr;
private String toCurr;
private String res;
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getFromCurr() {
return fromCurr;
}
public void setFromCurr(String fromCurr) {
this.fromCurr = fromCurr;
}
public String getToCurr() {
return toCurr;
}
public void setToCurr(String toCurr) {
this.toCurr = toCurr;
}
public String getRes() {
return amount;
}
public void setRes(String toCurr) {
this.toCurr = toCurr;
}
public void setRes(BigDecimal fromPrice, BigDecimal toPrice) {
System.out.println("HIT");
BigDecimal fromDiv = fromPrice.divide(new BigDecimal(amount),4 ,RoundingMode.CEILING);
BigDecimal toDivDiv = toPrice.divide(new BigDecimal(amount),4 ,RoundingMode.CEILING);
this.res = String.valueOf((fromDiv.subtract(toDivDiv)).multiply(fromPrice));
System.out.println("Res is actually: " + res);
}
}
| 1,283 | 0.652377 | 0.650818 | 54 | 22.75926 | 23.330107 | 94 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.481481 | false | false | 8 |
db181912bd0cc8c1c60875eecd1083734f5349d2 | 30,133,490,605,525 | 1d62594990eac09c6eda5d8117fdb71aa77c9378 | /src/main/java/com/example/spring/repository/EmpresaRepository.java | 129b0e026c20d30da5bca131d46913918755486a | [] | no_license | joseant8/usuario_empresa | https://github.com/joseant8/usuario_empresa | ad36925ccb96f7d18687d574378dc111a6da6d4a | 04b3fa11d8c668011db98f1be21dec5f5c7b7577 | refs/heads/master | 2023-03-28T04:46:44.007000 | 2021-04-06T23:04:40 | 2021-04-06T23:04:40 | 354,959,675 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.spring.repository;
import com.example.spring.model.Empresa;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface EmpresaRepository extends JpaRepository<Empresa, Long> {
// https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#reference
Optional<Empresa> findByNombre(String nombre);
}
| UTF-8 | Java | 452 | java | EmpresaRepository.java | Java | [] | null | [] | package com.example.spring.repository;
import com.example.spring.model.Empresa;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface EmpresaRepository extends JpaRepository<Empresa, Long> {
// https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#reference
Optional<Empresa> findByNombre(String nombre);
}
| 452 | 0.800885 | 0.800885 | 19 | 22.789474 | 28.079922 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.368421 | false | false | 8 |
59606a6ee2c3ef61333fef8868dbe9117c0890c8 | 15,427,522,528,933 | ee69a1640c9a2fe6b9ab7dcaeca8875b16aaa2e0 | /system/lazyat/sys/core/Server.java | ca366825231ed9f70aa4087368e3129341141c15 | [] | no_license | hanviseas/ATHENA | https://github.com/hanviseas/ATHENA | c34e67eb627d8868a8cb01cf97d93bae8f7ec88f | e49ac7aa72aa75d8206ba45cfba0f5613b7246ae | refs/heads/master | 2016-06-06T14:06:37.938000 | 2016-02-05T07:30:17 | 2016-02-05T07:30:17 | 49,465,338 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package lazyat.sys.core;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import lazyat.sys.map.ConfigMap;
public final class Server extends Thread {
/**
* main: 程序入口
* @param args 参数列表
* @return void
*/
public static void main(String[] args) {
Server.commander = new Commander();
commander.dispatch();
}
/**
* commander: 测试指挥官
*/
private static Commander commander = null;
public static Commander getCommander() {
return commander;
}
/**
* runMode: 测试运行模式
*/
private static String runMode = initRunMode();
public static String getRunMode() {
return runMode;
}
/**
* initRunMode: 初始化测试运行模式
* @return runMode 测试运行模式
*/
private static String initRunMode() {
String runMode = "local";
try { // 读取配置错误时,默认设为local
runMode = ConfigMap.getMap().get("normal").get("mode");
runMode = runMode.equals("") ? "local" : runMode;
} catch (Exception e) { // 配置错误
e.printStackTrace();
}
return runMode;
}
/**
* remoteHost: 远程服务位置
*/
private static String remoteHost = initRemoteHost();
public static String getRemoteHost() {
return remoteHost;
}
/**
* initRemoteHost: 初始化远程服务位置
* @return remoteHost 远程服务位置
*/
private static String initRemoteHost() {
String remoteHost = "127.0.0.1:4444";
try { // 读取配置错误时,默认设为本地默认端口
remoteHost = ConfigMap.getMap().get("normal").get("remote");
remoteHost = remoteHost.equals("") ? "127.0.0.1:4444" : remoteHost;
} catch (Exception e) { // 配置错误
e.printStackTrace();
}
return remoteHost;
}
/**
* pageLoadTimeout: 页面超时时间(秒)
*/
private static Integer pageLoadTimeout = initPageLoadTimeout();
public static Integer getPageLoadTimeout() {
return pageLoadTimeout;
}
/**
* initPageLoadTimeout: 初始化页面超时时间
* @return pageLoadTimeout 页面超时时间
*/
private static Integer initPageLoadTimeout() {
Integer pageLoadTimeout = 30;
try { // 读取配置错误时,默认设为30秒
pageLoadTimeout = Integer.parseInt(ConfigMap.getMap().get("timeout").get("page"));
} catch (Exception e) { // 配置错误
e.printStackTrace();
}
return pageLoadTimeout;
}
/**
* scriptTimeout: 脚本超时时间(秒)
*/
private static Integer scriptTimeout = initScriptTimeout();
public static Integer getScriptTimeout() {
return scriptTimeout;
}
/**
* initScriptTimeout: 初始化脚本超时时间
* @return scriptTimeout 脚本超时时间
*/
private static Integer initScriptTimeout() {
Integer scriptTimeout = 30;
try { // 读取配置错误时,默认设为30秒
scriptTimeout = Integer.parseInt(ConfigMap.getMap().get("timeout").get("script"));
} catch (Exception e) { // 配置错误
e.printStackTrace();
}
return scriptTimeout;
}
/**
* implicitlyWait: 等待超时时间(秒)
*/
private static Integer implicitlyWait = initImplicitlyWait();
public static Integer getImplicitlyWait() {
return implicitlyWait;
}
/**
* initImplicitlyWait: 初始化等待超时时间
* @return implicitlyWait 等待超时时间
*/
private static Integer initImplicitlyWait() {
Integer implicitlyWait = 10;
try { // 读取配置错误时,默认设为10秒
implicitlyWait = Integer.parseInt(ConfigMap.getMap().get("timeout").get("implicitness"));
} catch (Exception e) { // 配置错误
e.printStackTrace();
}
return implicitlyWait;
}
/**
* generateId: 生成唯一标识号
* @return id 唯一标识号
*/
public static String generateId() {
String time = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date());
String rand = String.format("%04d", new Random().nextInt(9999));
return time + "-" + rand;
}
/**
* currentTime: 当前时间
* @return time 当前时间
*/
public static String currentTime() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
}
}
| UTF-8 | Java | 4,082 | java | Server.java | Java | [
{
"context": " String initRemoteHost() {\n\t\tString remoteHost = \"127.0.0.1:4444\";\n\t\ttry { // 读取配置错误时,默认设为本地默认端口\n\t\t\tremoteHos",
"end": 1292,
"score": 0.9997629523277283,
"start": 1283,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "emote\");\n\t\t\tremoteHost = ... | null | [] | package lazyat.sys.core;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import lazyat.sys.map.ConfigMap;
public final class Server extends Thread {
/**
* main: 程序入口
* @param args 参数列表
* @return void
*/
public static void main(String[] args) {
Server.commander = new Commander();
commander.dispatch();
}
/**
* commander: 测试指挥官
*/
private static Commander commander = null;
public static Commander getCommander() {
return commander;
}
/**
* runMode: 测试运行模式
*/
private static String runMode = initRunMode();
public static String getRunMode() {
return runMode;
}
/**
* initRunMode: 初始化测试运行模式
* @return runMode 测试运行模式
*/
private static String initRunMode() {
String runMode = "local";
try { // 读取配置错误时,默认设为local
runMode = ConfigMap.getMap().get("normal").get("mode");
runMode = runMode.equals("") ? "local" : runMode;
} catch (Exception e) { // 配置错误
e.printStackTrace();
}
return runMode;
}
/**
* remoteHost: 远程服务位置
*/
private static String remoteHost = initRemoteHost();
public static String getRemoteHost() {
return remoteHost;
}
/**
* initRemoteHost: 初始化远程服务位置
* @return remoteHost 远程服务位置
*/
private static String initRemoteHost() {
String remoteHost = "127.0.0.1:4444";
try { // 读取配置错误时,默认设为本地默认端口
remoteHost = ConfigMap.getMap().get("normal").get("remote");
remoteHost = remoteHost.equals("") ? "127.0.0.1:4444" : remoteHost;
} catch (Exception e) { // 配置错误
e.printStackTrace();
}
return remoteHost;
}
/**
* pageLoadTimeout: 页面超时时间(秒)
*/
private static Integer pageLoadTimeout = initPageLoadTimeout();
public static Integer getPageLoadTimeout() {
return pageLoadTimeout;
}
/**
* initPageLoadTimeout: 初始化页面超时时间
* @return pageLoadTimeout 页面超时时间
*/
private static Integer initPageLoadTimeout() {
Integer pageLoadTimeout = 30;
try { // 读取配置错误时,默认设为30秒
pageLoadTimeout = Integer.parseInt(ConfigMap.getMap().get("timeout").get("page"));
} catch (Exception e) { // 配置错误
e.printStackTrace();
}
return pageLoadTimeout;
}
/**
* scriptTimeout: 脚本超时时间(秒)
*/
private static Integer scriptTimeout = initScriptTimeout();
public static Integer getScriptTimeout() {
return scriptTimeout;
}
/**
* initScriptTimeout: 初始化脚本超时时间
* @return scriptTimeout 脚本超时时间
*/
private static Integer initScriptTimeout() {
Integer scriptTimeout = 30;
try { // 读取配置错误时,默认设为30秒
scriptTimeout = Integer.parseInt(ConfigMap.getMap().get("timeout").get("script"));
} catch (Exception e) { // 配置错误
e.printStackTrace();
}
return scriptTimeout;
}
/**
* implicitlyWait: 等待超时时间(秒)
*/
private static Integer implicitlyWait = initImplicitlyWait();
public static Integer getImplicitlyWait() {
return implicitlyWait;
}
/**
* initImplicitlyWait: 初始化等待超时时间
* @return implicitlyWait 等待超时时间
*/
private static Integer initImplicitlyWait() {
Integer implicitlyWait = 10;
try { // 读取配置错误时,默认设为10秒
implicitlyWait = Integer.parseInt(ConfigMap.getMap().get("timeout").get("implicitness"));
} catch (Exception e) { // 配置错误
e.printStackTrace();
}
return implicitlyWait;
}
/**
* generateId: 生成唯一标识号
* @return id 唯一标识号
*/
public static String generateId() {
String time = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date());
String rand = String.format("%04d", new Random().nextInt(9999));
return time + "-" + rand;
}
/**
* currentTime: 当前时间
* @return time 当前时间
*/
public static String currentTime() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
}
}
| 4,082 | 0.680886 | 0.67036 | 164 | 21.012196 | 20.630308 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.469512 | false | false | 8 |
ebed8c09980e8dc4b32e4201e50a718c78943669 | 14,413,910,275,245 | 048f568697732020b4a5f8ca774db022dae9056a | /src/main/java/com/codeleven/config/ConfigInfoManager.java | 7c30cab7fb33f935f107539a5a50d3b8b8848154 | [] | no_license | CoDeleven/php-swagger-yapi-integration-plugin | https://github.com/CoDeleven/php-swagger-yapi-integration-plugin | 07e3640f7af89e950ca9f4ee936316d5b3013dbd | 1fe4b5385143a9380eafea0e326d591a102d7b53 | refs/heads/master | 2022-12-26T12:42:31.956000 | 2020-10-13T09:05:24 | 2020-10-13T09:05:24 | 281,284,089 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.codeleven.config;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.project.Project;
import static com.codeleven.config.YApiServerConfig.*;
public class ConfigInfoManager {
private static ConfigInfoManager instance;
private ConfigInfo configInfo;
private PropertiesComponent propertiesComponent;
private ConfigInfoManager(Project project) {
this.propertiesComponent = PropertiesComponent.getInstance(project);
this.configInfo = ConfigInfo.getInstance();
this.updateConfigInfo();
}
public static ConfigInfoManager getInstance(Project project) {
if (instance == null) {
instance = new ConfigInfoManager(project);
}
return instance;
}
public void updateConfigInfo() {
this.configInfo.setProjectToken(propertiesComponent.getValue(CONFIG_KEY_YAPI_PROJECT_TOKEN, ""));
this.configInfo.setSwaggerExecutablePath(propertiesComponent.getValue(CONFIG_KEY_SWAGGER_EXECUTABLE_PATH, ""));
this.configInfo.setSwaggerScanPath(propertiesComponent.getValue(CONFIG_KEY_SWAGGER_SCAN_PATH, ""));
this.configInfo.setYapiServerHost(propertiesComponent.getValue(CONFIG_KEY_YAPI_SERVER_HOST, ""));
this.configInfo.setSwaggerResultSavePath(propertiesComponent.getValue(CONFIG_KEY_SWAGGER_RESULT_SAVE_PATH, ""));
this.configInfo.setEnableDebug(Boolean.valueOf(propertiesComponent.getValue(CONFIG_KEY_YAPI_ENABLE_DEBUG, "")));
}
public void updateProperty(String propertyKey, String propertyValue) {
propertiesComponent.setValue(propertyKey, propertyValue);
this.updateConfigInfo();
}
public boolean isChanged(String propertyKey, String yourValue) {
String persistenceValue = propertiesComponent.getValue(propertyKey, "");
return !persistenceValue.equals(yourValue);
}
public String getProperty(String propertyKey, String defaultValue) {
return propertiesComponent.getValue(propertyKey, defaultValue);
}
public ConfigInfo getConfigInfo() {
return configInfo;
}
}
| UTF-8 | Java | 2,110 | java | ConfigInfoManager.java | Java | [] | null | [] | package com.codeleven.config;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.project.Project;
import static com.codeleven.config.YApiServerConfig.*;
public class ConfigInfoManager {
private static ConfigInfoManager instance;
private ConfigInfo configInfo;
private PropertiesComponent propertiesComponent;
private ConfigInfoManager(Project project) {
this.propertiesComponent = PropertiesComponent.getInstance(project);
this.configInfo = ConfigInfo.getInstance();
this.updateConfigInfo();
}
public static ConfigInfoManager getInstance(Project project) {
if (instance == null) {
instance = new ConfigInfoManager(project);
}
return instance;
}
public void updateConfigInfo() {
this.configInfo.setProjectToken(propertiesComponent.getValue(CONFIG_KEY_YAPI_PROJECT_TOKEN, ""));
this.configInfo.setSwaggerExecutablePath(propertiesComponent.getValue(CONFIG_KEY_SWAGGER_EXECUTABLE_PATH, ""));
this.configInfo.setSwaggerScanPath(propertiesComponent.getValue(CONFIG_KEY_SWAGGER_SCAN_PATH, ""));
this.configInfo.setYapiServerHost(propertiesComponent.getValue(CONFIG_KEY_YAPI_SERVER_HOST, ""));
this.configInfo.setSwaggerResultSavePath(propertiesComponent.getValue(CONFIG_KEY_SWAGGER_RESULT_SAVE_PATH, ""));
this.configInfo.setEnableDebug(Boolean.valueOf(propertiesComponent.getValue(CONFIG_KEY_YAPI_ENABLE_DEBUG, "")));
}
public void updateProperty(String propertyKey, String propertyValue) {
propertiesComponent.setValue(propertyKey, propertyValue);
this.updateConfigInfo();
}
public boolean isChanged(String propertyKey, String yourValue) {
String persistenceValue = propertiesComponent.getValue(propertyKey, "");
return !persistenceValue.equals(yourValue);
}
public String getProperty(String propertyKey, String defaultValue) {
return propertiesComponent.getValue(propertyKey, defaultValue);
}
public ConfigInfo getConfigInfo() {
return configInfo;
}
}
| 2,110 | 0.736967 | 0.736967 | 53 | 38.811321 | 36.486782 | 120 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.679245 | false | false | 8 |
41f2bbfec47d12ae98d7b279e9545d0634b5d5eb | 20,538,533,652,349 | ddb6bb56e4c116710aaccaaa5326b449a4ee5534 | /ui/src/test/java/tdd/vendingMachine/ui/machine/handlers/ProductTrayEmptiedActionHandlerTest.java | de16886779de6283a539584a15389ab712b20cd2 | [] | no_license | tomp3/vending-machine-kata | https://github.com/tomp3/vending-machine-kata | 10f9609fa13c14a2cfabcb94c879d815a0301d9e | 54c8e26d35078c2e061294c39c0b7b08b12c55b3 | refs/heads/master | 2021-01-19T19:58:52.151000 | 2017-09-22T17:49:14 | 2017-09-22T17:49:14 | 101,215,421 | 0 | 0 | null | true | 2017-08-29T15:42:35 | 2017-08-23T19:02:51 | 2017-08-26T11:21:20 | 2017-08-29T15:42:35 | 121 | 0 | 0 | 0 | Java | null | null | package tdd.vendingMachine.ui.machine.handlers;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.junit.Before;
import org.junit.Test;
import tdd.vendingMachine.model.common.CoinType;
import tdd.vendingMachine.model.machine.VendingMachine;
import tdd.vendingMachine.model.machine.VendingMachineCash;
import tdd.vendingMachine.model.machine.VendingMachineShelf;
import tdd.vendingMachine.model.product.Product;
import tdd.vendingMachine.model.product.ProductType;
import tdd.vendingMachine.ui.machine.actions.VendingMachineAction;
import tdd.vendingMachine.ui.machine.actions.VendingMachineActionParameters;
import tdd.vendingMachine.ui.machine.actions.VendingMachineActionType;
import tdd.vendingMachine.ui.machine.view.model.VendingMachineState;
import tdd.vendingMachine.ui.machine.view.model.VendingMachineViewModel;
import java.math.BigDecimal;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
/**
* {@link ProductTrayEmptiedActionHandler} tests.
*/
public class ProductTrayEmptiedActionHandlerTest {
/**
* Vending machine view model.
*/
private VendingMachineViewModel vendingMachineViewModel;
/**
* Initializes vending machine view model before tests.
*/
@Before
public void beforeTest() {
VendingMachineCash cash = new VendingMachineCash(ImmutableMap.<CoinType, Integer>builder()
.put(CoinType.POINT_ONE, 10)
.put(CoinType.POINT_TWO, 10)
.put(CoinType.POINT_FIVE, 10)
.put(CoinType.ONE, 10)
.put(CoinType.TWO, 10)
.put(CoinType.FIVE, 10)
.build());
cash.getCoins().putAll(ImmutableMap.of(CoinType.POINT_ONE, 1, CoinType.POINT_FIVE, 1));
final String code = "01";
Map<String, VendingMachineShelf> shelves = Maps.newHashMap();
shelves.put(code, new VendingMachineShelf(ProductType.AWESOME_CHOCOLATE_BAR, 10, BigDecimal.valueOf(2.4)));
final Product product = new Product(ProductType.AWESOME_CHOCOLATE_BAR);
shelves.get(code).addProduct(product);
shelves.get(code).addProduct(product);
VendingMachine vendingMachine = new VendingMachine(cash, Lists.newArrayList(code), shelves);
vendingMachineViewModel = new VendingMachineViewModel(vendingMachine);
vendingMachineViewModel.setSelectedCode(code);
vendingMachineViewModel.setState(VendingMachineState.SELECTED);
}
/**
* {@link ProductTrayEmptiedActionHandler#handle()} test.
*/
@Test
public void testHandle() {
Product product = new Product(ProductType.AWESOME_CHOCOLATE_BAR);
vendingMachineViewModel.getVendingMachine().getProductTray().getProducts().add(product);
assertThat(vendingMachineViewModel.getVendingMachine().getProductTray().getProducts()).hasSize(1);
new ProductTrayEmptiedActionHandler(
VendingMachineAction.of(VendingMachineActionParameters.of(vendingMachineViewModel), VendingMachineActionType.PRODUCT_TRAY_EMPTIED)).handle();
assertThat(vendingMachineViewModel.getVendingMachine().getProductTray().getProducts()).isEmpty();
}
}
| UTF-8 | Java | 3,229 | java | ProductTrayEmptiedActionHandlerTest.java | Java | [] | null | [] | package tdd.vendingMachine.ui.machine.handlers;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.junit.Before;
import org.junit.Test;
import tdd.vendingMachine.model.common.CoinType;
import tdd.vendingMachine.model.machine.VendingMachine;
import tdd.vendingMachine.model.machine.VendingMachineCash;
import tdd.vendingMachine.model.machine.VendingMachineShelf;
import tdd.vendingMachine.model.product.Product;
import tdd.vendingMachine.model.product.ProductType;
import tdd.vendingMachine.ui.machine.actions.VendingMachineAction;
import tdd.vendingMachine.ui.machine.actions.VendingMachineActionParameters;
import tdd.vendingMachine.ui.machine.actions.VendingMachineActionType;
import tdd.vendingMachine.ui.machine.view.model.VendingMachineState;
import tdd.vendingMachine.ui.machine.view.model.VendingMachineViewModel;
import java.math.BigDecimal;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
/**
* {@link ProductTrayEmptiedActionHandler} tests.
*/
public class ProductTrayEmptiedActionHandlerTest {
/**
* Vending machine view model.
*/
private VendingMachineViewModel vendingMachineViewModel;
/**
* Initializes vending machine view model before tests.
*/
@Before
public void beforeTest() {
VendingMachineCash cash = new VendingMachineCash(ImmutableMap.<CoinType, Integer>builder()
.put(CoinType.POINT_ONE, 10)
.put(CoinType.POINT_TWO, 10)
.put(CoinType.POINT_FIVE, 10)
.put(CoinType.ONE, 10)
.put(CoinType.TWO, 10)
.put(CoinType.FIVE, 10)
.build());
cash.getCoins().putAll(ImmutableMap.of(CoinType.POINT_ONE, 1, CoinType.POINT_FIVE, 1));
final String code = "01";
Map<String, VendingMachineShelf> shelves = Maps.newHashMap();
shelves.put(code, new VendingMachineShelf(ProductType.AWESOME_CHOCOLATE_BAR, 10, BigDecimal.valueOf(2.4)));
final Product product = new Product(ProductType.AWESOME_CHOCOLATE_BAR);
shelves.get(code).addProduct(product);
shelves.get(code).addProduct(product);
VendingMachine vendingMachine = new VendingMachine(cash, Lists.newArrayList(code), shelves);
vendingMachineViewModel = new VendingMachineViewModel(vendingMachine);
vendingMachineViewModel.setSelectedCode(code);
vendingMachineViewModel.setState(VendingMachineState.SELECTED);
}
/**
* {@link ProductTrayEmptiedActionHandler#handle()} test.
*/
@Test
public void testHandle() {
Product product = new Product(ProductType.AWESOME_CHOCOLATE_BAR);
vendingMachineViewModel.getVendingMachine().getProductTray().getProducts().add(product);
assertThat(vendingMachineViewModel.getVendingMachine().getProductTray().getProducts()).hasSize(1);
new ProductTrayEmptiedActionHandler(
VendingMachineAction.of(VendingMachineActionParameters.of(vendingMachineViewModel), VendingMachineActionType.PRODUCT_TRAY_EMPTIED)).handle();
assertThat(vendingMachineViewModel.getVendingMachine().getProductTray().getProducts()).isEmpty();
}
}
| 3,229 | 0.745122 | 0.738619 | 74 | 42.635136 | 33.503357 | 153 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.743243 | false | false | 8 |
d31382c4b1ae4780a1d76c04f7ea317ebbac14df | 16,432,544,915,681 | c6a991209a44e92c462fc97c8663e33f61546ee4 | /minshengbao/app/src/main/java/com/msht/minshengbao/androidShop/viewInterface/IShopSearchView.java | c6ba96410142b0ec77bce10570f4f4527ec54ff9 | [] | no_license | Unikince/mingshengbao | https://github.com/Unikince/mingshengbao | b34b33624034996b44c2b34e23d95b80dd39cf8f | 5621e87ead3fb5d38c509e21207c1aa330984836 | refs/heads/master | 2020-06-30T21:53:26.806000 | 2019-06-13T03:20:59 | 2019-06-13T03:20:59 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.msht.minshengbao.androidShop.viewInterface;
public interface IShopSearchView extends IBaseView{
void onGetDefaultSuccess(String s);
}
| UTF-8 | Java | 151 | java | IShopSearchView.java | Java | [] | null | [] | package com.msht.minshengbao.androidShop.viewInterface;
public interface IShopSearchView extends IBaseView{
void onGetDefaultSuccess(String s);
}
| 151 | 0.827815 | 0.827815 | 5 | 29.200001 | 24.019991 | 55 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 8 |
c5fb6c5a9c26167c075ba4f33673c0b2d18d71da | 31,250,182,049,380 | 611995a7137ca541d0035707765ace100e34d05e | /workeSpaces_forme/hpayNBDF/hpayNBDFDownloadSupport-1.0.2-dev/src/main/java/com/hpay/nbdf/download/connector/impl/unionacp/UnionACPConnector.java | 34610c66b9e0fbb8f9c43f303d96eeb6b72aaa46 | [] | no_license | maorui06/workspaces_forme | https://github.com/maorui06/workspaces_forme | f9d1e21cd8f13e5986424eba03da63c088139f18 | 9b03d3cc1e29cb3686168fa5fe0eab1ce1fb344a | refs/heads/master | 2017-12-04T13:15:11.321000 | 2017-02-27T08:59:10 | 2017-02-27T08:59:10 | 83,284,795 | 0 | 1 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* @(#)UnionACPConnector.java 1.0 2015年8月22日
*
* Copyright (c) 2007-2014 Shanghai Handpay IT, Co., Ltd.
* No. 80 Xinchang Rd, Huangpu District, Shanghai, China
* All rights reserved.
*
* This software is the confidential and proprietary information of
* Shanghai Handpay IT Co., Ltd. ("Confidential Information").
* You shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement you
* entered into with Handpay.
*/
package com.hpay.nbdf.download.connector.impl.unionacp;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import com.hpay.nbdf.download.bean.BatchTransRequestBean;
import com.hpay.nbdf.download.bean.BatchTransResponseBean;
import com.hpay.nbdf.download.bean.DownRncnlFileRequestBean;
import com.hpay.nbdf.download.bean.DownRncnlFileResponseBean;
import com.hpay.nbdf.download.connector.IBackendConnector;
import com.hpay.nbdf.download.constant.ACPConstants;
import com.hpay.nbdf.download.constant.ACPRequestParamConstants;
import com.hpay.nbdf.download.constant.ACPResponseParamConstants;
import com.hpay.nbdf.download.constant.ErrorCodesConstant;
import com.hpay.nbdf.download.enums.TransEnum;
import com.hpay.nbdf.download.exception.BackendConnectorException;
import com.hpay.nbdf.download.util.SDKConfig;
/**
* @Description 银联全渠道支付通道
* @version 1.0
* @author yhe
* @since 2015年8月22日
* @history
* 时间 版本 姓名 修改内容
*/
@Service("unionACPConnector")
public class UnionACPConnector extends UnionACPBaseConnector implements IBackendConnector {
/** 日志 */
protected Logger logger = Logger.getLogger(UnionACPConnector.class);
/** 全渠道配置参数 */
@Resource
private SDKConfig sdkConfig;
@Override
public DownRncnlFileResponseBean downLoadRncnlFileByHTTP(DownRncnlFileRequestBean downRncnlFileRequestBean) throws BackendConnectorException {
logger.info("向银联全渠道发起对账文件下载请求,请求参数为:" + downRncnlFileRequestBean.toString());
Map<String, String> resultMap = submitUrl(setDownRncnlFileFormData(downRncnlFileRequestBean), sdkConfig.getDownLoadFileUrl());
logger.info("向银联全渠道发起对账文件下载请求,响应结果为:" + resultMap.toString());
String respCode = resultMap.get(ACPResponseParamConstants.PARAM_RESPCODE);
if (!respCode.equals(ACPConstants.UNION_ACP_SUCCESS)) {
logger.error("向银联全渠道发起对账文件下载请求响应失败,响应结果为:" + respCode + ",响应描述为:"+resultMap.get(ACPResponseParamConstants.PARAM_RESPMSG)+",请求参数为: " + downRncnlFileRequestBean);
throw new BackendConnectorException(ErrorCodesConstant.E_CONNECTOR_RESPONSE_ERROR, "向银联全渠道发起对账文件下载请求响应失败,响应码为:" + respCode + ",响应描述为:"+resultMap.get(ACPResponseParamConstants.PARAM_RESPMSG));
}
String destRncnlFilePath = downRncnlFileRequestBean.getRncnlFilePath();
logger.info("下载银联全渠道对账文件,文件存放目录为:" + destRncnlFilePath);
String sourceRncnlFilePath = deCodeFileContent(resultMap, destRncnlFilePath);
logger.info("下载银联全渠道对账文件成功,对账源文件名为:" + sourceRncnlFilePath);
DownRncnlFileResponseBean downRncnlFileResponseBean = new DownRncnlFileResponseBean();
downRncnlFileResponseBean.setSourceRncnlFilePath(sourceRncnlFilePath);
return downRncnlFileResponseBean;
}
private Map<String, String> setDownRncnlFileFormData(DownRncnlFileRequestBean request) throws BackendConnectorException {
Map<String, String> contentData = new HashMap<String, String>();
// 1、版本号(version),固定填写 【M】
String version = ACPConstants.VERSION;
contentData.put(ACPRequestParamConstants.REQUEST_REQUEST_PARAM_VERSION, version);
// 2、编码方式(encoding),默认取值:UTF-8 【M】
String encoding = ACPConstants.UTF_8_ENCODING;
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_ENCODING, encoding);
// 5、签名方法(signMethod),取值:01(表示采用RSA)【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_SIGNMETHOD, ACPConstants.SIGN_METHOD);
// 6、交易类型(txnType),取值:01 【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_TXNTYPE, ACPConstants.TRANSTYPE_DOWNLOAD_FILE);
// 7、交易子类(txnSubType):01:自助消费,通过地址的方式区分前台消费和后台消费(含无跳转支付);02:订购;03:分期付款 【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_TXNSUBTYPE, ACPConstants.TXN_SUB_TYPE_01);
// 8、产品类型(bizType):默认取值:000000【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_BIZTYPE, ACPConstants.DOWNLOAD_FILE_BIZ_TYPE);
// 9、接入类型(accessType):0:普通商户直连接入;1:收单机构接入,2:平台类商户接入 【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_ACCESSTYPE, ACPConstants.ACCESS_TYPE_0);
// 10、商户代码(merId) 【M】,777290058111540
//contentData.put(ACPRequestParamConstants.REQUEST_PARAM_MERID, sdkConfig.getUnionMerchantId());
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_MERID, request.getMerId());
// 11、清算日期
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_SETTLEDATE, request.getSettleDate());
// 12、订单发送时间(txnTime),商户发送交易时间,格式:YYYYMMDDhhmmss【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_TXNTIME,request.getMerchantTransDate());
// 13、文件类型(fileType)【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_FILETYPE,request.getFileType());
// 14、证书ID(certId)
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_CERTID,request.getCertId());
// 15、签名字符串
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_SIGNATURE,request.getSignature());
// 14、请求方保留域(reqReserved),商户自定义保留域,交易应答时会原样返回【O】
//contentData.put(ACPRequestParamConstants.REQUEST_PARAM_REQRESERVED, ACPConstants.DOWNLOAD_FILE_RESERVED);
return contentData;
}
@Override
public BatchTransResponseBean batchQuery(BatchTransRequestBean batchTransRequest)
throws BackendConnectorException {
logger.info("【转发全渠道批量代付】交易状态查询,请求参数为【批次号:"+ batchTransRequest.getBatchNo()
+", 商户号:"+batchTransRequest.getMerCode()+", 交易日期:"+batchTransRequest.getTransTime()
+", 签名数据:"+batchTransRequest.getSignature()+ " 】");
Map<String, String> resultMap = this.submitUrl(this.setBatchQueryData(batchTransRequest),
sdkConfig.getBatchTransUrl());
logger.info("【转发全渠道批量代付】交易状态查询响应结果为:" + resultMap.toString());
//组装响应报文
BatchTransResponseBean batchTransResponse = new BatchTransResponseBean();
//查询状态
String respCode = resultMap.get(ACPResponseParamConstants.PARAM_RESPCODE);
String respMsg = resultMap.get(ACPResponseParamConstants.PARAM_RESPMSG);
//交易返回状态
String origRespCode = resultMap.get(ACPResponseParamConstants.PARAM_ORIGRESPCODE);
String origRespMsg = resultMap.get(ACPResponseParamConstants.PARAM_ORIGRESPMSG);
logger.info("交易查询响应码【"+respCode+"】, 响应信息【"+respMsg+"】");
logger.info("渠道交易结果响应码【"+origRespCode+"】, 响应信息【"+origRespMsg+"】");
if (ACPConstants.UNION_ACP_SUCCESS.equals(respCode)) {// 银行返回批量代付查询成功的应答码
//交易结果处理成功
if(ACPConstants.UNION_ACP_SUCCESS.equals(origRespCode)){
batchTransResponse.setTransStatusAndMsg(TransEnum.TRANS_STATUS_SUCCESE.getValue(),
"全渠道批量代付处理成功");
//批量代付文件查询内容
String fileContent = resultMap.get("fileContent");
//组装批量交易明细
batchTransResponse.setTransFileContent(fileContent);
}else{
batchTransResponse.setTransStatusAndMsg(TransEnum.TRANS_STATUS_FAIL.getValue(),
"全渠道批量代付处理失败");
}
batchTransResponse.setResponseCode(origRespCode);
batchTransResponse.setResponseMsg(origRespMsg);
}else if(ACPConstants.UNION_ACP_BATCHDF_DONE.contains(respCode)){ //处理中
logger.info("银联全渠道批量代付文件等待处理中");
batchTransResponse.setTransStatusAndMsg(TransEnum.TRANS_STATUS_DONE.getValue(),
"全渠道接收成功");
batchTransResponse.setResponseCode(respCode);
batchTransResponse.setResponseMsg(respMsg);
}else{ //其他应答码为失败
logger.error("银联全渠道批量代付文件查询失败");
batchTransResponse.setTransStatusAndMsg(TransEnum.TRANS_STATUS_FAIL.getValue(),
"批量代付交易文件查询失败");
batchTransResponse.setResponseCode(respCode);
batchTransResponse.setResponseMsg(respMsg);
}
return batchTransResponse;
}
@Override
public BatchTransResponseBean batchTrans(BatchTransRequestBean batchTransRequest)
throws BackendConnectorException {
logger.info("【转发全渠道批量代付】交易请求参数为【批次号:"+ batchTransRequest.getBatchNo()
+", 商户号:"+batchTransRequest.getMerCode()+", 交易日期:"+batchTransRequest.getTransTime()
+", 交易文件内容:"+batchTransRequest.getFileContent()
+", 签名数据:"+batchTransRequest.getSignature()+ " 】");
BatchTransResponseBean batchTransResponse = new BatchTransResponseBean();
try {
Map<String, String> resultMap = this.submitUrl(this.setBatchTransData(batchTransRequest),
sdkConfig.getBatchTransUrl());
logger.info("【转发全渠道批量代付】交易请求响应结果为:" + resultMap.toString());
String respCode = resultMap.get(ACPResponseParamConstants.PARAM_RESPCODE);
String respMsg = resultMap.get(ACPResponseParamConstants.PARAM_RESPMSG);
//返回交易状态
if (!ACPConstants.UNION_ACP_SUCCESS.equals(respCode) &&
!ACPConstants.UNION_ACP_BATCHDF_DONE.contains(respCode)) { //交易失败
batchTransResponse.setTransStatusAndMsg(TransEnum.TRANS_STATUS_BANK_FAIL.getValue(), respMsg);
}else{ //交易处理中
batchTransResponse.setTransStatusAndMsg(TransEnum.TRANS_STATUS_DONE.getValue(),
"全渠道批量代付处理中");
}
// 银行返回原交易的应答码、应答信息
batchTransResponse.setResponseCode(respCode);
batchTransResponse.setResponseMsg(respMsg);
} catch(Exception e){
logger.error("批量代付文件交易失败", e);
batchTransResponse.setTransStatusAndMsg(TransEnum.TRANS_STATUS_FAIL.getValue(),
"批量代付文件交易系统异常");
}
return batchTransResponse;
}
/**
* @Description 批量代付交易请求报文组装
* @version 1.0
* @author jwu
* @since 2016-6-29 下午3:28:39
* @history
*/
private Map<String, String> setBatchTransData(BatchTransRequestBean batchTransRequest){
Map<String, String> contentData = new HashMap<String, String>();
// 1、版本号(version),固定填写 【M】
String version = ACPConstants.VERSION;
contentData.put(ACPRequestParamConstants.REQUEST_REQUEST_PARAM_VERSION, version);
// 2、编码方式(encoding),默认取值:UTF-8 【M】
String encoding = ACPConstants.UTF_8_ENCODING;
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_ENCODING, encoding);
// 5、签名方法(signMethod),取值:01(表示采用RSA)【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_SIGNMETHOD, ACPConstants.SIGN_METHOD);
// 6、交易类型(txnType),取值:21 批量交易 【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_TXNTYPE, ACPConstants.TRANSTYPE_BATCHTRADE);
// 7、交易子类(txnSubType):01:自助消费,通过地址的方式区分前台消费和后台消费(含无跳转支付);02:订购;03:分期付款 【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_TXNSUBTYPE, ACPConstants.BATCH_TXN_SUB_TYPE_03);
// 8、产品类型(bizType):默认取值:000000【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_BIZTYPE, ACPConstants.HELPPAY_BIZ_TYPE);
// 10、接入类型(accessType):0:普通商户直连接入;1:收单机构接入,2:平台类商户接入 【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_ACCESSTYPE, ACPConstants.ACCESS_TYPE_0);
// 32、渠道类型(channelType),取值05:语音,07:互联网,08:移动 【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_CHANNELTYPE, sdkConfig.getChannelType());
// 11、商户代码(merId) 【M】,777290058111540
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_MERID, batchTransRequest.getMerCode());
// 16、订单发送时间(txnTime),商户发送交易时间,格式:YYYYMMDDhhmmss【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_TXNTIME, batchTransRequest.getTransTime());
//批量代付批次号
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_BATCHNO, batchTransRequest.getBatchNo());
//批量代付交易总笔数
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_TOTALQTY, batchTransRequest.getTotalCnt().toString());
//批量代付交易总金额
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_TOTALAMT, batchTransRequest.getTotalAmt().toString());
//批量代付文件内容
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_FILECONTENT, batchTransRequest.getFileContent());
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_CERTID, batchTransRequest.getCertId());
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_SIGNATURE, batchTransRequest.getSignature());
return contentData;
}
/**
* @Description 批量代付交易查询报文组装
* @version 1.0
* @author jwu
* @since 2016-6-28 下午6:08:21
* @history
*/
private Map<String, String> setBatchQueryData(BatchTransRequestBean transFileRequest){
Map<String, String> contentData = new HashMap<String, String>();
// 1、版本号(version),固定填写 【M】
String version = ACPConstants.VERSION;
contentData.put(ACPRequestParamConstants.REQUEST_REQUEST_PARAM_VERSION, version);
// 2、编码方式(encoding),默认取值:UTF-8 【M】
String encoding = ACPConstants.UTF_8_ENCODING;
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_ENCODING, encoding);
// 5、签名方法(signMethod),取值:01(表示采用RSA)【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_SIGNMETHOD, ACPConstants.SIGN_METHOD);
// 6、交易类型(txnType),取值:22 批量查询 【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_TXNTYPE, ACPConstants.TRANSTYPE_BATCHQUERY);
// 7、交易子类(txnSubType):01:自助消费,通过地址的方式区分前台消费和后台消费(含无跳转支付);02:订购;03:分期付款 【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_TXNSUBTYPE, ACPConstants.BATCH_TXN_SUB_TYPE_03);
// 8、产品类型(bizType):默认取值:000000【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_BIZTYPE, ACPConstants.HELPPAY_BIZ_TYPE);
// 10、接入类型(accessType):0:普通商户直连接入;1:收单机构接入,2:平台类商户接入 【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_ACCESSTYPE, ACPConstants.ACCESS_TYPE_0);
// 11、商户代码(merId) 【M】,777290058111540
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_MERID, transFileRequest.getMerCode());
// 16、订单发送时间(txnTime),商户发送交易时间,格式:YYYYMMDDhhmmss【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_TXNTIME, transFileRequest.getTransTime());
// 32、渠道类型(channelType),取值05:语音,07:互联网,08:移动 【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_CHANNELTYPE, sdkConfig.getChannelType());
//批量代付批次号
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_BATCHNO, transFileRequest.getBatchNo());
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_CERTID, transFileRequest.getCertId());
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_SIGNATURE, transFileRequest.getSignature());
return contentData;
}
}
| GB18030 | Java | 16,651 | java | UnionACPConnector.java | Java | [
{
"context": " @Description 银联全渠道支付通道\n * @version 1.0\n * @author yhe\n * @since 2015年8月22日\n * @history \n * 时间 版本 姓名 修改内",
"end": 1493,
"score": 0.9994366765022278,
"start": 1490,
"tag": "USERNAME",
"value": "yhe"
},
{
"context": "cription 批量代付交易请求报文组装\n\t * @version 1.0\n\t * @au... | null | [] | /*
* @(#)UnionACPConnector.java 1.0 2015年8月22日
*
* Copyright (c) 2007-2014 Shanghai Handpay IT, Co., Ltd.
* No. 80 Xinchang Rd, Huangpu District, Shanghai, China
* All rights reserved.
*
* This software is the confidential and proprietary information of
* Shanghai Handpay IT Co., Ltd. ("Confidential Information").
* You shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement you
* entered into with Handpay.
*/
package com.hpay.nbdf.download.connector.impl.unionacp;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import com.hpay.nbdf.download.bean.BatchTransRequestBean;
import com.hpay.nbdf.download.bean.BatchTransResponseBean;
import com.hpay.nbdf.download.bean.DownRncnlFileRequestBean;
import com.hpay.nbdf.download.bean.DownRncnlFileResponseBean;
import com.hpay.nbdf.download.connector.IBackendConnector;
import com.hpay.nbdf.download.constant.ACPConstants;
import com.hpay.nbdf.download.constant.ACPRequestParamConstants;
import com.hpay.nbdf.download.constant.ACPResponseParamConstants;
import com.hpay.nbdf.download.constant.ErrorCodesConstant;
import com.hpay.nbdf.download.enums.TransEnum;
import com.hpay.nbdf.download.exception.BackendConnectorException;
import com.hpay.nbdf.download.util.SDKConfig;
/**
* @Description 银联全渠道支付通道
* @version 1.0
* @author yhe
* @since 2015年8月22日
* @history
* 时间 版本 姓名 修改内容
*/
@Service("unionACPConnector")
public class UnionACPConnector extends UnionACPBaseConnector implements IBackendConnector {
/** 日志 */
protected Logger logger = Logger.getLogger(UnionACPConnector.class);
/** 全渠道配置参数 */
@Resource
private SDKConfig sdkConfig;
@Override
public DownRncnlFileResponseBean downLoadRncnlFileByHTTP(DownRncnlFileRequestBean downRncnlFileRequestBean) throws BackendConnectorException {
logger.info("向银联全渠道发起对账文件下载请求,请求参数为:" + downRncnlFileRequestBean.toString());
Map<String, String> resultMap = submitUrl(setDownRncnlFileFormData(downRncnlFileRequestBean), sdkConfig.getDownLoadFileUrl());
logger.info("向银联全渠道发起对账文件下载请求,响应结果为:" + resultMap.toString());
String respCode = resultMap.get(ACPResponseParamConstants.PARAM_RESPCODE);
if (!respCode.equals(ACPConstants.UNION_ACP_SUCCESS)) {
logger.error("向银联全渠道发起对账文件下载请求响应失败,响应结果为:" + respCode + ",响应描述为:"+resultMap.get(ACPResponseParamConstants.PARAM_RESPMSG)+",请求参数为: " + downRncnlFileRequestBean);
throw new BackendConnectorException(ErrorCodesConstant.E_CONNECTOR_RESPONSE_ERROR, "向银联全渠道发起对账文件下载请求响应失败,响应码为:" + respCode + ",响应描述为:"+resultMap.get(ACPResponseParamConstants.PARAM_RESPMSG));
}
String destRncnlFilePath = downRncnlFileRequestBean.getRncnlFilePath();
logger.info("下载银联全渠道对账文件,文件存放目录为:" + destRncnlFilePath);
String sourceRncnlFilePath = deCodeFileContent(resultMap, destRncnlFilePath);
logger.info("下载银联全渠道对账文件成功,对账源文件名为:" + sourceRncnlFilePath);
DownRncnlFileResponseBean downRncnlFileResponseBean = new DownRncnlFileResponseBean();
downRncnlFileResponseBean.setSourceRncnlFilePath(sourceRncnlFilePath);
return downRncnlFileResponseBean;
}
private Map<String, String> setDownRncnlFileFormData(DownRncnlFileRequestBean request) throws BackendConnectorException {
Map<String, String> contentData = new HashMap<String, String>();
// 1、版本号(version),固定填写 【M】
String version = ACPConstants.VERSION;
contentData.put(ACPRequestParamConstants.REQUEST_REQUEST_PARAM_VERSION, version);
// 2、编码方式(encoding),默认取值:UTF-8 【M】
String encoding = ACPConstants.UTF_8_ENCODING;
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_ENCODING, encoding);
// 5、签名方法(signMethod),取值:01(表示采用RSA)【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_SIGNMETHOD, ACPConstants.SIGN_METHOD);
// 6、交易类型(txnType),取值:01 【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_TXNTYPE, ACPConstants.TRANSTYPE_DOWNLOAD_FILE);
// 7、交易子类(txnSubType):01:自助消费,通过地址的方式区分前台消费和后台消费(含无跳转支付);02:订购;03:分期付款 【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_TXNSUBTYPE, ACPConstants.TXN_SUB_TYPE_01);
// 8、产品类型(bizType):默认取值:000000【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_BIZTYPE, ACPConstants.DOWNLOAD_FILE_BIZ_TYPE);
// 9、接入类型(accessType):0:普通商户直连接入;1:收单机构接入,2:平台类商户接入 【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_ACCESSTYPE, ACPConstants.ACCESS_TYPE_0);
// 10、商户代码(merId) 【M】,777290058111540
//contentData.put(ACPRequestParamConstants.REQUEST_PARAM_MERID, sdkConfig.getUnionMerchantId());
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_MERID, request.getMerId());
// 11、清算日期
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_SETTLEDATE, request.getSettleDate());
// 12、订单发送时间(txnTime),商户发送交易时间,格式:YYYYMMDDhhmmss【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_TXNTIME,request.getMerchantTransDate());
// 13、文件类型(fileType)【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_FILETYPE,request.getFileType());
// 14、证书ID(certId)
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_CERTID,request.getCertId());
// 15、签名字符串
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_SIGNATURE,request.getSignature());
// 14、请求方保留域(reqReserved),商户自定义保留域,交易应答时会原样返回【O】
//contentData.put(ACPRequestParamConstants.REQUEST_PARAM_REQRESERVED, ACPConstants.DOWNLOAD_FILE_RESERVED);
return contentData;
}
@Override
public BatchTransResponseBean batchQuery(BatchTransRequestBean batchTransRequest)
throws BackendConnectorException {
logger.info("【转发全渠道批量代付】交易状态查询,请求参数为【批次号:"+ batchTransRequest.getBatchNo()
+", 商户号:"+batchTransRequest.getMerCode()+", 交易日期:"+batchTransRequest.getTransTime()
+", 签名数据:"+batchTransRequest.getSignature()+ " 】");
Map<String, String> resultMap = this.submitUrl(this.setBatchQueryData(batchTransRequest),
sdkConfig.getBatchTransUrl());
logger.info("【转发全渠道批量代付】交易状态查询响应结果为:" + resultMap.toString());
//组装响应报文
BatchTransResponseBean batchTransResponse = new BatchTransResponseBean();
//查询状态
String respCode = resultMap.get(ACPResponseParamConstants.PARAM_RESPCODE);
String respMsg = resultMap.get(ACPResponseParamConstants.PARAM_RESPMSG);
//交易返回状态
String origRespCode = resultMap.get(ACPResponseParamConstants.PARAM_ORIGRESPCODE);
String origRespMsg = resultMap.get(ACPResponseParamConstants.PARAM_ORIGRESPMSG);
logger.info("交易查询响应码【"+respCode+"】, 响应信息【"+respMsg+"】");
logger.info("渠道交易结果响应码【"+origRespCode+"】, 响应信息【"+origRespMsg+"】");
if (ACPConstants.UNION_ACP_SUCCESS.equals(respCode)) {// 银行返回批量代付查询成功的应答码
//交易结果处理成功
if(ACPConstants.UNION_ACP_SUCCESS.equals(origRespCode)){
batchTransResponse.setTransStatusAndMsg(TransEnum.TRANS_STATUS_SUCCESE.getValue(),
"全渠道批量代付处理成功");
//批量代付文件查询内容
String fileContent = resultMap.get("fileContent");
//组装批量交易明细
batchTransResponse.setTransFileContent(fileContent);
}else{
batchTransResponse.setTransStatusAndMsg(TransEnum.TRANS_STATUS_FAIL.getValue(),
"全渠道批量代付处理失败");
}
batchTransResponse.setResponseCode(origRespCode);
batchTransResponse.setResponseMsg(origRespMsg);
}else if(ACPConstants.UNION_ACP_BATCHDF_DONE.contains(respCode)){ //处理中
logger.info("银联全渠道批量代付文件等待处理中");
batchTransResponse.setTransStatusAndMsg(TransEnum.TRANS_STATUS_DONE.getValue(),
"全渠道接收成功");
batchTransResponse.setResponseCode(respCode);
batchTransResponse.setResponseMsg(respMsg);
}else{ //其他应答码为失败
logger.error("银联全渠道批量代付文件查询失败");
batchTransResponse.setTransStatusAndMsg(TransEnum.TRANS_STATUS_FAIL.getValue(),
"批量代付交易文件查询失败");
batchTransResponse.setResponseCode(respCode);
batchTransResponse.setResponseMsg(respMsg);
}
return batchTransResponse;
}
@Override
public BatchTransResponseBean batchTrans(BatchTransRequestBean batchTransRequest)
throws BackendConnectorException {
logger.info("【转发全渠道批量代付】交易请求参数为【批次号:"+ batchTransRequest.getBatchNo()
+", 商户号:"+batchTransRequest.getMerCode()+", 交易日期:"+batchTransRequest.getTransTime()
+", 交易文件内容:"+batchTransRequest.getFileContent()
+", 签名数据:"+batchTransRequest.getSignature()+ " 】");
BatchTransResponseBean batchTransResponse = new BatchTransResponseBean();
try {
Map<String, String> resultMap = this.submitUrl(this.setBatchTransData(batchTransRequest),
sdkConfig.getBatchTransUrl());
logger.info("【转发全渠道批量代付】交易请求响应结果为:" + resultMap.toString());
String respCode = resultMap.get(ACPResponseParamConstants.PARAM_RESPCODE);
String respMsg = resultMap.get(ACPResponseParamConstants.PARAM_RESPMSG);
//返回交易状态
if (!ACPConstants.UNION_ACP_SUCCESS.equals(respCode) &&
!ACPConstants.UNION_ACP_BATCHDF_DONE.contains(respCode)) { //交易失败
batchTransResponse.setTransStatusAndMsg(TransEnum.TRANS_STATUS_BANK_FAIL.getValue(), respMsg);
}else{ //交易处理中
batchTransResponse.setTransStatusAndMsg(TransEnum.TRANS_STATUS_DONE.getValue(),
"全渠道批量代付处理中");
}
// 银行返回原交易的应答码、应答信息
batchTransResponse.setResponseCode(respCode);
batchTransResponse.setResponseMsg(respMsg);
} catch(Exception e){
logger.error("批量代付文件交易失败", e);
batchTransResponse.setTransStatusAndMsg(TransEnum.TRANS_STATUS_FAIL.getValue(),
"批量代付文件交易系统异常");
}
return batchTransResponse;
}
/**
* @Description 批量代付交易请求报文组装
* @version 1.0
* @author jwu
* @since 2016-6-29 下午3:28:39
* @history
*/
private Map<String, String> setBatchTransData(BatchTransRequestBean batchTransRequest){
Map<String, String> contentData = new HashMap<String, String>();
// 1、版本号(version),固定填写 【M】
String version = ACPConstants.VERSION;
contentData.put(ACPRequestParamConstants.REQUEST_REQUEST_PARAM_VERSION, version);
// 2、编码方式(encoding),默认取值:UTF-8 【M】
String encoding = ACPConstants.UTF_8_ENCODING;
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_ENCODING, encoding);
// 5、签名方法(signMethod),取值:01(表示采用RSA)【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_SIGNMETHOD, ACPConstants.SIGN_METHOD);
// 6、交易类型(txnType),取值:21 批量交易 【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_TXNTYPE, ACPConstants.TRANSTYPE_BATCHTRADE);
// 7、交易子类(txnSubType):01:自助消费,通过地址的方式区分前台消费和后台消费(含无跳转支付);02:订购;03:分期付款 【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_TXNSUBTYPE, ACPConstants.BATCH_TXN_SUB_TYPE_03);
// 8、产品类型(bizType):默认取值:000000【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_BIZTYPE, ACPConstants.HELPPAY_BIZ_TYPE);
// 10、接入类型(accessType):0:普通商户直连接入;1:收单机构接入,2:平台类商户接入 【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_ACCESSTYPE, ACPConstants.ACCESS_TYPE_0);
// 32、渠道类型(channelType),取值05:语音,07:互联网,08:移动 【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_CHANNELTYPE, sdkConfig.getChannelType());
// 11、商户代码(merId) 【M】,777290058111540
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_MERID, batchTransRequest.getMerCode());
// 16、订单发送时间(txnTime),商户发送交易时间,格式:YYYYMMDDhhmmss【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_TXNTIME, batchTransRequest.getTransTime());
//批量代付批次号
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_BATCHNO, batchTransRequest.getBatchNo());
//批量代付交易总笔数
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_TOTALQTY, batchTransRequest.getTotalCnt().toString());
//批量代付交易总金额
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_TOTALAMT, batchTransRequest.getTotalAmt().toString());
//批量代付文件内容
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_FILECONTENT, batchTransRequest.getFileContent());
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_CERTID, batchTransRequest.getCertId());
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_SIGNATURE, batchTransRequest.getSignature());
return contentData;
}
/**
* @Description 批量代付交易查询报文组装
* @version 1.0
* @author jwu
* @since 2016-6-28 下午6:08:21
* @history
*/
private Map<String, String> setBatchQueryData(BatchTransRequestBean transFileRequest){
Map<String, String> contentData = new HashMap<String, String>();
// 1、版本号(version),固定填写 【M】
String version = ACPConstants.VERSION;
contentData.put(ACPRequestParamConstants.REQUEST_REQUEST_PARAM_VERSION, version);
// 2、编码方式(encoding),默认取值:UTF-8 【M】
String encoding = ACPConstants.UTF_8_ENCODING;
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_ENCODING, encoding);
// 5、签名方法(signMethod),取值:01(表示采用RSA)【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_SIGNMETHOD, ACPConstants.SIGN_METHOD);
// 6、交易类型(txnType),取值:22 批量查询 【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_TXNTYPE, ACPConstants.TRANSTYPE_BATCHQUERY);
// 7、交易子类(txnSubType):01:自助消费,通过地址的方式区分前台消费和后台消费(含无跳转支付);02:订购;03:分期付款 【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_TXNSUBTYPE, ACPConstants.BATCH_TXN_SUB_TYPE_03);
// 8、产品类型(bizType):默认取值:000000【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_BIZTYPE, ACPConstants.HELPPAY_BIZ_TYPE);
// 10、接入类型(accessType):0:普通商户直连接入;1:收单机构接入,2:平台类商户接入 【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_ACCESSTYPE, ACPConstants.ACCESS_TYPE_0);
// 11、商户代码(merId) 【M】,777290058111540
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_MERID, transFileRequest.getMerCode());
// 16、订单发送时间(txnTime),商户发送交易时间,格式:YYYYMMDDhhmmss【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_TXNTIME, transFileRequest.getTransTime());
// 32、渠道类型(channelType),取值05:语音,07:互联网,08:移动 【M】
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_CHANNELTYPE, sdkConfig.getChannelType());
//批量代付批次号
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_BATCHNO, transFileRequest.getBatchNo());
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_CERTID, transFileRequest.getCertId());
contentData.put(ACPRequestParamConstants.REQUEST_PARAM_SIGNATURE, transFileRequest.getSignature());
return contentData;
}
}
| 16,651 | 0.773837 | 0.757203 | 335 | 41.170151 | 37.08181 | 194 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.486567 | false | false | 8 |
bae97af9300bac1e030987e777f50a2d616896aa | 13,408,887,943,922 | f164b56ed542b35b257c947b59ff79c708c72009 | /CoreJava/src/practice/SwitchExample.java | a751bac1f4741db5ae6fad7e23fcea692e812e39 | [] | no_license | MAYURIGAURAV/CoreJavaNew | https://github.com/MAYURIGAURAV/CoreJavaNew | f1593b27cb8800e1bd8833aec8ba495d53e21f90 | e1cd5825acde15c797c6ce9c777758a5db01bcfa | refs/heads/master | 2020-03-24T04:59:17.180000 | 2017-10-30T12:26:30 | 2017-10-30T12:26:30 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package practice;
public class SwitchExample {
public static void main(String[] args) {
int a = 20;
switch (a) {
case 10:
System.out.println("This is 10.");
break;
case 20:
System.out.println("This is 20.");
break;
case 30:
System.out.println("This is 30.");
break;
default:
System.out.println("This is not 10, 20, 30");
}
System.out.println("/////////////////////////////////////////////////////");
switch (a) {
case 10:
System.out.println("This is 10.");
case 20:
System.out.println("This is 20.");
case 30:
System.out.println("This is 30.");
default:
System.out.println("This is not 10, 20, 30");
}
}
}
| UTF-8 | Java | 945 | java | SwitchExample.java | Java | [] | null | [] | package practice;
public class SwitchExample {
public static void main(String[] args) {
int a = 20;
switch (a) {
case 10:
System.out.println("This is 10.");
break;
case 20:
System.out.println("This is 20.");
break;
case 30:
System.out.println("This is 30.");
break;
default:
System.out.println("This is not 10, 20, 30");
}
System.out.println("/////////////////////////////////////////////////////");
switch (a) {
case 10:
System.out.println("This is 10.");
case 20:
System.out.println("This is 20.");
case 30:
System.out.println("This is 30.");
default:
System.out.println("This is not 10, 20, 30");
}
}
}
| 945 | 0.397884 | 0.357672 | 33 | 27.636364 | 20.126596 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.545455 | false | false | 8 |
a03595bb12c911bdadd72d26c8dfece65eb1444b | 8,770,323,226,230 | 2e1ac137a865e5df699bc46a032e27ed217c3d71 | /src/main/java/pl/edu/pjatk/librarycms/web/rest/package-info.java | 8b8cc974fb2e42773ceef2da7e698797e70a4eea | [] | no_license | slawkolearn/library-cms | https://github.com/slawkolearn/library-cms | f86ac058b059f8ca71221b841995ccbf6d821626 | c8f7f26a3383013db4f06eb2870deb05738efbd1 | refs/heads/master | 2020-09-29T05:08:55.540000 | 2019-12-09T20:21:04 | 2019-12-09T20:21:04 | 226,959,647 | 0 | 0 | null | true | 2019-12-09T20:18:46 | 2019-12-09T20:18:45 | 2019-11-15T21:42:08 | 2019-11-15T21:47:29 | 1,434 | 0 | 0 | 0 | null | false | false | /**
* Spring MVC REST controllers.
*/
package pl.edu.pjatk.librarycms.web.rest;
| UTF-8 | Java | 82 | java | package-info.java | Java | [] | null | [] | /**
* Spring MVC REST controllers.
*/
package pl.edu.pjatk.librarycms.web.rest;
| 82 | 0.707317 | 0.707317 | 4 | 19.5 | 16.874537 | 41 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | false | false | 8 |
73060e7a149017a3234fd33e4275b5545425eac4 | 39,341,900,469,916 | 71e5a44e9b061cb31479873b88b8c17b8bbb5e1e | /src/main/java/com/cskaoyan/service/TopicServiceImpl.java | 282e5c74f80bf1bb4e702a6afd14639b28eedfbb | [] | no_license | 14February/mall | https://github.com/14February/mall | 5cd8e57d79c880bdd56d2f4e377826968e9581f5 | 0377832080d556d3f40994aea79f1baf061d7357 | refs/heads/main | 2023-02-13T16:04:03.729000 | 2021-01-16T05:57:30 | 2021-01-16T05:57:30 | 330,086,477 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.cskaoyan.service;
import com.cskaoyan.bean.backstage.ListData;
import com.cskaoyan.bean.backstage.Topic;
import com.cskaoyan.bean.backstage.TopicExample;
import com.cskaoyan.mapper.backstage.TopicMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
@Service
public class TopicServiceImpl implements TopicService{
@Autowired
TopicMapper topicMapper;
@Override
public Topic create(Topic topic) {
topic.setAddTime(new Date());
topic.setUpdateTime(new Date());
int insert = topicMapper.insertSelective(topic);
Topic insertTopic = topicMapper.selectByPrimaryKey(topic.getId());
return insertTopic;
}
@Override
public void delete(Topic topic) {
topic.setDeleted(true);
int delete = topicMapper.updateByPrimaryKey(topic);
}
@Override
public Topic update(Topic topic) {
topic.setUpdateTime(new Date());
int update = topicMapper.updateByPrimaryKey(topic);
Topic updateTopic = topicMapper.selectByPrimaryKey(topic.getId());
return updateTopic;
}
@Override
public ListData<Topic> queryTopicList(Integer page, Integer limit, String title, String subtitle, String sort, String order) {
PageHelper.startPage(page, limit);
TopicExample example = new TopicExample();
example.setOrderByClause(sort + " " + order);
TopicExample.Criteria criteria = example.createCriteria();
if(title != null) criteria.andTitleLike("%" + title + "%");
if(subtitle != null) criteria.andSubtitleLike("%" + subtitle + "%");
List<Topic> topics = topicMapper.selectByExample(example);
PageInfo<Topic> topicPageInfo = new PageInfo<>(topics);
int total = (int)topicPageInfo.getTotal();
return ListData.data(total, topics);
}
}
| UTF-8 | Java | 2,017 | java | TopicServiceImpl.java | Java | [] | null | [] | package com.cskaoyan.service;
import com.cskaoyan.bean.backstage.ListData;
import com.cskaoyan.bean.backstage.Topic;
import com.cskaoyan.bean.backstage.TopicExample;
import com.cskaoyan.mapper.backstage.TopicMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
@Service
public class TopicServiceImpl implements TopicService{
@Autowired
TopicMapper topicMapper;
@Override
public Topic create(Topic topic) {
topic.setAddTime(new Date());
topic.setUpdateTime(new Date());
int insert = topicMapper.insertSelective(topic);
Topic insertTopic = topicMapper.selectByPrimaryKey(topic.getId());
return insertTopic;
}
@Override
public void delete(Topic topic) {
topic.setDeleted(true);
int delete = topicMapper.updateByPrimaryKey(topic);
}
@Override
public Topic update(Topic topic) {
topic.setUpdateTime(new Date());
int update = topicMapper.updateByPrimaryKey(topic);
Topic updateTopic = topicMapper.selectByPrimaryKey(topic.getId());
return updateTopic;
}
@Override
public ListData<Topic> queryTopicList(Integer page, Integer limit, String title, String subtitle, String sort, String order) {
PageHelper.startPage(page, limit);
TopicExample example = new TopicExample();
example.setOrderByClause(sort + " " + order);
TopicExample.Criteria criteria = example.createCriteria();
if(title != null) criteria.andTitleLike("%" + title + "%");
if(subtitle != null) criteria.andSubtitleLike("%" + subtitle + "%");
List<Topic> topics = topicMapper.selectByExample(example);
PageInfo<Topic> topicPageInfo = new PageInfo<>(topics);
int total = (int)topicPageInfo.getTotal();
return ListData.data(total, topics);
}
}
| 2,017 | 0.704512 | 0.704512 | 56 | 35.017857 | 26.311657 | 130 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.714286 | false | false | 8 |
894de91af1aef01440cf0caf85a3eee5a15995f5 | 39,341,900,470,379 | 1ab2d8ef8abbb80820ee57a039eb6c206122cfe0 | /src/linda/reg.java | f1e67d847c85c49d7921fa9ae6e81a65bd744306 | [] | no_license | Sanjay075/Mini_Project_Batch_3_Sanjay_Kumar | https://github.com/Sanjay075/Mini_Project_Batch_3_Sanjay_Kumar | 101f6479173446e857fd7a37b97465b2b7d53eda | b6fd88eecc1ad237428336aa22130e45d9dfd156 | refs/heads/main | 2023-08-28T08:58:34.944000 | 2021-10-19T05:20:39 | 2021-10-19T05:20:39 | 418,770,981 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null |
package linda;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
*
* @author Sanjay Kumar
*/
public class reg extends javax.swing.JFrame {
/**
* Creates new form reg
*/
public reg() {
initComponents();
table_update();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
txtname = new javax.swing.JTextField();
txtmobile = new javax.swing.JTextField();
txtcourse = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jButton4 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(153, 0, 0));
jLabel1.setBackground(new java.awt.Color(255, 255, 0));
jLabel1.setFont(new java.awt.Font("Microsoft Sans Serif", 3, 24)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 102, 0));
jLabel1.setText("Student Registration Form");
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Registration", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("sansserif", 3, 14), new java.awt.Color(0, 0, 204))); // NOI18N
jLabel2.setBackground(new java.awt.Color(255, 255, 255));
jLabel2.setFont(new java.awt.Font("sansserif", 3, 14)); // NOI18N
jLabel2.setForeground(new java.awt.Color(204, 0, 0));
jLabel2.setText("Student Name");
jLabel3.setBackground(new java.awt.Color(255, 255, 255));
jLabel3.setFont(new java.awt.Font("sansserif", 3, 14)); // NOI18N
jLabel3.setForeground(new java.awt.Color(204, 0, 51));
jLabel3.setText("Mobile");
jLabel4.setFont(new java.awt.Font("sansserif", 3, 14)); // NOI18N
jLabel4.setForeground(new java.awt.Color(204, 0, 0));
jLabel4.setText("Course");
txtname.setBackground(new java.awt.Color(51, 255, 255));
txtname.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(0, 0, 255), new java.awt.Color(0, 102, 102)));
txtmobile.setBackground(new java.awt.Color(51, 255, 255));
txtmobile.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(0, 0, 255), new java.awt.Color(0, 102, 102)));
txtcourse.setBackground(new java.awt.Color(0, 255, 255));
txtcourse.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(51, 51, 255), new java.awt.Color(0, 153, 153)));
jButton1.setBackground(new java.awt.Color(153, 153, 255));
jButton1.setFont(new java.awt.Font("Georgia", 1, 14)); // NOI18N
jButton1.setForeground(new java.awt.Color(255, 51, 51));
jButton1.setText("Add");
jButton1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, new java.awt.Color(153, 0, 51), new java.awt.Color(255, 51, 0), null, new java.awt.Color(255, 51, 51)));
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setBackground(new java.awt.Color(153, 153, 255));
jButton2.setFont(new java.awt.Font("Georgia", 1, 14)); // NOI18N
jButton2.setForeground(new java.awt.Color(255, 0, 0));
jButton2.setText("Edit");
jButton2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, new java.awt.Color(255, 0, 51), new java.awt.Color(153, 0, 51), null, new java.awt.Color(153, 0, 0)));
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setBackground(new java.awt.Color(153, 153, 255));
jButton3.setFont(new java.awt.Font("Georgia", 1, 14)); // NOI18N
jButton3.setForeground(new java.awt.Color(204, 0, 0));
jButton3.setText("Delete");
jButton3.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, new java.awt.Color(255, 0, 0), new java.awt.Color(153, 0, 51), null, new java.awt.Color(153, 0, 0)));
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtcourse, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)
.addComponent(txtmobile)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtname, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 17, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(0, 123, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(29, 29, 29)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtmobile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(21, 21, 21)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtcourse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 15, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
jTable1.setBackground(new java.awt.Color(204, 255, 204));
jTable1.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED));
jTable1.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 12)); // NOI18N
jTable1.setForeground(new java.awt.Color(0, 0, 0));
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Id", "Name", "Mobile", "Course"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jTable1);
jButton4.setBackground(new java.awt.Color(0, 102, 51));
jButton4.setFont(new java.awt.Font("Courier New", 1, 18)); // NOI18N
jButton4.setForeground(new java.awt.Color(255, 51, 51));
jButton4.setText("Export");
jButton4.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, new java.awt.Color(204, 0, 0), new java.awt.Color(255, 51, 51), new java.awt.Color(0, 0, 204), new java.awt.Color(102, 0, 0)));
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(13, 13, 13))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 456, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 337, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(236, 236, 236))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(9, 9, 9)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(19, 19, 19)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(14, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
Connection con1;
PreparedStatement insert;
@SuppressWarnings("unchecked")
private void table_update()
{
int c;
try {
Class.forName("com.mysql.jdbc.Driver"); //Register the mysql driver
con1 = DriverManager.getConnection("jdbc:mysql://localhost/linda","root","");
insert = con1.prepareStatement("select * from record");
ResultSet rs=insert.executeQuery();
ResultSetMetaData Rss=rs.getMetaData();
c=Rss.getColumnCount();
DefaultTableModel Df=( DefaultTableModel)jTable1.getModel();
Df.setRowCount(0);
while (rs.next()) {
Vector v2 = new Vector();
for (int a = 1; a <= c; a++) {
v2.add(rs.getString("id"));
v2.add(rs.getString("name"));
v2.add(rs.getString("mobile"));
v2.add(rs.getString("course"));
}
Df.addRow(v2);
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(reg.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(reg.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
String name =txtname.getText();
String age =txtmobile.getText();
String course =txtcourse.getText();
try {
Class.forName("com.mysql.jdbc.Driver"); //Register the mysql driver
con1 = DriverManager.getConnection("jdbc:mysql://localhost/linda","root","");
insert = con1.prepareStatement("insert into record (name,mobile,course)values(?,?,?)");
insert.setString(1,name);
insert.setString(2,age);
insert.setString(3,course);
insert.executeUpdate();
JOptionPane.showMessageDialog(this, "Record Addeddd");
txtname.setText("");
txtmobile.setText("");
txtcourse.setText("");
txtname.requestFocus();
table_update();
} catch (ClassNotFoundException ex) {
Logger.getLogger(reg.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(reg.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
// TODO add your handling code here:
DefaultTableModel Df = (DefaultTableModel) jTable1.getModel();
int selectedIndex = jTable1.getSelectedRow();
txtname.setText(Df.getValueAt(selectedIndex, 1).toString());
txtmobile.setText(Df.getValueAt(selectedIndex, 2).toString());
txtcourse.setText(Df.getValueAt(selectedIndex, 3).toString());
}//GEN-LAST:event_jTable1MouseClicked
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
DefaultTableModel Df = (DefaultTableModel) jTable1.getModel();
int selectedIndex = jTable1.getSelectedRow();
try {
int id = Integer.parseInt(Df.getValueAt(selectedIndex, 0).toString());
String name =txtname.getText();
String mobile =txtmobile.getText();
String course =txtcourse.getText();
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost/linda","root","");
insert = con1.prepareStatement("update record set name= ?,mobile= ?,course= ? where id= ?");
insert.setString(1,name);
insert.setString(2,mobile);
insert.setString(3,course);
insert.setInt(4,id);
insert.executeUpdate();
JOptionPane.showMessageDialog(this, "Record Updated");
txtname.setText("");
txtmobile.setText("");
txtcourse.setText("");
table_update();
} catch (ClassNotFoundException ex) {
} catch (SQLException ex) {
}
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
DefaultTableModel Df = (DefaultTableModel) jTable1.getModel();
int selectedIndex = jTable1.getSelectedRow();
try {
int id = Integer.parseInt(Df.getValueAt(selectedIndex, 0).toString());
int dialogResult = JOptionPane.showConfirmDialog (null, "Do you want to Delete the record","Warning",JOptionPane.YES_NO_OPTION);
if(dialogResult == JOptionPane.YES_OPTION){
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost/linda","root","");
insert = con1.prepareStatement("delete from record where id = ?");
insert.setInt(1,id);
insert.executeUpdate();
JOptionPane.showMessageDialog(this, "Record Delete");
txtname.setText("");
txtmobile.setText("");
txtcourse.setText("");
table_update();
}
} catch (ClassNotFoundException ex) {
} catch (SQLException ex) {
}
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
// TODO add your handling code here:
DefaultTableModel Df = (DefaultTableModel) jTable1.getModel();
String CurrentDirectoryFilePath="C:\\Desktop";
JFileChooser excelExportChooser=new JFileChooser(CurrentDirectoryFilePath);
int excelChooser=excelExportChooser.showSaveDialog(null);
if(excelChooser==JFileChooser.APPROVE_OPTION){
XSSFWorkbook excelXSSFWorkbookExporter=new XSSFWorkbook();
XSSFSheet excelSheet= excelXSSFWorkbookExporter.createSheet("prepare");
for (int i=0 ;i<Df.getRowCount();i++){
XSSFRow excelRow=excelSheet.createRow(i);
for (int j=0; j<Df.getColumnCount();j++){
XSSFCell excelCell=excelRow.createCell(j);
excelCell.setCellValue(Df.getValueAt(i,j).toString());
}
}
FileOutputStream excelaFIS;
BufferedOutputStream excelBOU;
try{
excelaFIS=new FileOutputStream(excelExportChooser.getSelectedFile()+".xlsx");
excelBOU=new BufferedOutputStream(excelaFIS);
excelXSSFWorkbookExporter.write(excelBOU);
excelBOU.close();
excelXSSFWorkbookExporter.close();
}catch (IOException iOexception){
}
}
}//GEN-LAST:event_jButton4ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Metal".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(reg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(reg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(reg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(reg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new reg().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField txtcourse;
private javax.swing.JTextField txtmobile;
private javax.swing.JTextField txtname;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 24,647 | java | reg.java | Java | [
{
"context": "i.xssf.usermodel.XSSFWorkbook;\n\n\n/**\n *\n * @author Sanjay Kumar\n */\npublic class reg extends javax.swing.JFrame {",
"end": 724,
"score": 0.9998223781585693,
"start": 712,
"tag": "NAME",
"value": "Sanjay Kumar"
}
] | null | [] |
package linda;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
*
* @author <NAME>
*/
public class reg extends javax.swing.JFrame {
/**
* Creates new form reg
*/
public reg() {
initComponents();
table_update();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
txtname = new javax.swing.JTextField();
txtmobile = new javax.swing.JTextField();
txtcourse = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jButton4 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBackground(new java.awt.Color(153, 0, 0));
jLabel1.setBackground(new java.awt.Color(255, 255, 0));
jLabel1.setFont(new java.awt.Font("Microsoft Sans Serif", 3, 24)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 102, 0));
jLabel1.setText("Student Registration Form");
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Registration", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("sansserif", 3, 14), new java.awt.Color(0, 0, 204))); // NOI18N
jLabel2.setBackground(new java.awt.Color(255, 255, 255));
jLabel2.setFont(new java.awt.Font("sansserif", 3, 14)); // NOI18N
jLabel2.setForeground(new java.awt.Color(204, 0, 0));
jLabel2.setText("Student Name");
jLabel3.setBackground(new java.awt.Color(255, 255, 255));
jLabel3.setFont(new java.awt.Font("sansserif", 3, 14)); // NOI18N
jLabel3.setForeground(new java.awt.Color(204, 0, 51));
jLabel3.setText("Mobile");
jLabel4.setFont(new java.awt.Font("sansserif", 3, 14)); // NOI18N
jLabel4.setForeground(new java.awt.Color(204, 0, 0));
jLabel4.setText("Course");
txtname.setBackground(new java.awt.Color(51, 255, 255));
txtname.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(0, 0, 255), new java.awt.Color(0, 102, 102)));
txtmobile.setBackground(new java.awt.Color(51, 255, 255));
txtmobile.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(0, 0, 255), new java.awt.Color(0, 102, 102)));
txtcourse.setBackground(new java.awt.Color(0, 255, 255));
txtcourse.setBorder(javax.swing.BorderFactory.createEtchedBorder(new java.awt.Color(51, 51, 255), new java.awt.Color(0, 153, 153)));
jButton1.setBackground(new java.awt.Color(153, 153, 255));
jButton1.setFont(new java.awt.Font("Georgia", 1, 14)); // NOI18N
jButton1.setForeground(new java.awt.Color(255, 51, 51));
jButton1.setText("Add");
jButton1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, new java.awt.Color(153, 0, 51), new java.awt.Color(255, 51, 0), null, new java.awt.Color(255, 51, 51)));
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setBackground(new java.awt.Color(153, 153, 255));
jButton2.setFont(new java.awt.Font("Georgia", 1, 14)); // NOI18N
jButton2.setForeground(new java.awt.Color(255, 0, 0));
jButton2.setText("Edit");
jButton2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, new java.awt.Color(255, 0, 51), new java.awt.Color(153, 0, 51), null, new java.awt.Color(153, 0, 0)));
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setBackground(new java.awt.Color(153, 153, 255));
jButton3.setFont(new java.awt.Font("Georgia", 1, 14)); // NOI18N
jButton3.setForeground(new java.awt.Color(204, 0, 0));
jButton3.setText("Delete");
jButton3.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, new java.awt.Color(255, 0, 0), new java.awt.Color(153, 0, 51), null, new java.awt.Color(153, 0, 0)));
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(txtcourse, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)
.addComponent(txtmobile)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(txtname, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 17, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(0, 123, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(29, 29, 29)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtmobile, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(21, 21, 21)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtcourse, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 15, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)))
);
jTable1.setBackground(new java.awt.Color(204, 255, 204));
jTable1.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED));
jTable1.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 12)); // NOI18N
jTable1.setForeground(new java.awt.Color(0, 0, 0));
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Id", "Name", "Mobile", "Course"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jTable1);
jButton4.setBackground(new java.awt.Color(0, 102, 51));
jButton4.setFont(new java.awt.Font("Courier New", 1, 18)); // NOI18N
jButton4.setForeground(new java.awt.Color(255, 51, 51));
jButton4.setText("Export");
jButton4.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED, new java.awt.Color(204, 0, 0), new java.awt.Color(255, 51, 51), new java.awt.Color(0, 0, 204), new java.awt.Color(102, 0, 0)));
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(13, 13, 13))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 456, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 337, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(236, 236, 236))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(9, 9, 9)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(19, 19, 19)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(14, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
Connection con1;
PreparedStatement insert;
@SuppressWarnings("unchecked")
private void table_update()
{
int c;
try {
Class.forName("com.mysql.jdbc.Driver"); //Register the mysql driver
con1 = DriverManager.getConnection("jdbc:mysql://localhost/linda","root","");
insert = con1.prepareStatement("select * from record");
ResultSet rs=insert.executeQuery();
ResultSetMetaData Rss=rs.getMetaData();
c=Rss.getColumnCount();
DefaultTableModel Df=( DefaultTableModel)jTable1.getModel();
Df.setRowCount(0);
while (rs.next()) {
Vector v2 = new Vector();
for (int a = 1; a <= c; a++) {
v2.add(rs.getString("id"));
v2.add(rs.getString("name"));
v2.add(rs.getString("mobile"));
v2.add(rs.getString("course"));
}
Df.addRow(v2);
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(reg.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(reg.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
String name =txtname.getText();
String age =txtmobile.getText();
String course =txtcourse.getText();
try {
Class.forName("com.mysql.jdbc.Driver"); //Register the mysql driver
con1 = DriverManager.getConnection("jdbc:mysql://localhost/linda","root","");
insert = con1.prepareStatement("insert into record (name,mobile,course)values(?,?,?)");
insert.setString(1,name);
insert.setString(2,age);
insert.setString(3,course);
insert.executeUpdate();
JOptionPane.showMessageDialog(this, "Record Addeddd");
txtname.setText("");
txtmobile.setText("");
txtcourse.setText("");
txtname.requestFocus();
table_update();
} catch (ClassNotFoundException ex) {
Logger.getLogger(reg.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(reg.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_jButton1ActionPerformed
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
// TODO add your handling code here:
DefaultTableModel Df = (DefaultTableModel) jTable1.getModel();
int selectedIndex = jTable1.getSelectedRow();
txtname.setText(Df.getValueAt(selectedIndex, 1).toString());
txtmobile.setText(Df.getValueAt(selectedIndex, 2).toString());
txtcourse.setText(Df.getValueAt(selectedIndex, 3).toString());
}//GEN-LAST:event_jTable1MouseClicked
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
DefaultTableModel Df = (DefaultTableModel) jTable1.getModel();
int selectedIndex = jTable1.getSelectedRow();
try {
int id = Integer.parseInt(Df.getValueAt(selectedIndex, 0).toString());
String name =txtname.getText();
String mobile =txtmobile.getText();
String course =txtcourse.getText();
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost/linda","root","");
insert = con1.prepareStatement("update record set name= ?,mobile= ?,course= ? where id= ?");
insert.setString(1,name);
insert.setString(2,mobile);
insert.setString(3,course);
insert.setInt(4,id);
insert.executeUpdate();
JOptionPane.showMessageDialog(this, "Record Updated");
txtname.setText("");
txtmobile.setText("");
txtcourse.setText("");
table_update();
} catch (ClassNotFoundException ex) {
} catch (SQLException ex) {
}
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
DefaultTableModel Df = (DefaultTableModel) jTable1.getModel();
int selectedIndex = jTable1.getSelectedRow();
try {
int id = Integer.parseInt(Df.getValueAt(selectedIndex, 0).toString());
int dialogResult = JOptionPane.showConfirmDialog (null, "Do you want to Delete the record","Warning",JOptionPane.YES_NO_OPTION);
if(dialogResult == JOptionPane.YES_OPTION){
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost/linda","root","");
insert = con1.prepareStatement("delete from record where id = ?");
insert.setInt(1,id);
insert.executeUpdate();
JOptionPane.showMessageDialog(this, "Record Delete");
txtname.setText("");
txtmobile.setText("");
txtcourse.setText("");
table_update();
}
} catch (ClassNotFoundException ex) {
} catch (SQLException ex) {
}
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
// TODO add your handling code here:
DefaultTableModel Df = (DefaultTableModel) jTable1.getModel();
String CurrentDirectoryFilePath="C:\\Desktop";
JFileChooser excelExportChooser=new JFileChooser(CurrentDirectoryFilePath);
int excelChooser=excelExportChooser.showSaveDialog(null);
if(excelChooser==JFileChooser.APPROVE_OPTION){
XSSFWorkbook excelXSSFWorkbookExporter=new XSSFWorkbook();
XSSFSheet excelSheet= excelXSSFWorkbookExporter.createSheet("prepare");
for (int i=0 ;i<Df.getRowCount();i++){
XSSFRow excelRow=excelSheet.createRow(i);
for (int j=0; j<Df.getColumnCount();j++){
XSSFCell excelCell=excelRow.createCell(j);
excelCell.setCellValue(Df.getValueAt(i,j).toString());
}
}
FileOutputStream excelaFIS;
BufferedOutputStream excelBOU;
try{
excelaFIS=new FileOutputStream(excelExportChooser.getSelectedFile()+".xlsx");
excelBOU=new BufferedOutputStream(excelaFIS);
excelXSSFWorkbookExporter.write(excelBOU);
excelBOU.close();
excelXSSFWorkbookExporter.close();
}catch (IOException iOexception){
}
}
}//GEN-LAST:event_jButton4ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Metal".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(reg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(reg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(reg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(reg.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new reg().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField txtcourse;
private javax.swing.JTextField txtmobile;
private javax.swing.JTextField txtname;
// End of variables declaration//GEN-END:variables
}
| 24,641 | 0.633505 | 0.609608 | 486 | 49.711933 | 40.430088 | 279 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.053498 | false | false | 8 |
51ab1ff3d06d569425fa51592be86886319d6407 | 4,621,384,865,460 | b32b976a2d06d253fae9bd2f5df9f0b8f7b6648d | /src/main/java/io/webgraph/warc/WarcReader.java | eaf7513ddfe18e224d110224f6bc32712278f4bd | [] | no_license | cbeams/warc | https://github.com/cbeams/warc | 980edf58e78372c3244751df146f1985cdbc1103 | ebbae4c378beb70710eeba523c346b7c75b4b462 | refs/heads/master | 2021-03-19T16:44:23.551000 | 2017-06-23T16:23:27 | 2017-06-23T16:23:27 | 89,901,540 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package io.webgraph.warc;
import org.iokit.gzip.MultiMemberGzipInputStream;
import org.iokit.general.ConcatenationReader;
import org.iokit.general.LineReader;
import org.iokit.core.IOKitInputStream;
import org.iokit.core.Try;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class WarcReader extends ConcatenationReader<WarcRecord> {
public static final int DEFAULT_MINIMUM_READ_COUNT = 1;
public WarcReader(String warcFilePath) {
this(new File(warcFilePath));
}
public WarcReader(File warcFile) {
this(Try.toCall(() -> new FileInputStream(warcFile)));
}
public WarcReader(InputStream in) {
this(in, new MultiMemberGzipInputStream.Adapter());
}
public WarcReader(InputStream in, IOKitInputStream.Adapter... adapters) {
this(IOKitInputStream.adapt(in, WarcRecord.LINE_TERMINATOR, adapters));
}
public WarcReader(IOKitInputStream in) {
this(new LineReader(in));
}
public WarcReader(LineReader lineReader) {
this(new WarcRecord.Reader(lineReader), new WarcConcatenator.Reader(lineReader));
}
public WarcReader(WarcRecord.Reader recordReader, WarcConcatenator.Reader concatenatorReader) {
super(recordReader, concatenatorReader);
setMinimumReadCount(DEFAULT_MINIMUM_READ_COUNT);
}
public void seek(long offset) {
in.skipRaw(offset);
}
}
| UTF-8 | Java | 1,426 | java | WarcReader.java | Java | [] | null | [] | package io.webgraph.warc;
import org.iokit.gzip.MultiMemberGzipInputStream;
import org.iokit.general.ConcatenationReader;
import org.iokit.general.LineReader;
import org.iokit.core.IOKitInputStream;
import org.iokit.core.Try;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
public class WarcReader extends ConcatenationReader<WarcRecord> {
public static final int DEFAULT_MINIMUM_READ_COUNT = 1;
public WarcReader(String warcFilePath) {
this(new File(warcFilePath));
}
public WarcReader(File warcFile) {
this(Try.toCall(() -> new FileInputStream(warcFile)));
}
public WarcReader(InputStream in) {
this(in, new MultiMemberGzipInputStream.Adapter());
}
public WarcReader(InputStream in, IOKitInputStream.Adapter... adapters) {
this(IOKitInputStream.adapt(in, WarcRecord.LINE_TERMINATOR, adapters));
}
public WarcReader(IOKitInputStream in) {
this(new LineReader(in));
}
public WarcReader(LineReader lineReader) {
this(new WarcRecord.Reader(lineReader), new WarcConcatenator.Reader(lineReader));
}
public WarcReader(WarcRecord.Reader recordReader, WarcConcatenator.Reader concatenatorReader) {
super(recordReader, concatenatorReader);
setMinimumReadCount(DEFAULT_MINIMUM_READ_COUNT);
}
public void seek(long offset) {
in.skipRaw(offset);
}
}
| 1,426 | 0.721599 | 0.720898 | 51 | 26.960785 | 27.113386 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.509804 | false | false | 8 |
4f9b40a498fe3b61270a9b0d399f296380a641e9 | 17,076,789,974,944 | 13500601c77b636831b676e720ad420d0434d0e8 | /src/java/com/sansec/hsm/bean/config/NetworkInfo.java | 17caf80fc16bf5a9e6722c9c5eed1f5578356888 | [] | no_license | tauruswei/WebHsmm_1.2.15.12 | https://github.com/tauruswei/WebHsmm_1.2.15.12 | b04fa691f8231870215ffc56a94f058cf3b17317 | be02e1a0d5c8277eb1787c7c14e3254f74fc1996 | refs/heads/master | 2022-03-14T14:14:58.346000 | 2019-10-12T09:18:15 | 2019-10-12T09:18:15 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.sansec.hsm.bean.config;
import com.sansec.hsm.bean.Privilege;
import com.sansec.hsm.exception.DeviceException;
import com.sansec.hsm.exception.NoPrivilegeException;
import com.sansec.hsm.util.ConfigUtil;
import com.sansec.hsm.util.ErrorInfo;
import com.sansec.hsm.util.OperationLogUtil;
import debug.log.LogUtil;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.Properties;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Enumeration;
/**
*
* @author root
*/
public class NetworkInfo {
public static final String operationname = "NETWORK MANAGEMENT";
public static final int MAX_ETH_COUNT = 4;
public static final String BOND0 = "/etc/sysconfig/network-scripts/ifcfg-bond0";
public static final String ETH = "/etc/sysconfig/network-scripts/ifcfg-eth";
public static final String NETCONFIG = "/mnt/linux/etc/network.param";
public static final String NETEXEC = "/mnt/linux/etc/network.sh";
public static final String ROUTE = "/etc/sysconfig/network-scripts/routes";
public static final String BOND0NOBOND = "/etc/sysconfig/network-scripts/ifcfg-bond0.bond";
public static final String ETHNOBONDSUFFIX = ".nobond";
public static final String ETHBONDSUFFIX = ".bond";
public static final String WEBCONFXML = "/mnt/linux/tomcat6/conf/server.xml";
public static final String WEBCONFCOPY = "/mnt/linux/tomcat6/conf/ex.server.xml";
public static final int WEBETH = 1;
// index=0 -> eth0, index=1 -> eth1
private int index;
private int nEth = 0;//非绑定网口数量
private String name;
private String ip;
private String mask;
private String gateway;
private boolean bond = false;
private boolean webbond = false;
public NetworkInfo() {
}
public NetworkInfo(int index, String name, String ip, String mask, String gateway) {
this.index = index;
this.name = name;
this.ip = ip;
this.mask = mask;
this.gateway = gateway;
}
public String getIp() {
return ip;
}
public String getMask() {
return mask;
}
public String getGateway() {
return gateway;
}
public int getIndex() {
return index;
}
public String getName() {
return name;
}
public String getBondingIP(String path){
String sXML = new String();
String sLine = new String();
String sIP = new String();
int index,indextmp;
try
{
if (path.isEmpty()) {
path=WEBCONFXML;
}
File file = new File(path);
if(!file.exists()) {
// OperationLogUtil.println(operationname,"配置文件不存在.");
return "0.0.0.0";
}
BufferedReader rXML = new BufferedReader(new FileReader(file));
while((sLine = rXML.readLine())!=null){
sXML += sLine+"\n";
if((index = sLine.indexOf("address"))>-1)
{
index=sLine.indexOf("\"",index);
indextmp=sLine.indexOf("\"",index+1);
sIP=sLine.substring(index+1,indextmp);
}
}
rXML.close();
}
catch (Exception ex)
{
// OperationLogUtil.println(operationname,"读取网页管理配置失败.");
}
return sIP;
}
public boolean setBondingIP(String newIP,String path){
String sXML = new String();
String sLine = new String();
String sLeft = new String();
String sRight = new String();
int index,indextmp;
try
{
File file = new File(path);
BufferedReader rXML = new BufferedReader(new FileReader(file));
while((sLine = rXML.readLine())!=null){
if((index = sLine.indexOf("URIEncoding"))>-1)
{
if((index = sLine.indexOf("address"))>-1)
{
indextmp=sLine.indexOf("\"",sLine.indexOf("\"",index)+1);
sLeft=sLine.substring(0, index);
sRight=sLine.substring(indextmp+1);
}
else
{
indextmp=sLine.lastIndexOf('/');
sLeft=sLine.substring(0, indextmp);
if(!sLeft.endsWith(" "))
{
sLeft=sLeft+" ";
}
sRight=sLine.substring(indextmp);
}
if(newIP.length()>0)
{
newIP="address=\""+newIP+"\"";
}
sLine=sLeft+newIP+sRight;
}
sXML += sLine+"\n";
}
rXML.close();
BufferedWriter wXML = new BufferedWriter(new FileWriter(file));
wXML.write(sXML);
wXML.close();
}
catch (Exception ex)
{
OperationLogUtil.genLogMsg("ERROR",operationname ,"Failed","Configure Network Failed.",ErrorInfo.returnErrorInfo().get(0),ErrorInfo.returnErrorInfo().get(1));
}
return true;
}
public void setWebBond(boolean webbond) {
this.webbond = webbond;
}
public boolean getWebBond() {
return webbond;
}
public boolean getBond() {
return bond;
}
public void setBond(boolean bond) {
this.bond = bond;
}
public void store() throws NoPrivilegeException, DeviceException {
LogUtil.println("store(): "+this.toString());
Privilege rights = new Privilege();
if( !rights.check(Privilege.PRIVILEGE_MODIFY_NETWORK_CONFIG) ) {
OperationLogUtil.genLogMsg("ERROR","Check Privilege" ,"Failed",Privilege.getPrivilegeInfo(Privilege.PRIVILEGE_MODIFY_NETWORK_CONFIG), ErrorInfo.returnErrorInfo().get(0),ErrorInfo.returnErrorInfo().get(1));
throw new NoPrivilegeException(Privilege.getPrivilegeInfo(Privilege.PRIVILEGE_MODIFY_NETWORK_CONFIG));
}
Properties props=System.getProperties();
String path;
if(props.getProperty("os.arch").indexOf("arm")<0)
{
if(bond) {
try {
File file1 = new File(BOND0NOBOND);
File file2 = new File(BOND0);
boolean mv = file1.renameTo(file2);
for (int i=0; i<MAX_ETH_COUNT; i++) {
String oldPath = ETH + i + ETHBONDSUFFIX;
String newPath = ETH + i;
ConfigUtil.copyFile(oldPath, newPath);
}
} catch (Exception ex) {
LogUtil.println("cp eth config error: " + ex);
throw new DeviceException("修改网络配置文件错误-1!");
}
path = BOND0;
} else {
if(index == 0) {
try {
File file1 = new File(BOND0NOBOND);
File file2 = new File(BOND0);
file2.renameTo(file1);
for (int i=0; i<MAX_ETH_COUNT; i++) {
String oldPath = ETH + i + ETHNOBONDSUFFIX;
String newPath = ETH + i;
ConfigUtil.copyFile(oldPath, newPath);
}
} catch (Exception ex) {
LogUtil.println("cp eth config error: " + ex);
throw new DeviceException("修改网络配置文件错误-2!");
}
}
path = ETH + index;
}
}
else
{
path = NETCONFIG;
}
Properties p = new Properties();
File eth = new File(path);
if( !eth.exists()) {
throw new DeviceException("文件不存在[ "+eth.getAbsolutePath()+"]");
}
try {
FileInputStream fis = new FileInputStream(eth);
p.load(fis);
fis.close();
p.setProperty("IPADDR", ip);
p.setProperty("NETMASK", mask);
p.setProperty("GATEWAY", gateway);
//add by zxq 2014-5-15 for stroe file
//Properties.store add '\' before '='
//FileOutputStream fos = new FileOutputStream(eth);
//p.store(fos, null);
//fos.close();
//
FileWriter writer = new FileWriter(path);
Enumeration<Object> enums = p.keys();
while(enums.hasMoreElements()){
String key = (String)enums.nextElement();
writer.write(key+"="+p.getProperty(key)+"\n");
}
writer.flush();
writer.close();
//end add by zxq 2014-5-15
//add by GAO, 2012/5/10
if (props.getProperty("os.arch").indexOf("arm")<0 &&(!gateway.isEmpty()) && (gateway.compareTo("0.0.0.0") != 0)) {
this.storeRoute();
}
Process process = Runtime.getRuntime().exec("sync");
process.waitFor();
if (getBond()||this.index == WEBETH)
{
String webip = getBondingIP(WEBCONFXML);
if( !getWebBond() )
{
if(webip.compareTo("")!=0 )
{
// OperationLogUtil.println(operationname,"不绑定网页服务ip.");
// OperationLogUtil.println(operationname,"需重启管理服务,解除.");
// OperationLogUtil.println(operationname,"需重启管理服务,web."+webip);
// setBondingIP("",WEBCONFXML);
// process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","/mnt/linux/tomcat6/restart &"});
// process.waitFor();
// OperationLogUtil.println(operationname,"重启管理服务.");
}
}
else
{
String bondingIP ;
bondingIP = this.getIp();
if(webip.compareTo(bondingIP)!=0)
{
OperationLogUtil.genLogMsg("INFO",operationname ,"success",null,null,null);
// OperationLogUtil.println(operationname,"需重启管理服务,ip."+bondingIP);
// OperationLogUtil.println(operationname,"需重启管理服务,web."+webip);
setBondingIP(bondingIP,WEBCONFXML);
// process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","/mnt/linux/tomcat6/restart &"});
// process.waitFor();
// OperationLogUtil.println(operationname,"重启管理服务.");
}
}
}
if (bond)
OperationLogUtil.genLogMsg("INFO",operationname ,"success",null,null,null);
else
OperationLogUtil.genLogMsg("INFO",operationname ,"success",null,null,null);
} catch(Exception e) {
OperationLogUtil.genLogMsg("ERROR",operationname ,"Failed","Configure Network Failed.",ErrorInfo.returnErrorInfo().get(0),ErrorInfo.returnErrorInfo().get(1));
throw new DeviceException(""+e);
}
}
private void storeRoute() throws Exception {
FileOutputStream fos = new FileOutputStream(ROUTE);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write("default "+gateway+" - -\n");
bw.close();
fos.close();
}
public void restart() throws DeviceException, NoPrivilegeException {
// 检查权限
Privilege rights = new Privilege();
if( !rights.check(Privilege.PRIVILEGE_RESTART_NETWORK) ) {
throw new NoPrivilegeException(Privilege.getPrivilegeInfo(Privilege.PRIVILEGE_RESTART_NETWORK));
}
try {
Properties props=System.getProperties();
Process process;
if(props.getProperty("os.arch").indexOf("arm")<0)
{
process = Runtime.getRuntime().exec("sudo /etc/init.d/network restart");
process.waitFor();
}
else
{
process = Runtime.getRuntime().exec(NETEXEC);
process.waitFor();
}
OperationLogUtil.genLogMsg("INFO",operationname ,"success",null,null,null);
String webip = getBondingIP(WEBCONFXML);
String currentIp = getBondingIP(WEBCONFCOPY);
if(nEth != 1 && webip.compareTo(currentIp) != 0 )
{
// OperationLogUtil.println(operationname,"不绑定网页服务.");
// OperationLogUtil.println(operationname,"需重启管理服务,解除.");
// OperationLogUtil.println(operationname,"需重启管理服务,web."+webip);
process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","/mnt/linux/tomcat6/restart &"});
process.waitFor();
ConfigUtil.copyFile(WEBCONFXML, WEBCONFCOPY);
}
/* else
{
OperationLogUtil.println(operationname,"Limit Web Management IP Succeed.");
String bondingIP ;
if( interlist.get(0).getBond())
bondingIP=interlist.get(0).getIp();
else
bondingIP=interlist.get(1).getIp();
if(webip.compareTo(bondingIP)!=0)
{
// OperationLogUtil.println(operationname,"需重启管理服务,ip."+bondingIP);
// OperationLogUtil.println(operationname,"需重启管理服务,web."+webip);
setBondingIP(bondingIP,WEBCONFXML);
process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","/mnt/linux/tomcat6/restart &"});
process.waitFor();
OperationLogUtil.println(operationname,"Restart Network Succeed.");
}
}*/
} catch (Exception ex) {
LogUtil.println("sudo /etc/init.d/network restart error: " + ex);
OperationLogUtil.genLogMsg("ERROR",operationname ,"Failed","Restart Network Failed.",ErrorInfo.returnErrorInfo().get(0),ErrorInfo.returnErrorInfo().get(1));
throw new DeviceException("重启网络错误!");
}
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
}
public List<NetworkInfo> getNetworks() throws NoPrivilegeException, DeviceException {
Privilege rights = new Privilege();
if( !rights.check(Privilege.PRIVILEGE_SHOW_NETWORK_CONFIG) ) {
throw new NoPrivilegeException(Privilege.getPrivilegeInfo(Privilege.PRIVILEGE_SHOW_NETWORK_CONFIG));
}
Properties props=System.getProperties();
List<NetworkInfo> list = new ArrayList<NetworkInfo>(MAX_ETH_COUNT);
Properties p = new Properties();
File bond0 = new File(BOND0);
if(bond0.exists()) {
try {
FileInputStream fis = new FileInputStream(bond0);
p.load(fis);
String tName = p.getProperty("DEVICE");
String tIp = p.getProperty("IPADDR");
String tMask = p.getProperty("NETMASK");
String tGateway = p.getProperty("GATEWAY");
NetworkInfo net = new NetworkInfo(0, tName, tIp, tMask, tGateway);
net.setBond(true);
LogUtil.println("load() -> eth0: "+net.toString());
list.add(net);
fis.close();
} catch (Exception ex) {
// can't do exception
}
p.clear();
return list;
}
if(props.getProperty("os.arch").indexOf("arm")<0)
{
for(int i=0; i<MAX_ETH_COUNT; i++) {
File eth = new File(ETH + i);
if(eth.exists()) {
try {
FileInputStream fis = new FileInputStream(eth);
p.load(fis);
String tName = p.getProperty("DEVICE");
String tIp = p.getProperty("IPADDR");
String tMask = p.getProperty("NETMASK");
String tGateway = p.getProperty("GATEWAY");
NetworkInfo net = new NetworkInfo(i, tName, tIp, tMask, tGateway);
net.setBond(false);
LogUtil.println("load() -> eth0: "+net.toString());
list.add(net);
fis.close();
nEth ++;
} catch (Exception ex) {
// can't do exception
}
} else {
break;
}
p.clear();
}}
else
{
File eth = new File(NETCONFIG);
if(eth.exists()) {
try {
FileInputStream fis = new FileInputStream(eth);
p.load(fis);
String tName = p.getProperty("DEVICE");
String tIp = p.getProperty("IPADDR");
String tMask = p.getProperty("NETMASK");
String tGateway = p.getProperty("GATEWAY");
NetworkInfo net = new NetworkInfo(0, tName, tIp, tMask, tGateway);
net.setBond(false);
LogUtil.println("load() -> eth0: "+net.toString());
list.add(net);
fis.close();
nEth ++;
} catch (Exception ex) {
// can't do exception
}
p.clear();
}
}
return list;
}
@Override
public String toString() {
return "index = "+index + "\n"+
"name = "+name +"\n"+
"DEVICE = "+name + "\n"+
"IPADDR = "+ip + "\n"+
"NETWORK = "+mask + "\n"+
"GATEWAY = "+gateway;
}
public static void main(String[] args) throws NoPrivilegeException, DeviceException {
List<NetworkInfo> list = new NetworkInfo().getNetworks();
System.out.println(list);
}
}
| UTF-8 | Java | 19,347 | java | NetworkInfo.java | Java | [
{
"context": ";\nimport java.util.Enumeration;\n\n/**\n *\n * @author root\n */\npublic class NetworkInfo {\n\t public static fi",
"end": 797,
"score": 0.9958354234695435,
"start": 793,
"tag": "USERNAME",
"value": "root"
},
{
"context": "Property(\"GATEWAY\", gateway);\n /... | null | [] | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.sansec.hsm.bean.config;
import com.sansec.hsm.bean.Privilege;
import com.sansec.hsm.exception.DeviceException;
import com.sansec.hsm.exception.NoPrivilegeException;
import com.sansec.hsm.util.ConfigUtil;
import com.sansec.hsm.util.ErrorInfo;
import com.sansec.hsm.util.OperationLogUtil;
import debug.log.LogUtil;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.Properties;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Enumeration;
/**
*
* @author root
*/
public class NetworkInfo {
public static final String operationname = "NETWORK MANAGEMENT";
public static final int MAX_ETH_COUNT = 4;
public static final String BOND0 = "/etc/sysconfig/network-scripts/ifcfg-bond0";
public static final String ETH = "/etc/sysconfig/network-scripts/ifcfg-eth";
public static final String NETCONFIG = "/mnt/linux/etc/network.param";
public static final String NETEXEC = "/mnt/linux/etc/network.sh";
public static final String ROUTE = "/etc/sysconfig/network-scripts/routes";
public static final String BOND0NOBOND = "/etc/sysconfig/network-scripts/ifcfg-bond0.bond";
public static final String ETHNOBONDSUFFIX = ".nobond";
public static final String ETHBONDSUFFIX = ".bond";
public static final String WEBCONFXML = "/mnt/linux/tomcat6/conf/server.xml";
public static final String WEBCONFCOPY = "/mnt/linux/tomcat6/conf/ex.server.xml";
public static final int WEBETH = 1;
// index=0 -> eth0, index=1 -> eth1
private int index;
private int nEth = 0;//非绑定网口数量
private String name;
private String ip;
private String mask;
private String gateway;
private boolean bond = false;
private boolean webbond = false;
public NetworkInfo() {
}
public NetworkInfo(int index, String name, String ip, String mask, String gateway) {
this.index = index;
this.name = name;
this.ip = ip;
this.mask = mask;
this.gateway = gateway;
}
public String getIp() {
return ip;
}
public String getMask() {
return mask;
}
public String getGateway() {
return gateway;
}
public int getIndex() {
return index;
}
public String getName() {
return name;
}
public String getBondingIP(String path){
String sXML = new String();
String sLine = new String();
String sIP = new String();
int index,indextmp;
try
{
if (path.isEmpty()) {
path=WEBCONFXML;
}
File file = new File(path);
if(!file.exists()) {
// OperationLogUtil.println(operationname,"配置文件不存在.");
return "0.0.0.0";
}
BufferedReader rXML = new BufferedReader(new FileReader(file));
while((sLine = rXML.readLine())!=null){
sXML += sLine+"\n";
if((index = sLine.indexOf("address"))>-1)
{
index=sLine.indexOf("\"",index);
indextmp=sLine.indexOf("\"",index+1);
sIP=sLine.substring(index+1,indextmp);
}
}
rXML.close();
}
catch (Exception ex)
{
// OperationLogUtil.println(operationname,"读取网页管理配置失败.");
}
return sIP;
}
public boolean setBondingIP(String newIP,String path){
String sXML = new String();
String sLine = new String();
String sLeft = new String();
String sRight = new String();
int index,indextmp;
try
{
File file = new File(path);
BufferedReader rXML = new BufferedReader(new FileReader(file));
while((sLine = rXML.readLine())!=null){
if((index = sLine.indexOf("URIEncoding"))>-1)
{
if((index = sLine.indexOf("address"))>-1)
{
indextmp=sLine.indexOf("\"",sLine.indexOf("\"",index)+1);
sLeft=sLine.substring(0, index);
sRight=sLine.substring(indextmp+1);
}
else
{
indextmp=sLine.lastIndexOf('/');
sLeft=sLine.substring(0, indextmp);
if(!sLeft.endsWith(" "))
{
sLeft=sLeft+" ";
}
sRight=sLine.substring(indextmp);
}
if(newIP.length()>0)
{
newIP="address=\""+newIP+"\"";
}
sLine=sLeft+newIP+sRight;
}
sXML += sLine+"\n";
}
rXML.close();
BufferedWriter wXML = new BufferedWriter(new FileWriter(file));
wXML.write(sXML);
wXML.close();
}
catch (Exception ex)
{
OperationLogUtil.genLogMsg("ERROR",operationname ,"Failed","Configure Network Failed.",ErrorInfo.returnErrorInfo().get(0),ErrorInfo.returnErrorInfo().get(1));
}
return true;
}
public void setWebBond(boolean webbond) {
this.webbond = webbond;
}
public boolean getWebBond() {
return webbond;
}
public boolean getBond() {
return bond;
}
public void setBond(boolean bond) {
this.bond = bond;
}
public void store() throws NoPrivilegeException, DeviceException {
LogUtil.println("store(): "+this.toString());
Privilege rights = new Privilege();
if( !rights.check(Privilege.PRIVILEGE_MODIFY_NETWORK_CONFIG) ) {
OperationLogUtil.genLogMsg("ERROR","Check Privilege" ,"Failed",Privilege.getPrivilegeInfo(Privilege.PRIVILEGE_MODIFY_NETWORK_CONFIG), ErrorInfo.returnErrorInfo().get(0),ErrorInfo.returnErrorInfo().get(1));
throw new NoPrivilegeException(Privilege.getPrivilegeInfo(Privilege.PRIVILEGE_MODIFY_NETWORK_CONFIG));
}
Properties props=System.getProperties();
String path;
if(props.getProperty("os.arch").indexOf("arm")<0)
{
if(bond) {
try {
File file1 = new File(BOND0NOBOND);
File file2 = new File(BOND0);
boolean mv = file1.renameTo(file2);
for (int i=0; i<MAX_ETH_COUNT; i++) {
String oldPath = ETH + i + ETHBONDSUFFIX;
String newPath = ETH + i;
ConfigUtil.copyFile(oldPath, newPath);
}
} catch (Exception ex) {
LogUtil.println("cp eth config error: " + ex);
throw new DeviceException("修改网络配置文件错误-1!");
}
path = BOND0;
} else {
if(index == 0) {
try {
File file1 = new File(BOND0NOBOND);
File file2 = new File(BOND0);
file2.renameTo(file1);
for (int i=0; i<MAX_ETH_COUNT; i++) {
String oldPath = ETH + i + ETHNOBONDSUFFIX;
String newPath = ETH + i;
ConfigUtil.copyFile(oldPath, newPath);
}
} catch (Exception ex) {
LogUtil.println("cp eth config error: " + ex);
throw new DeviceException("修改网络配置文件错误-2!");
}
}
path = ETH + index;
}
}
else
{
path = NETCONFIG;
}
Properties p = new Properties();
File eth = new File(path);
if( !eth.exists()) {
throw new DeviceException("文件不存在[ "+eth.getAbsolutePath()+"]");
}
try {
FileInputStream fis = new FileInputStream(eth);
p.load(fis);
fis.close();
p.setProperty("IPADDR", ip);
p.setProperty("NETMASK", mask);
p.setProperty("GATEWAY", gateway);
//add by zxq 2014-5-15 for stroe file
//Properties.store add '\' before '='
//FileOutputStream fos = new FileOutputStream(eth);
//p.store(fos, null);
//fos.close();
//
FileWriter writer = new FileWriter(path);
Enumeration<Object> enums = p.keys();
while(enums.hasMoreElements()){
String key = (String)enums.nextElement();
writer.write(key+"="+p.getProperty(key)+"\n");
}
writer.flush();
writer.close();
//end add by zxq 2014-5-15
//add by GAO, 2012/5/10
if (props.getProperty("os.arch").indexOf("arm")<0 &&(!gateway.isEmpty()) && (gateway.compareTo("0.0.0.0") != 0)) {
this.storeRoute();
}
Process process = Runtime.getRuntime().exec("sync");
process.waitFor();
if (getBond()||this.index == WEBETH)
{
String webip = getBondingIP(WEBCONFXML);
if( !getWebBond() )
{
if(webip.compareTo("")!=0 )
{
// OperationLogUtil.println(operationname,"不绑定网页服务ip.");
// OperationLogUtil.println(operationname,"需重启管理服务,解除.");
// OperationLogUtil.println(operationname,"需重启管理服务,web."+webip);
// setBondingIP("",WEBCONFXML);
// process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","/mnt/linux/tomcat6/restart &"});
// process.waitFor();
// OperationLogUtil.println(operationname,"重启管理服务.");
}
}
else
{
String bondingIP ;
bondingIP = this.getIp();
if(webip.compareTo(bondingIP)!=0)
{
OperationLogUtil.genLogMsg("INFO",operationname ,"success",null,null,null);
// OperationLogUtil.println(operationname,"需重启管理服务,ip."+bondingIP);
// OperationLogUtil.println(operationname,"需重启管理服务,web."+webip);
setBondingIP(bondingIP,WEBCONFXML);
// process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","/mnt/linux/tomcat6/restart &"});
// process.waitFor();
// OperationLogUtil.println(operationname,"重启管理服务.");
}
}
}
if (bond)
OperationLogUtil.genLogMsg("INFO",operationname ,"success",null,null,null);
else
OperationLogUtil.genLogMsg("INFO",operationname ,"success",null,null,null);
} catch(Exception e) {
OperationLogUtil.genLogMsg("ERROR",operationname ,"Failed","Configure Network Failed.",ErrorInfo.returnErrorInfo().get(0),ErrorInfo.returnErrorInfo().get(1));
throw new DeviceException(""+e);
}
}
private void storeRoute() throws Exception {
FileOutputStream fos = new FileOutputStream(ROUTE);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
bw.write("default "+gateway+" - -\n");
bw.close();
fos.close();
}
public void restart() throws DeviceException, NoPrivilegeException {
// 检查权限
Privilege rights = new Privilege();
if( !rights.check(Privilege.PRIVILEGE_RESTART_NETWORK) ) {
throw new NoPrivilegeException(Privilege.getPrivilegeInfo(Privilege.PRIVILEGE_RESTART_NETWORK));
}
try {
Properties props=System.getProperties();
Process process;
if(props.getProperty("os.arch").indexOf("arm")<0)
{
process = Runtime.getRuntime().exec("sudo /etc/init.d/network restart");
process.waitFor();
}
else
{
process = Runtime.getRuntime().exec(NETEXEC);
process.waitFor();
}
OperationLogUtil.genLogMsg("INFO",operationname ,"success",null,null,null);
String webip = getBondingIP(WEBCONFXML);
String currentIp = getBondingIP(WEBCONFCOPY);
if(nEth != 1 && webip.compareTo(currentIp) != 0 )
{
// OperationLogUtil.println(operationname,"不绑定网页服务.");
// OperationLogUtil.println(operationname,"需重启管理服务,解除.");
// OperationLogUtil.println(operationname,"需重启管理服务,web."+webip);
process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","/mnt/linux/tomcat6/restart &"});
process.waitFor();
ConfigUtil.copyFile(WEBCONFXML, WEBCONFCOPY);
}
/* else
{
OperationLogUtil.println(operationname,"Limit Web Management IP Succeed.");
String bondingIP ;
if( interlist.get(0).getBond())
bondingIP=interlist.get(0).getIp();
else
bondingIP=interlist.get(1).getIp();
if(webip.compareTo(bondingIP)!=0)
{
// OperationLogUtil.println(operationname,"需重启管理服务,ip."+bondingIP);
// OperationLogUtil.println(operationname,"需重启管理服务,web."+webip);
setBondingIP(bondingIP,WEBCONFXML);
process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","/mnt/linux/tomcat6/restart &"});
process.waitFor();
OperationLogUtil.println(operationname,"Restart Network Succeed.");
}
}*/
} catch (Exception ex) {
LogUtil.println("sudo /etc/init.d/network restart error: " + ex);
OperationLogUtil.genLogMsg("ERROR",operationname ,"Failed","Restart Network Failed.",ErrorInfo.returnErrorInfo().get(0),ErrorInfo.returnErrorInfo().get(1));
throw new DeviceException("重启网络错误!");
}
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
}
public List<NetworkInfo> getNetworks() throws NoPrivilegeException, DeviceException {
Privilege rights = new Privilege();
if( !rights.check(Privilege.PRIVILEGE_SHOW_NETWORK_CONFIG) ) {
throw new NoPrivilegeException(Privilege.getPrivilegeInfo(Privilege.PRIVILEGE_SHOW_NETWORK_CONFIG));
}
Properties props=System.getProperties();
List<NetworkInfo> list = new ArrayList<NetworkInfo>(MAX_ETH_COUNT);
Properties p = new Properties();
File bond0 = new File(BOND0);
if(bond0.exists()) {
try {
FileInputStream fis = new FileInputStream(bond0);
p.load(fis);
String tName = p.getProperty("DEVICE");
String tIp = p.getProperty("IPADDR");
String tMask = p.getProperty("NETMASK");
String tGateway = p.getProperty("GATEWAY");
NetworkInfo net = new NetworkInfo(0, tName, tIp, tMask, tGateway);
net.setBond(true);
LogUtil.println("load() -> eth0: "+net.toString());
list.add(net);
fis.close();
} catch (Exception ex) {
// can't do exception
}
p.clear();
return list;
}
if(props.getProperty("os.arch").indexOf("arm")<0)
{
for(int i=0; i<MAX_ETH_COUNT; i++) {
File eth = new File(ETH + i);
if(eth.exists()) {
try {
FileInputStream fis = new FileInputStream(eth);
p.load(fis);
String tName = p.getProperty("DEVICE");
String tIp = p.getProperty("IPADDR");
String tMask = p.getProperty("NETMASK");
String tGateway = p.getProperty("GATEWAY");
NetworkInfo net = new NetworkInfo(i, tName, tIp, tMask, tGateway);
net.setBond(false);
LogUtil.println("load() -> eth0: "+net.toString());
list.add(net);
fis.close();
nEth ++;
} catch (Exception ex) {
// can't do exception
}
} else {
break;
}
p.clear();
}}
else
{
File eth = new File(NETCONFIG);
if(eth.exists()) {
try {
FileInputStream fis = new FileInputStream(eth);
p.load(fis);
String tName = p.getProperty("DEVICE");
String tIp = p.getProperty("IPADDR");
String tMask = p.getProperty("NETMASK");
String tGateway = p.getProperty("GATEWAY");
NetworkInfo net = new NetworkInfo(0, tName, tIp, tMask, tGateway);
net.setBond(false);
LogUtil.println("load() -> eth0: "+net.toString());
list.add(net);
fis.close();
nEth ++;
} catch (Exception ex) {
// can't do exception
}
p.clear();
}
}
return list;
}
@Override
public String toString() {
return "index = "+index + "\n"+
"name = "+name +"\n"+
"DEVICE = "+name + "\n"+
"IPADDR = "+ip + "\n"+
"NETWORK = "+mask + "\n"+
"GATEWAY = "+gateway;
}
public static void main(String[] args) throws NoPrivilegeException, DeviceException {
List<NetworkInfo> list = new NetworkInfo().getNetworks();
System.out.println(list);
}
}
| 19,347 | 0.500971 | 0.495249 | 520 | 35.63269 | 29.85519 | 229 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.715385 | false | false | 8 |
77fd1be88547a23481e92f72ec6aa412f0abe365 | 30,039,001,275,913 | 4e1c7b612c037666af333c079d5d5db237e7e0ff | /src/block_chain/Mine_Block.java | 0781455563cb0a206feeb9b2433e83024219ee74 | [] | no_license | UzairAhmed14/BlockChainProject | https://github.com/UzairAhmed14/BlockChainProject | ce706c4d61147d7ec2c0a62355f08fd21e5dd74d | 4349d1381ddc97d620cecc25977baa9b636ada02 | refs/heads/master | 2020-05-21T10:31:57.552000 | 2019-11-23T16:56:36 | 2019-11-23T16:56:36 | 186,013,361 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | /*
* 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 block_chain;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
*
* @author Uzair Ahmed
*/
public class Mine_Block extends javax.swing.JFrame {
/**
* Creates new form Mine_Block
*/
public Mine_Block() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
btnloadblocks = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jTextPane1 = new javax.swing.JTextPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
jLabel1.setText("Mine Blocks");
btnloadblocks.setText("Load Blocks");
btnloadblocks.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnloadblocksActionPerformed(evt);
}
});
jScrollPane2.setViewportView(jTextPane1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(138, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(128, 128, 128))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addComponent(btnloadblocks))
.addGroup(layout.createSequentialGroup()
.addGap(96, 96, 96)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnloadblocks)
.addGap(120, 120, 120)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(72, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnloadblocksActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnloadblocksActionPerformed
try {
// TODO add your handling code here:
XmlLoadBlock();
} catch (TransformerException | ParserConfigurationException | SAXException | IOException ex) {
Logger.getLogger(Mine_Block.class.getName()).log(Level.SEVERE, null, ex);
}
// jTextPane1.setContentType("text/xml");
// jTextPane1.setText("UnminedBlocks");
}//GEN-LAST:event_btnloadblocksActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Mine_Block.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Mine_Block.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Mine_Block.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Mine_Block.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Mine_Block().setVisible(true);
}
});
}
public void XmlLoadBlock() throws TransformerConfigurationException, TransformerException, ParserConfigurationException, SAXException, IOException, IOException{
File xmlfile = new File("./UnminedBlocks.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document d = db.parse(xmlfile);
NodeList list = d.getElementsByTagName("Blocks");
for(int i = 0; i <list.getLength(); i++){
Node node = list.item(i);
Element element = (Element) node;
String Pk = element.getElementsByTagName("PublicKey").item(0).getTextContent();
String fund = element.getElementsByTagName("Funds").item(0).getTextContent();
JOptionPane.showMessageDialog(null, Pk, fund, JOptionPane.INFORMATION_MESSAGE);
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnloadblocks;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextPane jTextPane1;
// End of variables declaration//GEN-END:variables
}
| UTF-8 | Java | 7,797 | java | Mine_Block.java | Java | [
{
"context": "mport org.xml.sax.SAXException;\n\n/**\n *\n * @author Uzair Ahmed\n */\npublic class Mine_Block extends javax.swing.J",
"end": 988,
"score": 0.9998031854629517,
"start": 977,
"tag": "NAME",
"value": "Uzair Ahmed"
}
] | null | [] | /*
* 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 block_chain;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
*
* @author <NAME>
*/
public class Mine_Block extends javax.swing.JFrame {
/**
* Creates new form Mine_Block
*/
public Mine_Block() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
btnloadblocks = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jTextPane1 = new javax.swing.JTextPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N
jLabel1.setText("Mine Blocks");
btnloadblocks.setText("Load Blocks");
btnloadblocks.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnloadblocksActionPerformed(evt);
}
});
jScrollPane2.setViewportView(jTextPane1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(138, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(128, 128, 128))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(26, 26, 26)
.addComponent(btnloadblocks))
.addGroup(layout.createSequentialGroup()
.addGap(96, 96, 96)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnloadblocks)
.addGap(120, 120, 120)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(72, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnloadblocksActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnloadblocksActionPerformed
try {
// TODO add your handling code here:
XmlLoadBlock();
} catch (TransformerException | ParserConfigurationException | SAXException | IOException ex) {
Logger.getLogger(Mine_Block.class.getName()).log(Level.SEVERE, null, ex);
}
// jTextPane1.setContentType("text/xml");
// jTextPane1.setText("UnminedBlocks");
}//GEN-LAST:event_btnloadblocksActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Mine_Block.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Mine_Block.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Mine_Block.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Mine_Block.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Mine_Block().setVisible(true);
}
});
}
public void XmlLoadBlock() throws TransformerConfigurationException, TransformerException, ParserConfigurationException, SAXException, IOException, IOException{
File xmlfile = new File("./UnminedBlocks.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document d = db.parse(xmlfile);
NodeList list = d.getElementsByTagName("Blocks");
for(int i = 0; i <list.getLength(); i++){
Node node = list.item(i);
Element element = (Element) node;
String Pk = element.getElementsByTagName("PublicKey").item(0).getTextContent();
String fund = element.getElementsByTagName("Funds").item(0).getTextContent();
JOptionPane.showMessageDialog(null, Pk, fund, JOptionPane.INFORMATION_MESSAGE);
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnloadblocks;
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextPane jTextPane1;
// End of variables declaration//GEN-END:variables
}
| 7,792 | 0.662691 | 0.653456 | 176 | 43.301136 | 35.097675 | 161 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.664773 | false | false | 8 |
16d48c4da4fbf97f945e0e6e5840bcc77781ede7 | 30,039,001,274,117 | 70f10b005807b6035e229e008ba50f59760ffc88 | /src/main/java/bus/UserBus.java | 130dda4f9dfcc1e16b909c159cb836b1c517bd7a | [] | no_license | xudaashuai/ThreeLayer | https://github.com/xudaashuai/ThreeLayer | 7abe6c06829da0f4847548d82c996e73b1479db5 | 8e306d7b6df4090a44b5ea54157e99d6399b1dcf | refs/heads/master | 2021-07-16T21:06:01.026000 | 2017-10-24T14:51:14 | 2017-10-24T14:51:14 | 106,690,696 | 1 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package bus;
import dao.UserDAO;
import vo.UserVO;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class UserBus {
private UserDAO userDAO = new UserDAO();
public List<UserVO> getUserById(int id) {
return getUserFromResultSet(userDAO.searchById(id));
}
public List<UserVO> getUserEmailByName(String name) {
return getUserFromResultSet(userDAO.searchByName(name));
}
public List<UserVO> getUserByUser(UserVO user) {
return getUserFromResultSet(userDAO.searchByUser(user));
}
public boolean updateById(UserVO u){
return userDAO.updateById(u);
}
private List<UserVO> getUserFromResultSet(ResultSet resultSet) {
List<UserVO> result=new ArrayList<UserVO>();
try {
while (resultSet.next()) {
UserVO userVO = new UserVO();
userVO.setId(resultSet.getInt(1));
userVO.setFirstName(resultSet.getString(2));
userVO.setLastName(resultSet.getString(3));
userVO.setEmail(resultSet.getString(4));
result.add(userVO);
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
}
| UTF-8 | Java | 1,334 | java | UserBus.java | Java | [] | null | [] | package bus;
import dao.UserDAO;
import vo.UserVO;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class UserBus {
private UserDAO userDAO = new UserDAO();
public List<UserVO> getUserById(int id) {
return getUserFromResultSet(userDAO.searchById(id));
}
public List<UserVO> getUserEmailByName(String name) {
return getUserFromResultSet(userDAO.searchByName(name));
}
public List<UserVO> getUserByUser(UserVO user) {
return getUserFromResultSet(userDAO.searchByUser(user));
}
public boolean updateById(UserVO u){
return userDAO.updateById(u);
}
private List<UserVO> getUserFromResultSet(ResultSet resultSet) {
List<UserVO> result=new ArrayList<UserVO>();
try {
while (resultSet.next()) {
UserVO userVO = new UserVO();
userVO.setId(resultSet.getInt(1));
userVO.setFirstName(resultSet.getString(2));
userVO.setLastName(resultSet.getString(3));
userVO.setEmail(resultSet.getString(4));
result.add(userVO);
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
}
| 1,334 | 0.632684 | 0.629685 | 45 | 28.644444 | 21.854219 | 68 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.488889 | false | false | 8 |
89e91e416943a04c996c8feb9246f80e69cdb192 | 4,217,657,944,127 | eed4eab423cd2933c090647765cdd0f4ae09dc04 | /bos-dao/src/main/java/ncwu/zyj/bos/dao/impl/RoleDaoImpl.java | d0630b0c8d8a12d9ef22f0ec866b2646b55c7faa | [] | no_license | YoJn/logistics-management-information-system | https://github.com/YoJn/logistics-management-information-system | 00b9229960378871af776827361c97fbe4f7852d | 068d793190cc44bc81d79841a26675bf6a8ccbf4 | refs/heads/master | 2020-03-24T13:13:18.684000 | 2018-07-29T08:15:25 | 2018-07-29T08:15:25 | 142,739,158 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package ncwu.zyj.bos.dao.impl;
import org.springframework.stereotype.Repository;
import ncwu.zyj.bos.dao.IRoleDao;
import ncwu.zyj.bos.domain.Role;
@Repository
public class RoleDaoImpl extends BaseDaoImpl<Role> implements IRoleDao{
}
| UTF-8 | Java | 247 | java | RoleDaoImpl.java | Java | [] | null | [] | package ncwu.zyj.bos.dao.impl;
import org.springframework.stereotype.Repository;
import ncwu.zyj.bos.dao.IRoleDao;
import ncwu.zyj.bos.domain.Role;
@Repository
public class RoleDaoImpl extends BaseDaoImpl<Role> implements IRoleDao{
}
| 247 | 0.781377 | 0.781377 | 10 | 22.700001 | 23.289698 | 71 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.4 | false | false | 8 |
12970ef19afe756531b6b62e96007111280f128e | 4,776,003,680,948 | b6a3bdfb22992497f2188640c006d7df4423d616 | /app/src/main/java/com/manre/airappproject/adapter/easybutton/EasyButtonAdapter.java | d86b90219500298d0deac2e2f46f16bec8cde7dd | [
"Apache-2.0"
] | permissive | Rex-Man/AirAppProject | https://github.com/Rex-Man/AirAppProject | 17df97ed8c44b61e007ac2971b6352f52c10301e | 388185e30061281b65e45a6d970867b7cff95fc9 | refs/heads/master | 2021-01-24T16:40:13.100000 | 2018-04-13T08:40:03 | 2018-04-13T08:40:03 | 123,208,229 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.manre.airappproject.adapter.easybutton;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.manre.airappproject.R;
import com.manre.airappproject.adapter.BaseRecyclerAdapter;
import com.manre.airappproject.adapter.BaseRecyclerHolder;
import java.util.List;
/**
* Created by manre on 21/03/2018.
*/
public class EasyButtonAdapter extends BaseRecyclerAdapter<Integer> {
public EasyButtonAdapter(Context context, List<Integer> data,int replaceLayout)
{
initBaseRecyclerAdapter(context,data,replaceLayout,null);
}
@Override
public void onBindViewHolder(@NonNull BaseRecyclerHolder holder, int position) {
super.onBindViewHolder(holder,position);
int buttonResource= getDataList().get(position);
ImageView shownButton=holder.findViewById(R.id.easy_button);
shownButton.setImageResource(buttonResource);
}
}
| UTF-8 | Java | 1,062 | java | EasyButtonAdapter.java | Java | [
{
"context": "Holder;\n\nimport java.util.List;\n\n/**\n * Created by manre on 21/03/2018.\n */\n\npublic class EasyButtonAdapte",
"end": 456,
"score": 0.9994925856590271,
"start": 451,
"tag": "USERNAME",
"value": "manre"
}
] | null | [] | package com.manre.airappproject.adapter.easybutton;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.manre.airappproject.R;
import com.manre.airappproject.adapter.BaseRecyclerAdapter;
import com.manre.airappproject.adapter.BaseRecyclerHolder;
import java.util.List;
/**
* Created by manre on 21/03/2018.
*/
public class EasyButtonAdapter extends BaseRecyclerAdapter<Integer> {
public EasyButtonAdapter(Context context, List<Integer> data,int replaceLayout)
{
initBaseRecyclerAdapter(context,data,replaceLayout,null);
}
@Override
public void onBindViewHolder(@NonNull BaseRecyclerHolder holder, int position) {
super.onBindViewHolder(holder,position);
int buttonResource= getDataList().get(position);
ImageView shownButton=holder.findViewById(R.id.easy_button);
shownButton.setImageResource(buttonResource);
}
}
| 1,062 | 0.764595 | 0.757062 | 41 | 24.902439 | 26.768934 | 84 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.560976 | false | false | 8 |
39d4ce5cf0006b47dfc16884ee7cf3f9decd0ec3 | 171,798,753,554 | 72b968cf8e1d0378f4a94f498e5071f3e0d63e00 | /src/day24_Methods/Test.java | 88180331e874fcddd16ff8e78a0688099bfab08d | [] | no_license | gsaltug/Java2020Class | https://github.com/gsaltug/Java2020Class | c18544cfe2da727928fcb01667a025176856ac95 | dcee1d09c777dfedaa575a3a6435736ba789918e | refs/heads/master | 2022-07-10T19:18:58.875000 | 2020-05-17T20:51:29 | 2020-05-17T20:51:29 | 259,124,853 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package day24_Methods;
import java.util.Arrays;
import Resources.Library;
public class Test {
public static void main(String[] args) {
String str ="Cybertek";
String RevStr = Library.Reverse2(str);
System.out.println(RevStr);//ketrebyC
System.out.println(str.equalsIgnoreCase(RevStr));//false not palindrome
int [] arr = { 2000, 3100, 24000, 2510};
// int des [] = Library.sortDesending(arr);
arr = Library.sortDesending(arr);
Arrays.sort(arr);
System.out.println(Arrays.toString(arr)); //[2000, 2510, 3100, 24000]
}
}
| UTF-8 | Java | 591 | java | Test.java | Java | [
{
"context": "c void main(String[] args) {\n String str =\"Cybertek\";\n\n String RevStr = Library.Reverse2(str);\n",
"end": 169,
"score": 0.8276169896125793,
"start": 161,
"tag": "NAME",
"value": "Cybertek"
}
] | null | [] | package day24_Methods;
import java.util.Arrays;
import Resources.Library;
public class Test {
public static void main(String[] args) {
String str ="Cybertek";
String RevStr = Library.Reverse2(str);
System.out.println(RevStr);//ketrebyC
System.out.println(str.equalsIgnoreCase(RevStr));//false not palindrome
int [] arr = { 2000, 3100, 24000, 2510};
// int des [] = Library.sortDesending(arr);
arr = Library.sortDesending(arr);
Arrays.sort(arr);
System.out.println(Arrays.toString(arr)); //[2000, 2510, 3100, 24000]
}
}
| 591 | 0.648054 | 0.585448 | 24 | 23.625 | 24.21916 | 79 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 8 |
195215e30811d180f86fb094989ec2ff69499dd5 | 18,648,748,052,203 | cfd150c541b20c8673b41f9064e7635e5d0dc421 | /app/src/main/java/com/zzcar/zzc/models/ShouzhiItem.java | f3b37e4db6ef75ee403efc70a9921499c4d9000e | [] | no_license | ruhui/ZZC | https://github.com/ruhui/ZZC | 4423b9aecd0b6d9e6aadf3972b1342192495c3a4 | 5a605ee498640fba92fed9c6281c47bed05df3de | refs/heads/master | 2021-01-19T23:49:10.969000 | 2017-08-16T11:37:04 | 2017-08-16T11:37:04 | 89,010,031 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.zzcar.zzc.models;
/**
* 描述:
* 作者:黄如辉 时间 2017/5/20.
*/
public class ShouzhiItem {
private int object_id;
private String id;
private int type;
private String name;
private double ammount;
private String time;
private String status_name;
public ShouzhiItem(int object_id, String id, int type, String name, double ammount, String time, String status_name) {
this.object_id = object_id;
this.id = id;
this.type = type;
this.name = name;
this.ammount = ammount;
this.time = time;
this.status_name = status_name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getObject_id() {
return object_id;
}
public void setObject_id(int object_id) {
this.object_id = object_id;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getAmmount() {
return ammount;
}
public void setAmmount(double ammount) {
this.ammount = ammount;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getStatus_name() {
return status_name;
}
public void setStatus_name(String status_name) {
this.status_name = status_name;
}
public String getTypeDes(){
String destype = "";
switch (type){
case 0:
destype = "";
break;
case 1:
destype = "收款";
break;
case 2:
destype = "订单收入";
break;
case 3:
destype = "退款";
break;
case 4:
destype = "提现";
break;
case 5:
destype = "分润";
break;
case 6:
destype = "手续费";
break;
case 7:
destype = "支付";
break;
case 8:
destype = "充值";
break;
case 9:
destype = "积分充值";
break;
case 10:
destype = "退回手续费";
break;
case 11:
destype = "交易担保";
break;
}
return destype;
}
public boolean isIntent(){
//6交易手续费、9购买积分、5分润、10退还手续费,11交易担保,不用跳到详情
if (type == 6 || type == 9 || type == 5 || type == 10 || type == 11 || type == 8){
return false;
}else{
return true;
}
}
}
//"object_id": 1,
// "type": 0,
// "name": "sample string 2",
// "ammount": 3.0,
// "time": "sample string 4",
// "status_name": "sample string 5"
| UTF-8 | Java | 3,217 | java | ShouzhiItem.java | Java | [
{
"context": "package com.zzcar.zzc.models;\n\n/**\n * 描述:\n * 作者:黄如辉 时间 2017/5/20.\n */\n\npublic class ShouzhiItem {\n ",
"end": 51,
"score": 0.9996823072433472,
"start": 48,
"tag": "NAME",
"value": "黄如辉"
}
] | null | [] | package com.zzcar.zzc.models;
/**
* 描述:
* 作者:黄如辉 时间 2017/5/20.
*/
public class ShouzhiItem {
private int object_id;
private String id;
private int type;
private String name;
private double ammount;
private String time;
private String status_name;
public ShouzhiItem(int object_id, String id, int type, String name, double ammount, String time, String status_name) {
this.object_id = object_id;
this.id = id;
this.type = type;
this.name = name;
this.ammount = ammount;
this.time = time;
this.status_name = status_name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getObject_id() {
return object_id;
}
public void setObject_id(int object_id) {
this.object_id = object_id;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getAmmount() {
return ammount;
}
public void setAmmount(double ammount) {
this.ammount = ammount;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getStatus_name() {
return status_name;
}
public void setStatus_name(String status_name) {
this.status_name = status_name;
}
public String getTypeDes(){
String destype = "";
switch (type){
case 0:
destype = "";
break;
case 1:
destype = "收款";
break;
case 2:
destype = "订单收入";
break;
case 3:
destype = "退款";
break;
case 4:
destype = "提现";
break;
case 5:
destype = "分润";
break;
case 6:
destype = "手续费";
break;
case 7:
destype = "支付";
break;
case 8:
destype = "充值";
break;
case 9:
destype = "积分充值";
break;
case 10:
destype = "退回手续费";
break;
case 11:
destype = "交易担保";
break;
}
return destype;
}
public boolean isIntent(){
//6交易手续费、9购买积分、5分润、10退还手续费,11交易担保,不用跳到详情
if (type == 6 || type == 9 || type == 5 || type == 10 || type == 11 || type == 8){
return false;
}else{
return true;
}
}
}
//"object_id": 1,
// "type": 0,
// "name": "sample string 2",
// "ammount": 3.0,
// "time": "sample string 4",
// "status_name": "sample string 5"
| 3,217 | 0.456854 | 0.442852 | 141 | 20.780142 | 16.537125 | 122 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.560284 | false | false | 8 |
2afab121485e6b6f6ee3db10d7057a5ab0ba1a99 | 30,365,418,825,873 | 05e2e97978726925c1024f3944e0d40cbd4ad64c | /foodie-service/src/main/java/com/imooc/service/impl/AddressServiceImpl.java | 16c859280fbd660fa31429c17e1519c2df6adcd6 | [] | no_license | chuckma/foodie | https://github.com/chuckma/foodie | 57869f00b3cc227131223cf36f32d39775167e48 | eea255a6ca4bad4de8061c8473c39df5d97b9ad8 | refs/heads/master | 2022-08-07T00:31:02.567000 | 2019-12-18T13:53:51 | 2019-12-18T13:53:51 | 221,637,256 | 0 | 0 | null | false | 2022-06-21T02:14:12 | 2019-11-14T07:28:25 | 2019-12-18T13:54:11 | 2022-06-21T02:14:11 | 219 | 0 | 0 | 2 | Java | false | false | package com.imooc.service.impl;
import com.imooc.enums.YesOrNo;
import com.imooc.mapper.CarouselMapper;
import com.imooc.mapper.UserAddressMapper;
import com.imooc.pojo.Carousel;
import com.imooc.pojo.UserAddress;
import com.imooc.pojo.bo.AddressBO;
import com.imooc.service.AddressService;
import com.imooc.service.CarouselService;
import org.n3r.idworker.Sid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;
import java.util.Date;
import java.util.List;
/**
* @Author mcg
* @Date 2019/11/15 21:18
**/
@Service
public class AddressServiceImpl implements AddressService {
@Autowired
private UserAddressMapper userAddressMapper;
@Autowired
private Sid sid;
@Transactional(propagation = Propagation.SUPPORTS)
@Override
public List<UserAddress> queryAll(String userId) {
UserAddress ua = new UserAddress();
ua.setUserId(userId);
return userAddressMapper.select(ua);
}
@Transactional(propagation = Propagation.REQUIRED)
@Override
public void addNewUserAddress(AddressBO addressBO) {
// 1. 判断当前用户是否存在地址,如果没有,则新增为 默认地址
List<UserAddress> userAddresses = this.queryAll(addressBO.getUserId());
Integer isDefault = 0;
if (userAddresses == null || userAddresses.isEmpty() || userAddresses.size() == 0) {
isDefault = 1;
}
String addressId = sid.nextShort();
// 2. 保存
UserAddress newAddress = new UserAddress();
BeanUtils.copyProperties(addressBO, newAddress);
newAddress.setId(addressId);
newAddress.setIsDefault(isDefault);
newAddress.setCreatedTime(new Date());
newAddress.setUpdatedTime(new Date());
userAddressMapper.insert(newAddress);
}
@Transactional(propagation = Propagation.REQUIRED)
@Override
public void updateUserAddress(AddressBO addressBO) {
String addressId = addressBO.getAddressId();
UserAddress updateAddress = new UserAddress();
BeanUtils.copyProperties(addressBO, updateAddress);
updateAddress.setId(addressId);
updateAddress.setUpdatedTime(new Date());
userAddressMapper.updateByPrimaryKeySelective(updateAddress);
}
@Transactional(propagation = Propagation.REQUIRED)
@Override
public void deleteUserAddress(String userId, String addressId) {
UserAddress address = new UserAddress();
address.setId(addressId);
address.setUserId(userId);
userAddressMapper.delete(address);
}
@Transactional(propagation = Propagation.REQUIRED)
@Override
public void updateUserAddressToBeDefault(String userId, String addressId) {
// 1 查找默认地址,设置为非默认
UserAddress queryAddress = new UserAddress();
queryAddress.setUserId(userId);
queryAddress.setIsDefault(YesOrNo.YES.type);
List<UserAddress> userAddressList = userAddressMapper.select(queryAddress);
for (UserAddress address : userAddressList) {
address.setIsDefault(YesOrNo.NO.type);
userAddressMapper.updateByPrimaryKeySelective(address);
}
// 2 根据地址id 设置为默认地址
UserAddress defaultAddress = new UserAddress();
defaultAddress.setId(addressId);
defaultAddress.setIsDefault(YesOrNo.YES.type);
defaultAddress.setUserId(userId);
defaultAddress.setUpdatedTime(new Date());
userAddressMapper.updateByPrimaryKeySelective(defaultAddress);
}
@Transactional(propagation = Propagation.SUPPORTS)
@Override
public UserAddress queryUserAddress(String userId, String addressId) {
UserAddress address = new UserAddress();
address.setUserId(userId);
address.setId(addressId);
return userAddressMapper.selectOne(address);
}
}
| UTF-8 | Java | 4,203 | java | AddressServiceImpl.java | Java | [
{
"context": ".util.Date;\nimport java.util.List;\n\n/**\n * @Author mcg\n * @Date 2019/11/15 21:18\n **/\n@Service\npublic cl",
"end": 801,
"score": 0.9996719360351562,
"start": 798,
"tag": "USERNAME",
"value": "mcg"
}
] | null | [] | package com.imooc.service.impl;
import com.imooc.enums.YesOrNo;
import com.imooc.mapper.CarouselMapper;
import com.imooc.mapper.UserAddressMapper;
import com.imooc.pojo.Carousel;
import com.imooc.pojo.UserAddress;
import com.imooc.pojo.bo.AddressBO;
import com.imooc.service.AddressService;
import com.imooc.service.CarouselService;
import org.n3r.idworker.Sid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;
import java.util.Date;
import java.util.List;
/**
* @Author mcg
* @Date 2019/11/15 21:18
**/
@Service
public class AddressServiceImpl implements AddressService {
@Autowired
private UserAddressMapper userAddressMapper;
@Autowired
private Sid sid;
@Transactional(propagation = Propagation.SUPPORTS)
@Override
public List<UserAddress> queryAll(String userId) {
UserAddress ua = new UserAddress();
ua.setUserId(userId);
return userAddressMapper.select(ua);
}
@Transactional(propagation = Propagation.REQUIRED)
@Override
public void addNewUserAddress(AddressBO addressBO) {
// 1. 判断当前用户是否存在地址,如果没有,则新增为 默认地址
List<UserAddress> userAddresses = this.queryAll(addressBO.getUserId());
Integer isDefault = 0;
if (userAddresses == null || userAddresses.isEmpty() || userAddresses.size() == 0) {
isDefault = 1;
}
String addressId = sid.nextShort();
// 2. 保存
UserAddress newAddress = new UserAddress();
BeanUtils.copyProperties(addressBO, newAddress);
newAddress.setId(addressId);
newAddress.setIsDefault(isDefault);
newAddress.setCreatedTime(new Date());
newAddress.setUpdatedTime(new Date());
userAddressMapper.insert(newAddress);
}
@Transactional(propagation = Propagation.REQUIRED)
@Override
public void updateUserAddress(AddressBO addressBO) {
String addressId = addressBO.getAddressId();
UserAddress updateAddress = new UserAddress();
BeanUtils.copyProperties(addressBO, updateAddress);
updateAddress.setId(addressId);
updateAddress.setUpdatedTime(new Date());
userAddressMapper.updateByPrimaryKeySelective(updateAddress);
}
@Transactional(propagation = Propagation.REQUIRED)
@Override
public void deleteUserAddress(String userId, String addressId) {
UserAddress address = new UserAddress();
address.setId(addressId);
address.setUserId(userId);
userAddressMapper.delete(address);
}
@Transactional(propagation = Propagation.REQUIRED)
@Override
public void updateUserAddressToBeDefault(String userId, String addressId) {
// 1 查找默认地址,设置为非默认
UserAddress queryAddress = new UserAddress();
queryAddress.setUserId(userId);
queryAddress.setIsDefault(YesOrNo.YES.type);
List<UserAddress> userAddressList = userAddressMapper.select(queryAddress);
for (UserAddress address : userAddressList) {
address.setIsDefault(YesOrNo.NO.type);
userAddressMapper.updateByPrimaryKeySelective(address);
}
// 2 根据地址id 设置为默认地址
UserAddress defaultAddress = new UserAddress();
defaultAddress.setId(addressId);
defaultAddress.setIsDefault(YesOrNo.YES.type);
defaultAddress.setUserId(userId);
defaultAddress.setUpdatedTime(new Date());
userAddressMapper.updateByPrimaryKeySelective(defaultAddress);
}
@Transactional(propagation = Propagation.SUPPORTS)
@Override
public UserAddress queryUserAddress(String userId, String addressId) {
UserAddress address = new UserAddress();
address.setUserId(userId);
address.setId(addressId);
return userAddressMapper.selectOne(address);
}
}
| 4,203 | 0.715296 | 0.710417 | 119 | 33.445377 | 23.36006 | 92 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.588235 | false | false | 8 |
744f1cf2d15d3dfdb8d3189ae26d7aa5e30cf554 | 24,343,874,640,674 | 237f1c57c2406e45bad6ec6c7e1e20add3d2df7a | /app/src/main/java/com/faaya/fernandoaranaandrade/demo/NotificationsSettingsActivity.java | f06863e759d36bbf2ab6b80b5f702949f4f25245 | [] | no_license | fdoclaves/toDoManager | https://github.com/fdoclaves/toDoManager | 1a0a012ad9111729da1d39dd045c2216450e84dc | e4a6abb39792218d093d2dfeae5cf9a594eceaa0 | refs/heads/master | 2020-04-18T16:25:19.786000 | 2019-03-02T01:23:53 | 2019-03-02T01:23:53 | 167,633,603 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.faaya.fernandoaranaandrade.demo;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import com.faaya.fernandoaranaandrade.demo.Beans.DateEnum;
import com.faaya.fernandoaranaandrade.demo.Beans.NotificationsApp;
import com.faaya.fernandoaranaandrade.demo.Beans.SettingsEnum;
import com.faaya.fernandoaranaandrade.demo.database.Queries;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class NotificationsSettingsActivity extends AppCompatActivity {
public static final String HORAS = "H";
public static final String MINUTOS = "M";
public static final String _5MINUTOS = "5M";
public static final String _15MINUTOS = "15M";
public static final String _30MINUTOS = "30M";
public static final String _1HORA = "1H";
public static final String _24HORAS = "24H";
private Queries queries;
private Spinner tiempoSpinner;
Map<String, String> map = new HashMap<>();
List<String> list = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list.add(getString(R.string._5minutos));
list.add(getString(R.string._15minutos));
list.add(getString(R.string._30minutos));
list.add(getString(R.string._1Hora));
list.add(getString(R.string._24Horas));
map.put(list.get(0),_5MINUTOS);
map.put(list.get(1),_15MINUTOS);
map.put(list.get(2),_30MINUTOS);
map.put(list.get(3),_1HORA);
map.put(list.get(4), _24HORAS);
setContentView(R.layout.activity_notifications_settings);
queries = new Queries(this);
tiempoSpinner = findViewById(R.id.spinnerHorasMinutosGeneral);
tiempoSpinner.setAdapter(new ArrayAdapter<String>(this, R.layout.spinner18, list));
fillSnooze();
fillNextNotification();
}
private void fillNextNotification() {
TextView textViewNextNotifacion = findViewById(R.id.textViewNextNotifacion);
NotificationsApp firstNotification = queries.getFirstNotification();
if(firstNotification == null){
textViewNextNotifacion.setVisibility(View.INVISIBLE);
TextView textViewNextNotificationTitule = findViewById(R.id.textViewNextNotificationTitule);
textViewNextNotificationTitule.setVisibility(View.INVISIBLE);
} else {
String format = DateEnum.fullDateSimpleDateFormat.format(new Date(firstNotification.getDate()));
textViewNextNotifacion.setText(format);
}
}
private void fillSnooze() {
String timeSnooze = queries.getValueByProperty(SettingsEnum.TIME_SNOOZE);
for (Map.Entry<String, String> pair : map.entrySet()) {
if(pair.getValue().equals(timeSnooze)){
for (int i = 0; i < list.size(); i++) {
if(list.get(i).equals(pair.getKey())){
tiempoSpinner.setSelection(i);
}
}
}
}
}
public void save(View view) {
queries.saveProperty(SettingsEnum.TIME_SNOOZE, map.get(tiempoSpinner.getSelectedItem()));
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
}
| UTF-8 | Java | 3,611 | java | NotificationsSettingsActivity.java | Java | [] | null | [] | package com.faaya.fernandoaranaandrade.demo;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import com.faaya.fernandoaranaandrade.demo.Beans.DateEnum;
import com.faaya.fernandoaranaandrade.demo.Beans.NotificationsApp;
import com.faaya.fernandoaranaandrade.demo.Beans.SettingsEnum;
import com.faaya.fernandoaranaandrade.demo.database.Queries;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class NotificationsSettingsActivity extends AppCompatActivity {
public static final String HORAS = "H";
public static final String MINUTOS = "M";
public static final String _5MINUTOS = "5M";
public static final String _15MINUTOS = "15M";
public static final String _30MINUTOS = "30M";
public static final String _1HORA = "1H";
public static final String _24HORAS = "24H";
private Queries queries;
private Spinner tiempoSpinner;
Map<String, String> map = new HashMap<>();
List<String> list = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list.add(getString(R.string._5minutos));
list.add(getString(R.string._15minutos));
list.add(getString(R.string._30minutos));
list.add(getString(R.string._1Hora));
list.add(getString(R.string._24Horas));
map.put(list.get(0),_5MINUTOS);
map.put(list.get(1),_15MINUTOS);
map.put(list.get(2),_30MINUTOS);
map.put(list.get(3),_1HORA);
map.put(list.get(4), _24HORAS);
setContentView(R.layout.activity_notifications_settings);
queries = new Queries(this);
tiempoSpinner = findViewById(R.id.spinnerHorasMinutosGeneral);
tiempoSpinner.setAdapter(new ArrayAdapter<String>(this, R.layout.spinner18, list));
fillSnooze();
fillNextNotification();
}
private void fillNextNotification() {
TextView textViewNextNotifacion = findViewById(R.id.textViewNextNotifacion);
NotificationsApp firstNotification = queries.getFirstNotification();
if(firstNotification == null){
textViewNextNotifacion.setVisibility(View.INVISIBLE);
TextView textViewNextNotificationTitule = findViewById(R.id.textViewNextNotificationTitule);
textViewNextNotificationTitule.setVisibility(View.INVISIBLE);
} else {
String format = DateEnum.fullDateSimpleDateFormat.format(new Date(firstNotification.getDate()));
textViewNextNotifacion.setText(format);
}
}
private void fillSnooze() {
String timeSnooze = queries.getValueByProperty(SettingsEnum.TIME_SNOOZE);
for (Map.Entry<String, String> pair : map.entrySet()) {
if(pair.getValue().equals(timeSnooze)){
for (int i = 0; i < list.size(); i++) {
if(list.get(i).equals(pair.getKey())){
tiempoSpinner.setSelection(i);
}
}
}
}
}
public void save(View view) {
queries.saveProperty(SettingsEnum.TIME_SNOOZE, map.get(tiempoSpinner.getSelectedItem()));
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
}
| 3,611 | 0.687344 | 0.67599 | 94 | 37.414894 | 25.360973 | 108 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.787234 | false | false | 8 |
2615a748954b170096b80d0343f9abce107840f0 | 24,343,874,639,207 | e085efe99127108fc4ebffe5296bdfa9ca51fdcd | /src/main/java/mx/amib/sistemas/oficios/revocacion/service/RevocacionServiceImpl.java | d257daaa4e619fabb63c0f139bb707fe65f52c76 | [] | no_license | amiboficial/amibOficios | https://github.com/amiboficial/amibOficios | dfe3de9c058381d5bcfae12affbf9c326f6ae1ed | eeee032972e33ec293fdf9c4317b81bd4fd4ff1e | refs/heads/master | 2020-05-24T12:16:02.805000 | 2017-12-15T02:16:23 | 2017-12-15T02:16:23 | 37,888,728 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package mx.amib.sistemas.oficios.revocacion.service;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import mx.amib.sistemas.external.oficios.revocacion.RevocacionTO;
import mx.amib.sistemas.external.oficios.revocacion.RevocadoTO;
import mx.amib.sistemas.oficios.poder.dao.ApoderadoDAO;
import mx.amib.sistemas.oficios.revocacion.dao.RevocacionDAO;
import mx.amib.sistemas.oficios.revocacion.model.Revocacion;
import mx.amib.sistemas.oficios.revocacion.model.Revocado;
import mx.amib.sistemas.utils.SearchResult;
@Scope("singleton")
@Service("revocacionService")
public class RevocacionServiceImpl implements RevocacionService {
@Autowired
private RevocacionDAO revocacionDAO;
@Autowired
private ApoderadoDAO apoderadoDAO;
public SearchResult<RevocacionTO> index(Integer max, Integer offset,
String sort, String order) {
SearchResult<Revocacion> rsr = this.revocacionDAO.findAll(max, offset, sort, order);
SearchResult<RevocacionTO> rsrt = this.entityToTransport(rsr);
return rsrt;
}
public SearchResult<RevocacionTO> findAllBy(Integer max, Integer offset,
String sort, String order, Integer numeroEscritura,
Integer fechaDelDia, Integer fechaDelMes, Integer fechaDelAnio,
Integer fechaAlDia, Integer fechaAlMes, Integer fechaAlAnio,
Long idGrupoFinanciero, Long idInstitucion) {
SearchResult<Revocacion> rsr = this.revocacionDAO.findAllBy(max, offset, sort, order,
numeroEscritura, fechaDelDia, fechaDelMes, fechaDelAnio,
fechaAlDia, fechaAlMes, fechaAlAnio, idGrupoFinanciero, idInstitucion);
SearchResult<RevocacionTO> rsrt = this.entityToTransport(rsr);
return rsrt;
}
public SearchResult<RevocacionTO> findAllByNumeroEscritura(Integer numeroEscritura) {
SearchResult<Revocacion> _result;
SearchResult<RevocacionTO> result;
_result = this.revocacionDAO.findAllByNumeroEscritura(numeroEscritura);
result = this.entityToTransport(_result);
return result;
}
public SearchResult<RevocacionTO> findAllByFechaRevocacion(Integer max, Integer offset, String sort, String order,
Integer fechaDelDia, Integer fechaDelMes, Integer fechaDelAnio, Integer fechaAlDia, Integer fechaAlMes,
Integer fechaAlAnio) {
SearchResult<Revocacion> _result;
SearchResult<RevocacionTO> result;
_result = this.revocacionDAO.findAllByFechaRevocacion(max,offset,sort,order,fechaDelDia, fechaDelMes, fechaDelAnio, fechaAlDia, fechaAlMes, fechaAlAnio);
result = this.entityToTransport(_result);
return result;
}
public SearchResult<RevocacionTO> findAllByGrupoFinanciero(Integer max, Integer offset, String sort, String order,
Long idGrupoFinanciero) {
SearchResult<Revocacion> _result;
SearchResult<RevocacionTO> result;
_result = this.revocacionDAO.findAllByGrupoFinanciero(max,offset,sort,order,idGrupoFinanciero);
result = this.entityToTransport(_result);
return result;
}
public SearchResult<RevocacionTO> findAllByInstitucion(Integer max, Integer offset, String sort, String order,
Long idInstitucion) {
SearchResult<Revocacion> _result;
SearchResult<RevocacionTO> result;
_result = this.revocacionDAO.findAllByInstitucion(max,offset,sort,order,idInstitucion);
result = this.entityToTransport(_result);
return result;
}
public Set<RevocacionTO> getAllByIdCertficacionInSet(Set<Long> idsCertficacion){
Set<Revocacion> _result;
Set<RevocacionTO> result;
_result = this.revocacionDAO.getAllByIdCertficacionInSet(idsCertficacion);
result = this.entityToTransport(_result);
return result;
}
public RevocacionTO get(Long id) {
return this.entityToTransport( this.revocacionDAO.get(id) );
}
public RevocacionTO save(RevocacionTO r) {
Revocacion _r = new Revocacion();
RevocacionTO rres = new RevocacionTO();
_r = this.setEntityWithTransportNoChilds(r, _r);
_r.setVersion(1L);
_r.setFechaCreacion(Calendar.getInstance().getTime());
_r.setFechaModificacion(Calendar.getInstance().getTime());
List<Revocado> _rrs = new ArrayList<Revocado>();
for(RevocadoTO rr : r.getRevocados()){
Revocado _rr = new Revocado();
_rr.setId( null );
_rr.setRevocacion( _r );
_rr.setApoderado( this.apoderadoDAO.get(rr.getIdApoderado()) );
_rr.setMotivo( rr.getMotivo() );
_rr.setFechaBaja( rr.getFechaBaja() );
_rr.setFechaCreacion( Calendar.getInstance().getTime() );
_rr.setFechaModificacion( Calendar.getInstance().getTime() );
_rrs.add(_rr);
}
_r.setRevocados(_rrs);
try{
_r = this.revocacionDAO.save(_r);
rres = this.entityToTransport(_r);
}
catch(Exception e){
rres.setId(-1L);
}
return rres;
}
@Transactional
public RevocacionTO update(RevocacionTO r) {
RevocacionTO rres = new RevocacionTO();
List<RevocadoTO> nuevosRevocadosTO = new ArrayList<RevocadoTO>();
Map<Long,RevocadoTO> actualizablesRevocadosTO = new HashMap<Long,RevocadoTO>();
Map<Long,Revocado> actualizablesRevocados = new HashMap<Long,Revocado>();
Map<Long,Revocado> borrablesRevocados = new HashMap<Long,Revocado>();
//Obtiene la instancia actual de Revocacion y sus respectivos Revocados
Revocacion _r = this.revocacionDAO.get(r.getId());
//Actualiza datos de la revocacion
_r = this.setEntityWithTransportNoChilds(r, _r);
_r.setVersion( _r.getVersion() + 1L );
_r.setFechaModificacion( Calendar.getInstance().getTime() );
//Obtiene a los nuevos y a los actualizables del "TO"
for(RevocadoTO rr : r.getRevocados() ){
if(rr.getId() == null || rr.getId() <= 0){
nuevosRevocadosTO.add(rr);
}
else{
actualizablesRevocadosTO.put(rr.getId(), rr);
}
}
//Obtiene a los actualizables y a los borrables de la instancia de Revocado
for(Revocado _rr : _r.getRevocados()){
if( !actualizablesRevocadosTO.containsKey(_rr.getId()) ){
borrablesRevocados.put(_rr.getId(), _rr);
}
else{
actualizablesRevocados.put(_rr.getId(), _rr);
}
}
//Quita los revocados que ya no esten incluidos en lista
for(Revocado _rr : borrablesRevocados.values()){
_r.getRevocados().remove(_rr);
}
//Inserta nuevos revocados
for(RevocadoTO rr: nuevosRevocadosTO){
Revocado _rr = new Revocado();
_rr.setId( rr.getId() );
_rr.setRevocacion( _r );
_rr.setApoderado( this.apoderadoDAO.get( rr.getIdApoderado() ) );
_rr.setMotivo(rr.getMotivo());
_rr.setFechaBaja(rr.getFechaBaja());
_rr.setFechaCreacion( Calendar.getInstance().getTime() );
_rr.setFechaModificacion( Calendar.getInstance().getTime() );
_r.getRevocados().add(_rr);
}
//Actualiza los revocados que si se encuentran
for(RevocadoTO rr : actualizablesRevocadosTO.values()){
Revocado _rr = null;
_rr = actualizablesRevocados.get(rr.getId());
_rr.setMotivo(rr.getMotivo());
_rr.setFechaBaja(rr.getFechaBaja());
_rr.setFechaModificacion( Calendar.getInstance().getTime() );
}
try{
_r = this.revocacionDAO.update(_r);
rres = this.entityToTransport(_r);
}
catch (Exception e) {
rres.setId(-1L);
}
return rres;
}
//Método privados
private Revocacion setEntityWithTransportNoChilds(RevocacionTO r, Revocacion _r){
_r.setIdGrupoFinanciero(r.getIdGrupoFinanciero());
_r.setIdInstitucion(r.getIdInstitucion());
_r.setIdNotario(r.getIdNotario());
_r.setNumeroEscritura(r.getNumeroEscritura());
_r.setRepresentanteLegalNombre(r.getRepresentanteLegalNombre());
_r.setRepresentanteLegalApellido1(r.getRepresentanteLegalApellido1());
_r.setRepresentanteLegalApellido2(r.getRepresentanteLegalApellido2());
_r.setFechaRevocacion(r.getFechaRevocacion());
_r.setUuidDocumentoRespaldo(r.getUuidDocumentoRespaldo());
return _r;
}
private SearchResult<RevocacionTO> entityToTransport(SearchResult<Revocacion> _sr){
SearchResult<RevocacionTO> sr = new SearchResult<RevocacionTO>();
sr.setList(new ArrayList<RevocacionTO>());
sr.setError(false);
sr.setCount(0L);
for(Revocacion _r : _sr.getList()){
RevocacionTO r = this.entityToTransport(_r);
sr.getList().add(r);
}
sr.setError(_sr.getError());
sr.setCount(_sr.getCount());
return sr;
}
private Set<RevocacionTO> entityToTransport(Set<Revocacion> _sr){
Set<RevocacionTO> sr = new HashSet<RevocacionTO>();
for(Revocacion _r : _sr){
RevocacionTO r = this.entityToTransport(_r);
sr.add(r);
}
return sr;
}
private RevocacionTO entityToTransport(Revocacion _r){
RevocacionTO r = new RevocacionTO();
r.setId(_r.getId());
r.setVersion(_r.getVersion());
r.setIdGrupoFinanciero(_r.getIdGrupoFinanciero());
r.setIdInstitucion(_r.getIdInstitucion());
r.setIdNotario(_r.getIdNotario());
r.setNumeroEscritura(_r.getNumeroEscritura());
r.setRepresentanteLegalNombre(_r.getRepresentanteLegalNombre());
r.setRepresentanteLegalApellido1(_r.getRepresentanteLegalApellido1());
r.setRepresentanteLegalApellido2(_r.getRepresentanteLegalApellido2());
r.setFechaRevocacion(_r.getFechaRevocacion());
r.setUuidDocumentoRespaldo(_r.getUuidDocumentoRespaldo());
List<RevocadoTO> revocados = new ArrayList<RevocadoTO>();
for(Revocado _rv : _r.getRevocados()){
RevocadoTO rv = new RevocadoTO();
rv.setId(_rv.getId());
rv.setIdRevocacion(_rv.getRevocacion().getId());
rv.setIdApoderado(_rv.getApoderado().getId());
rv.setMotivo(_rv.getMotivo());
rv.setFechaBaja(_rv.getFechaBaja());
rv.setFechaCreacion(_rv.getFechaCreacion());
rv.setFechaModificacion(_rv.getFechaModificacion());
revocados.add(rv);
}
r.setRevocados(revocados);
r.setFechaCreacion(_r.getFechaCreacion());
r.setFechaModificacion(_r.getFechaModificacion());
return r;
}
public Boolean delete(Long id) {
Boolean completed;
try{
this.revocacionDAO.delete(id);
completed = true;
}
catch(Exception e){
completed = false;
}
return completed;
}
public Boolean isNumeroEscrituraAvailable(int numeroEscritura) {
return this.revocacionDAO.isNumeroEscrituraAvailable(numeroEscritura);
}
public ApoderadoDAO getApoderadoDAO() {
return apoderadoDAO;
}
public void setApoderadoDAO(ApoderadoDAO apoderadoDAO) {
this.apoderadoDAO = apoderadoDAO;
}
public RevocacionDAO getRevocacionDAO() {
return revocacionDAO;
}
public void setRevocacionDAO(RevocacionDAO revocacionDAO) {
this.revocacionDAO = revocacionDAO;
}
}
| UTF-8 | Java | 10,604 | java | RevocacionServiceImpl.java | Java | [] | null | [] | package mx.amib.sistemas.oficios.revocacion.service;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import mx.amib.sistemas.external.oficios.revocacion.RevocacionTO;
import mx.amib.sistemas.external.oficios.revocacion.RevocadoTO;
import mx.amib.sistemas.oficios.poder.dao.ApoderadoDAO;
import mx.amib.sistemas.oficios.revocacion.dao.RevocacionDAO;
import mx.amib.sistemas.oficios.revocacion.model.Revocacion;
import mx.amib.sistemas.oficios.revocacion.model.Revocado;
import mx.amib.sistemas.utils.SearchResult;
@Scope("singleton")
@Service("revocacionService")
public class RevocacionServiceImpl implements RevocacionService {
@Autowired
private RevocacionDAO revocacionDAO;
@Autowired
private ApoderadoDAO apoderadoDAO;
public SearchResult<RevocacionTO> index(Integer max, Integer offset,
String sort, String order) {
SearchResult<Revocacion> rsr = this.revocacionDAO.findAll(max, offset, sort, order);
SearchResult<RevocacionTO> rsrt = this.entityToTransport(rsr);
return rsrt;
}
public SearchResult<RevocacionTO> findAllBy(Integer max, Integer offset,
String sort, String order, Integer numeroEscritura,
Integer fechaDelDia, Integer fechaDelMes, Integer fechaDelAnio,
Integer fechaAlDia, Integer fechaAlMes, Integer fechaAlAnio,
Long idGrupoFinanciero, Long idInstitucion) {
SearchResult<Revocacion> rsr = this.revocacionDAO.findAllBy(max, offset, sort, order,
numeroEscritura, fechaDelDia, fechaDelMes, fechaDelAnio,
fechaAlDia, fechaAlMes, fechaAlAnio, idGrupoFinanciero, idInstitucion);
SearchResult<RevocacionTO> rsrt = this.entityToTransport(rsr);
return rsrt;
}
public SearchResult<RevocacionTO> findAllByNumeroEscritura(Integer numeroEscritura) {
SearchResult<Revocacion> _result;
SearchResult<RevocacionTO> result;
_result = this.revocacionDAO.findAllByNumeroEscritura(numeroEscritura);
result = this.entityToTransport(_result);
return result;
}
public SearchResult<RevocacionTO> findAllByFechaRevocacion(Integer max, Integer offset, String sort, String order,
Integer fechaDelDia, Integer fechaDelMes, Integer fechaDelAnio, Integer fechaAlDia, Integer fechaAlMes,
Integer fechaAlAnio) {
SearchResult<Revocacion> _result;
SearchResult<RevocacionTO> result;
_result = this.revocacionDAO.findAllByFechaRevocacion(max,offset,sort,order,fechaDelDia, fechaDelMes, fechaDelAnio, fechaAlDia, fechaAlMes, fechaAlAnio);
result = this.entityToTransport(_result);
return result;
}
public SearchResult<RevocacionTO> findAllByGrupoFinanciero(Integer max, Integer offset, String sort, String order,
Long idGrupoFinanciero) {
SearchResult<Revocacion> _result;
SearchResult<RevocacionTO> result;
_result = this.revocacionDAO.findAllByGrupoFinanciero(max,offset,sort,order,idGrupoFinanciero);
result = this.entityToTransport(_result);
return result;
}
public SearchResult<RevocacionTO> findAllByInstitucion(Integer max, Integer offset, String sort, String order,
Long idInstitucion) {
SearchResult<Revocacion> _result;
SearchResult<RevocacionTO> result;
_result = this.revocacionDAO.findAllByInstitucion(max,offset,sort,order,idInstitucion);
result = this.entityToTransport(_result);
return result;
}
public Set<RevocacionTO> getAllByIdCertficacionInSet(Set<Long> idsCertficacion){
Set<Revocacion> _result;
Set<RevocacionTO> result;
_result = this.revocacionDAO.getAllByIdCertficacionInSet(idsCertficacion);
result = this.entityToTransport(_result);
return result;
}
public RevocacionTO get(Long id) {
return this.entityToTransport( this.revocacionDAO.get(id) );
}
public RevocacionTO save(RevocacionTO r) {
Revocacion _r = new Revocacion();
RevocacionTO rres = new RevocacionTO();
_r = this.setEntityWithTransportNoChilds(r, _r);
_r.setVersion(1L);
_r.setFechaCreacion(Calendar.getInstance().getTime());
_r.setFechaModificacion(Calendar.getInstance().getTime());
List<Revocado> _rrs = new ArrayList<Revocado>();
for(RevocadoTO rr : r.getRevocados()){
Revocado _rr = new Revocado();
_rr.setId( null );
_rr.setRevocacion( _r );
_rr.setApoderado( this.apoderadoDAO.get(rr.getIdApoderado()) );
_rr.setMotivo( rr.getMotivo() );
_rr.setFechaBaja( rr.getFechaBaja() );
_rr.setFechaCreacion( Calendar.getInstance().getTime() );
_rr.setFechaModificacion( Calendar.getInstance().getTime() );
_rrs.add(_rr);
}
_r.setRevocados(_rrs);
try{
_r = this.revocacionDAO.save(_r);
rres = this.entityToTransport(_r);
}
catch(Exception e){
rres.setId(-1L);
}
return rres;
}
@Transactional
public RevocacionTO update(RevocacionTO r) {
RevocacionTO rres = new RevocacionTO();
List<RevocadoTO> nuevosRevocadosTO = new ArrayList<RevocadoTO>();
Map<Long,RevocadoTO> actualizablesRevocadosTO = new HashMap<Long,RevocadoTO>();
Map<Long,Revocado> actualizablesRevocados = new HashMap<Long,Revocado>();
Map<Long,Revocado> borrablesRevocados = new HashMap<Long,Revocado>();
//Obtiene la instancia actual de Revocacion y sus respectivos Revocados
Revocacion _r = this.revocacionDAO.get(r.getId());
//Actualiza datos de la revocacion
_r = this.setEntityWithTransportNoChilds(r, _r);
_r.setVersion( _r.getVersion() + 1L );
_r.setFechaModificacion( Calendar.getInstance().getTime() );
//Obtiene a los nuevos y a los actualizables del "TO"
for(RevocadoTO rr : r.getRevocados() ){
if(rr.getId() == null || rr.getId() <= 0){
nuevosRevocadosTO.add(rr);
}
else{
actualizablesRevocadosTO.put(rr.getId(), rr);
}
}
//Obtiene a los actualizables y a los borrables de la instancia de Revocado
for(Revocado _rr : _r.getRevocados()){
if( !actualizablesRevocadosTO.containsKey(_rr.getId()) ){
borrablesRevocados.put(_rr.getId(), _rr);
}
else{
actualizablesRevocados.put(_rr.getId(), _rr);
}
}
//Quita los revocados que ya no esten incluidos en lista
for(Revocado _rr : borrablesRevocados.values()){
_r.getRevocados().remove(_rr);
}
//Inserta nuevos revocados
for(RevocadoTO rr: nuevosRevocadosTO){
Revocado _rr = new Revocado();
_rr.setId( rr.getId() );
_rr.setRevocacion( _r );
_rr.setApoderado( this.apoderadoDAO.get( rr.getIdApoderado() ) );
_rr.setMotivo(rr.getMotivo());
_rr.setFechaBaja(rr.getFechaBaja());
_rr.setFechaCreacion( Calendar.getInstance().getTime() );
_rr.setFechaModificacion( Calendar.getInstance().getTime() );
_r.getRevocados().add(_rr);
}
//Actualiza los revocados que si se encuentran
for(RevocadoTO rr : actualizablesRevocadosTO.values()){
Revocado _rr = null;
_rr = actualizablesRevocados.get(rr.getId());
_rr.setMotivo(rr.getMotivo());
_rr.setFechaBaja(rr.getFechaBaja());
_rr.setFechaModificacion( Calendar.getInstance().getTime() );
}
try{
_r = this.revocacionDAO.update(_r);
rres = this.entityToTransport(_r);
}
catch (Exception e) {
rres.setId(-1L);
}
return rres;
}
//Método privados
private Revocacion setEntityWithTransportNoChilds(RevocacionTO r, Revocacion _r){
_r.setIdGrupoFinanciero(r.getIdGrupoFinanciero());
_r.setIdInstitucion(r.getIdInstitucion());
_r.setIdNotario(r.getIdNotario());
_r.setNumeroEscritura(r.getNumeroEscritura());
_r.setRepresentanteLegalNombre(r.getRepresentanteLegalNombre());
_r.setRepresentanteLegalApellido1(r.getRepresentanteLegalApellido1());
_r.setRepresentanteLegalApellido2(r.getRepresentanteLegalApellido2());
_r.setFechaRevocacion(r.getFechaRevocacion());
_r.setUuidDocumentoRespaldo(r.getUuidDocumentoRespaldo());
return _r;
}
private SearchResult<RevocacionTO> entityToTransport(SearchResult<Revocacion> _sr){
SearchResult<RevocacionTO> sr = new SearchResult<RevocacionTO>();
sr.setList(new ArrayList<RevocacionTO>());
sr.setError(false);
sr.setCount(0L);
for(Revocacion _r : _sr.getList()){
RevocacionTO r = this.entityToTransport(_r);
sr.getList().add(r);
}
sr.setError(_sr.getError());
sr.setCount(_sr.getCount());
return sr;
}
private Set<RevocacionTO> entityToTransport(Set<Revocacion> _sr){
Set<RevocacionTO> sr = new HashSet<RevocacionTO>();
for(Revocacion _r : _sr){
RevocacionTO r = this.entityToTransport(_r);
sr.add(r);
}
return sr;
}
private RevocacionTO entityToTransport(Revocacion _r){
RevocacionTO r = new RevocacionTO();
r.setId(_r.getId());
r.setVersion(_r.getVersion());
r.setIdGrupoFinanciero(_r.getIdGrupoFinanciero());
r.setIdInstitucion(_r.getIdInstitucion());
r.setIdNotario(_r.getIdNotario());
r.setNumeroEscritura(_r.getNumeroEscritura());
r.setRepresentanteLegalNombre(_r.getRepresentanteLegalNombre());
r.setRepresentanteLegalApellido1(_r.getRepresentanteLegalApellido1());
r.setRepresentanteLegalApellido2(_r.getRepresentanteLegalApellido2());
r.setFechaRevocacion(_r.getFechaRevocacion());
r.setUuidDocumentoRespaldo(_r.getUuidDocumentoRespaldo());
List<RevocadoTO> revocados = new ArrayList<RevocadoTO>();
for(Revocado _rv : _r.getRevocados()){
RevocadoTO rv = new RevocadoTO();
rv.setId(_rv.getId());
rv.setIdRevocacion(_rv.getRevocacion().getId());
rv.setIdApoderado(_rv.getApoderado().getId());
rv.setMotivo(_rv.getMotivo());
rv.setFechaBaja(_rv.getFechaBaja());
rv.setFechaCreacion(_rv.getFechaCreacion());
rv.setFechaModificacion(_rv.getFechaModificacion());
revocados.add(rv);
}
r.setRevocados(revocados);
r.setFechaCreacion(_r.getFechaCreacion());
r.setFechaModificacion(_r.getFechaModificacion());
return r;
}
public Boolean delete(Long id) {
Boolean completed;
try{
this.revocacionDAO.delete(id);
completed = true;
}
catch(Exception e){
completed = false;
}
return completed;
}
public Boolean isNumeroEscrituraAvailable(int numeroEscritura) {
return this.revocacionDAO.isNumeroEscrituraAvailable(numeroEscritura);
}
public ApoderadoDAO getApoderadoDAO() {
return apoderadoDAO;
}
public void setApoderadoDAO(ApoderadoDAO apoderadoDAO) {
this.apoderadoDAO = apoderadoDAO;
}
public RevocacionDAO getRevocacionDAO() {
return revocacionDAO;
}
public void setRevocacionDAO(RevocacionDAO revocacionDAO) {
this.revocacionDAO = revocacionDAO;
}
}
| 10,604 | 0.742903 | 0.741583 | 319 | 32.238243 | 27.146988 | 155 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 2.595611 | false | false | 8 |
e7471bd46491035639006e893f05f30cb388da7a | 26,405,458,944,576 | 6f8d79d737f384a3b9d7c9f62d7a840cf344cc74 | /app/src/main/java/com/example/filipedgb/cmovproj1/classes/Order.java | 3a9cf208b337a1085f0e2a5ae838df0e6f713c59 | [] | no_license | filipedgb/cafe-payment-system | https://github.com/filipedgb/cafe-payment-system | d7b92cd5b9dbc3f43202653bd6d05f414fccfe8e | 8ade105d97836afff14ff3301afdb8d25546de3c | refs/heads/master | 2021-01-10T23:24:33.171000 | 2017-07-27T11:38:02 | 2017-07-27T11:38:02 | 70,586,025 | 1 | 1 | null | false | 2016-10-22T14:09:30 | 2016-10-11T11:21:39 | 2016-10-11T11:33:43 | 2016-10-22T14:09:29 | 421 | 0 | 0 | 0 | Java | null | null | package com.example.filipedgb.cmovproj1.classes;
import android.util.Log;
import com.example.filipedgb.cmovproj1.Product;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.FirebaseAuth;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by Filipe Batista on 23/10/2016.
*/
public class Order implements Serializable {
private FirebaseApp app;
private FirebaseAuth auth;
private String order_id;
private Double order_price;
private String user_code;
private String created_at;
private HashMap<String, Integer> listOfProducts;
private Boolean order_paid;
private HashMap<String,String> vouchers_to_use;
public Order() {
}
public Order(String user_code_input) {
order_paid = false;
listOfProducts = new HashMap<String,Integer>();
vouchers_to_use = new HashMap<String,String>();
user_code = user_code_input;
}
public void addProductToOrder(Product product, Integer quantity) {
listOfProducts.put(product.getId(),quantity);
}
public void addVoucherToOrder(String voucher_key, String voucher_signature) {
if(vouchers_to_use.size() <= 3) {
vouchers_to_use.put(voucher_key, voucher_signature.replace("{","{\"").replace("==",""));
} else {
Log.e("WARNING","No more vouchers added because the limit was exceeded");
}
}
public void setConfirmPayment() {
order_paid = true;
}
public FirebaseApp getApp() {
return app;
}public void setApp(FirebaseApp app) {
this.app = app;
}public FirebaseAuth getAuth() {
return auth;
}public void setAuth(FirebaseAuth auth) {
this.auth = auth;
}public String getOrder_id() {
return order_id;
}public void setOrder_id(String order_id) {
this.order_id = order_id;
}public HashMap<String, Integer> getListOfProducts() {
return listOfProducts;
}public void setListOfProducts(HashMap<String, Integer> listOfProducts) {
this.listOfProducts = listOfProducts;
}public Boolean getOrder_paid() {
return order_paid;
}public void setOrder_paid(Boolean order_paid) {
this.order_paid = order_paid;
}
public Double getOrder_price() {
return order_price;
}
public void setOrder_price(Double order_price) {
this.order_price = order_price;
}
public String getUser_code() {
return user_code;
}
public void setUser_code(String user_code) {
this.user_code = user_code;
}
public HashMap<String, String> getVouchers_to_use() {
return vouchers_to_use;
}
public void setVouchers_to_use(HashMap<String, String> vouchers_to_use) {
this.vouchers_to_use = vouchers_to_use;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
}
| UTF-8 | Java | 3,026 | java | Order.java | Java | [
{
"context": "List;\nimport java.util.HashMap;\n\n/**\n * Created by Filipe Batista on 23/10/2016.\n */\n\npublic class Order implements",
"end": 328,
"score": 0.9998703598976135,
"start": 314,
"tag": "NAME",
"value": "Filipe Batista"
}
] | null | [] | package com.example.filipedgb.cmovproj1.classes;
import android.util.Log;
import com.example.filipedgb.cmovproj1.Product;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.FirebaseAuth;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Created by <NAME> on 23/10/2016.
*/
public class Order implements Serializable {
private FirebaseApp app;
private FirebaseAuth auth;
private String order_id;
private Double order_price;
private String user_code;
private String created_at;
private HashMap<String, Integer> listOfProducts;
private Boolean order_paid;
private HashMap<String,String> vouchers_to_use;
public Order() {
}
public Order(String user_code_input) {
order_paid = false;
listOfProducts = new HashMap<String,Integer>();
vouchers_to_use = new HashMap<String,String>();
user_code = user_code_input;
}
public void addProductToOrder(Product product, Integer quantity) {
listOfProducts.put(product.getId(),quantity);
}
public void addVoucherToOrder(String voucher_key, String voucher_signature) {
if(vouchers_to_use.size() <= 3) {
vouchers_to_use.put(voucher_key, voucher_signature.replace("{","{\"").replace("==",""));
} else {
Log.e("WARNING","No more vouchers added because the limit was exceeded");
}
}
public void setConfirmPayment() {
order_paid = true;
}
public FirebaseApp getApp() {
return app;
}public void setApp(FirebaseApp app) {
this.app = app;
}public FirebaseAuth getAuth() {
return auth;
}public void setAuth(FirebaseAuth auth) {
this.auth = auth;
}public String getOrder_id() {
return order_id;
}public void setOrder_id(String order_id) {
this.order_id = order_id;
}public HashMap<String, Integer> getListOfProducts() {
return listOfProducts;
}public void setListOfProducts(HashMap<String, Integer> listOfProducts) {
this.listOfProducts = listOfProducts;
}public Boolean getOrder_paid() {
return order_paid;
}public void setOrder_paid(Boolean order_paid) {
this.order_paid = order_paid;
}
public Double getOrder_price() {
return order_price;
}
public void setOrder_price(Double order_price) {
this.order_price = order_price;
}
public String getUser_code() {
return user_code;
}
public void setUser_code(String user_code) {
this.user_code = user_code;
}
public HashMap<String, String> getVouchers_to_use() {
return vouchers_to_use;
}
public void setVouchers_to_use(HashMap<String, String> vouchers_to_use) {
this.vouchers_to_use = vouchers_to_use;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
}
| 3,018 | 0.649372 | 0.645737 | 116 | 25.077587 | 22.807724 | 100 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | false | false | 8 |
5717da9507c0e11113e99b4d7f6cd14b000b6397 | 24,094,766,589,415 | 0679cf56d5ef3c23cf3bae52d5f94755c264cec3 | /NoteService/src/main/java/com/bridgelabz/note/repository/LabelRepository.java | 449d9edb1852075e610dafdb1b6b27f7475362ea | [] | no_license | Lalit340/MIcroservices-Fundoo-project | https://github.com/Lalit340/MIcroservices-Fundoo-project | 8bf04918ee879ee5d7bf8f31e429b1ab1b5b176c | 5a40dc42c0d17a94a97db6c912e35d7f8fcc9d63 | refs/heads/master | 2022-09-13T11:21:53.135000 | 2019-11-13T06:41:48 | 2019-11-13T06:41:48 | 221,389,066 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.bridgelabz.note.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.bridgelabz.note.model.Label;
@Repository
public interface LabelRepository extends JpaRepository<Label , Long>{
Optional<Label> findByUserIdAndLabelId(long userId,long labelId);
List<Label> findLabelByUserId(long userId);
}
| UTF-8 | Java | 444 | java | LabelRepository.java | Java | [] | null | [] | package com.bridgelabz.note.repository;
import java.util.List;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.bridgelabz.note.model.Label;
@Repository
public interface LabelRepository extends JpaRepository<Label , Long>{
Optional<Label> findByUserIdAndLabelId(long userId,long labelId);
List<Label> findLabelByUserId(long userId);
}
| 444 | 0.824324 | 0.824324 | 16 | 26.75 | 25.063669 | 69 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.8125 | false | false | 8 |
b68e0e497be06ede3dd1c2dcbc7848c4fe722182 | 1,778,116,497,653 | 18e54913a6f1ce6696ade3d1fc4e840f89c093fe | /src/main/java/com/riversql/plugins/mysql/UsersNode.java | a8f0de1023d5df80542f189542d1f95f4d2315dc | [] | no_license | jrialland/riversql | https://github.com/jrialland/riversql | 1c9e585131f3f0c3297f76a592f0f59602baa558 | 9eda1050d6af0ba7ae5bd2a418310e565cf740fd | refs/heads/master | 2020-03-30T23:28:12.382000 | 2018-10-12T18:53:11 | 2018-10-12T18:53:11 | 151,701,308 | 0 | 0 | null | true | 2018-10-05T09:53:11 | 2018-10-05T09:53:11 | 2016-02-19T23:30:42 | 2016-02-19T23:32:02 | 14,930 | 0 | 0 | 0 | null | false | null | package com.riversql.plugins.mysql;
import com.riversql.dbtree.CatalogNode;
import com.riversql.dbtree.IStructureNode;
import com.riversql.plugin.BasePluginType;
import com.riversql.sql.SQLConnection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class UsersNode extends BasePluginType implements IStructureNode {
public UsersNode(CatalogNode caNode, SQLConnection conn) {
super("User", caNode, conn);
}
@Override
public void load() {
if (loaded)
return;
ResultSet rs = null;
PreparedStatement ps = null;
try {
final String sql = "select concat('''',user,'''','@','''',host,'''') from mysql.user";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
String oname = rs.getString(1);
UserNode functNode = new UserNode(this, oname, conn);
list.add(functNode);
}
} catch (Exception e) {
list.clear();
} finally {
try {
if (rs != null)
rs.close();
} catch (Exception e) {
}
try {
if (ps != null)
ps.close();
} catch (Exception e) {
}
}
loaded = true;
}
private String getOwner() {
return parentNode.getName();
}
public String getCls() {
return "objs";
}
public String getType() {
return "mysql_users";
}
public boolean isLeaf() {
return false;
}
}
| UTF-8 | Java | 1,637 | java | UsersNode.java | Java | [] | null | [] | package com.riversql.plugins.mysql;
import com.riversql.dbtree.CatalogNode;
import com.riversql.dbtree.IStructureNode;
import com.riversql.plugin.BasePluginType;
import com.riversql.sql.SQLConnection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class UsersNode extends BasePluginType implements IStructureNode {
public UsersNode(CatalogNode caNode, SQLConnection conn) {
super("User", caNode, conn);
}
@Override
public void load() {
if (loaded)
return;
ResultSet rs = null;
PreparedStatement ps = null;
try {
final String sql = "select concat('''',user,'''','@','''',host,'''') from mysql.user";
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
String oname = rs.getString(1);
UserNode functNode = new UserNode(this, oname, conn);
list.add(functNode);
}
} catch (Exception e) {
list.clear();
} finally {
try {
if (rs != null)
rs.close();
} catch (Exception e) {
}
try {
if (ps != null)
ps.close();
} catch (Exception e) {
}
}
loaded = true;
}
private String getOwner() {
return parentNode.getName();
}
public String getCls() {
return "objs";
}
public String getType() {
return "mysql_users";
}
public boolean isLeaf() {
return false;
}
}
| 1,637 | 0.522908 | 0.522297 | 69 | 22.724638 | 19.643847 | 98 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.521739 | false | false | 8 |
9d154e799a7a05d95774644d0c455487c6a81905 | 24,034,637,052,048 | 668960d4d3d02dcb6161b8260ecc863dd7517636 | /persistence/src/main/java/org/openstack/atlas/service/domain/services/impl/SessionPersistenceServiceImpl.java | a395436b4b62641eb94af9f5b75e11f0370308ba | [] | no_license | lbrackspace/atlas-lb | https://github.com/lbrackspace/atlas-lb | de1eb3c45427b08308d348fe3dbcf3d38ce116cb | dde84090fefc9c6e5861d7f4d39dd291c745f392 | refs/heads/master | 2022-06-16T02:33:58.445000 | 2021-06-11T21:47:56 | 2021-06-11T21:47:56 | 2,043,124 | 3 | 16 | null | true | 2016-10-13T23:36:49 | 2011-07-13T17:12:25 | 2016-08-05T21:13:07 | 2016-10-13T22:25:01 | 120,199 | 11 | 4 | 0 | Java | null | null | package org.openstack.atlas.service.domain.services.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openstack.atlas.docs.loadbalancers.api.v1.faults.BadRequest;
import org.openstack.atlas.service.domain.entities.LoadBalancer;
import org.openstack.atlas.service.domain.entities.LoadBalancerStatus;
import org.openstack.atlas.service.domain.entities.SessionPersistence;
import org.openstack.atlas.service.domain.exceptions.*;
import org.openstack.atlas.service.domain.services.LoadBalancerStatusHistoryService;
import org.openstack.atlas.service.domain.services.SessionPersistenceService;
import org.openstack.atlas.service.domain.services.helpers.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.openstack.atlas.service.domain.entities.LoadBalancerProtocol;
import static org.openstack.atlas.service.domain.entities.LoadBalancerProtocol.*;
import static org.openstack.atlas.service.domain.entities.SessionPersistence.*;
@Service
public class SessionPersistenceServiceImpl extends BaseService implements SessionPersistenceService {
private final Log LOG = LogFactory.getLog(SessionPersistenceServiceImpl.class);
@Autowired
private LoadBalancerStatusHistoryService loadBalancerStatusHistoryService;
@Override
public SessionPersistence get(Integer accountId, Integer lbId) throws EntityNotFoundException, BadRequestException, DeletedStatusException {
return loadBalancerRepository.getSessionPersistenceByAccountIdLoadBalancerId(accountId, lbId);
}
@Override
@Transactional(rollbackFor = {EntityNotFoundException.class, ImmutableEntityException.class, BadRequestException.class})
public void update(LoadBalancer queueLb) throws EntityNotFoundException, ImmutableEntityException, BadRequestException, UnprocessableEntityException {
LOG.debug("Entering " + getClass());
LoadBalancer dbLoadBalancer = loadBalancerRepository.getByIdAndAccountId(queueLb.getId(), queueLb.getAccountId());
validateSessionPersistenceProtocolCompatibility(queueLb, dbLoadBalancer);
LOG.debug("Updating the lb status to pending_update");
if (!loadBalancerRepository.testAndSetStatus(dbLoadBalancer.getAccountId(), dbLoadBalancer.getId(), LoadBalancerStatus.PENDING_UPDATE, false)) {
String message = StringHelper.immutableLoadBalancer(dbLoadBalancer);
LOG.warn(message);
throw new ImmutableEntityException(message);
} else {
//Set status record
loadBalancerStatusHistoryService.save(dbLoadBalancer.getAccountId(), dbLoadBalancer.getId(), LoadBalancerStatus.PENDING_UPDATE);
}
dbLoadBalancer.setSessionPersistence(queueLb.getSessionPersistence());
loadBalancerRepository.update(dbLoadBalancer);
LOG.debug("Leaving " + getClass());
}
@Override
@Transactional(rollbackFor = {EntityNotFoundException.class, ImmutableEntityException.class, UnprocessableEntityException.class})
public void delete(LoadBalancer requestLb) throws Exception {
LOG.debug("Entering " + getClass());
LoadBalancer dbLb = loadBalancerRepository.getByIdAndAccountId(requestLb.getId(), requestLb.getAccountId());
if (dbLb.getSessionPersistence().equals(SessionPersistence.NONE)) {
throw new UnprocessableEntityException("Session persistence is already deleted.");
}
if (!loadBalancerRepository.testAndSetStatus(dbLb.getAccountId(), dbLb.getId(), LoadBalancerStatus.PENDING_UPDATE, false)) {
String message = StringHelper.immutableLoadBalancer(dbLb);
LOG.warn(message);
throw new ImmutableEntityException(message);
} else {
//Set status record
loadBalancerStatusHistoryService.save(dbLb.getAccountId(), dbLb.getId(), LoadBalancerStatus.PENDING_UPDATE);
}
}
public void validateSessionPersistenceProtocolCompatibility(LoadBalancer inLb, LoadBalancer dbLb) throws BadRequestException, UnprocessableEntityException {
SessionPersistence persistenceType = inLb.getSessionPersistence();
LoadBalancerProtocol dbProtocol = dbLb.getProtocol();
String httpErrMsg = "HTTP_COOKIE Session persistence is only valid with HTTP protocol with or without SSL termination.";
String sslErrMsg = "SSL_ID session persistence is only valid with the HTTPS protocol. ";
LOG.info("Verifying session persistence protocol..." + persistenceType);
if (persistenceType != NONE) {
if (persistenceType == HTTP_COOKIE && (dbProtocol != HTTP)) {
LOG.info(httpErrMsg);
throw new BadRequestException(httpErrMsg);
}
if (persistenceType == SSL_ID && (dbProtocol != HTTPS)) {
LOG.info(sslErrMsg);
throw new BadRequestException(sslErrMsg);
}
}
LOG.info("Successfully verified session persistence protocol..." + inLb.getSessionPersistence());
}
}
| UTF-8 | Java | 5,242 | java | SessionPersistenceServiceImpl.java | Java | [] | null | [] | package org.openstack.atlas.service.domain.services.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openstack.atlas.docs.loadbalancers.api.v1.faults.BadRequest;
import org.openstack.atlas.service.domain.entities.LoadBalancer;
import org.openstack.atlas.service.domain.entities.LoadBalancerStatus;
import org.openstack.atlas.service.domain.entities.SessionPersistence;
import org.openstack.atlas.service.domain.exceptions.*;
import org.openstack.atlas.service.domain.services.LoadBalancerStatusHistoryService;
import org.openstack.atlas.service.domain.services.SessionPersistenceService;
import org.openstack.atlas.service.domain.services.helpers.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.openstack.atlas.service.domain.entities.LoadBalancerProtocol;
import static org.openstack.atlas.service.domain.entities.LoadBalancerProtocol.*;
import static org.openstack.atlas.service.domain.entities.SessionPersistence.*;
@Service
public class SessionPersistenceServiceImpl extends BaseService implements SessionPersistenceService {
private final Log LOG = LogFactory.getLog(SessionPersistenceServiceImpl.class);
@Autowired
private LoadBalancerStatusHistoryService loadBalancerStatusHistoryService;
@Override
public SessionPersistence get(Integer accountId, Integer lbId) throws EntityNotFoundException, BadRequestException, DeletedStatusException {
return loadBalancerRepository.getSessionPersistenceByAccountIdLoadBalancerId(accountId, lbId);
}
@Override
@Transactional(rollbackFor = {EntityNotFoundException.class, ImmutableEntityException.class, BadRequestException.class})
public void update(LoadBalancer queueLb) throws EntityNotFoundException, ImmutableEntityException, BadRequestException, UnprocessableEntityException {
LOG.debug("Entering " + getClass());
LoadBalancer dbLoadBalancer = loadBalancerRepository.getByIdAndAccountId(queueLb.getId(), queueLb.getAccountId());
validateSessionPersistenceProtocolCompatibility(queueLb, dbLoadBalancer);
LOG.debug("Updating the lb status to pending_update");
if (!loadBalancerRepository.testAndSetStatus(dbLoadBalancer.getAccountId(), dbLoadBalancer.getId(), LoadBalancerStatus.PENDING_UPDATE, false)) {
String message = StringHelper.immutableLoadBalancer(dbLoadBalancer);
LOG.warn(message);
throw new ImmutableEntityException(message);
} else {
//Set status record
loadBalancerStatusHistoryService.save(dbLoadBalancer.getAccountId(), dbLoadBalancer.getId(), LoadBalancerStatus.PENDING_UPDATE);
}
dbLoadBalancer.setSessionPersistence(queueLb.getSessionPersistence());
loadBalancerRepository.update(dbLoadBalancer);
LOG.debug("Leaving " + getClass());
}
@Override
@Transactional(rollbackFor = {EntityNotFoundException.class, ImmutableEntityException.class, UnprocessableEntityException.class})
public void delete(LoadBalancer requestLb) throws Exception {
LOG.debug("Entering " + getClass());
LoadBalancer dbLb = loadBalancerRepository.getByIdAndAccountId(requestLb.getId(), requestLb.getAccountId());
if (dbLb.getSessionPersistence().equals(SessionPersistence.NONE)) {
throw new UnprocessableEntityException("Session persistence is already deleted.");
}
if (!loadBalancerRepository.testAndSetStatus(dbLb.getAccountId(), dbLb.getId(), LoadBalancerStatus.PENDING_UPDATE, false)) {
String message = StringHelper.immutableLoadBalancer(dbLb);
LOG.warn(message);
throw new ImmutableEntityException(message);
} else {
//Set status record
loadBalancerStatusHistoryService.save(dbLb.getAccountId(), dbLb.getId(), LoadBalancerStatus.PENDING_UPDATE);
}
}
public void validateSessionPersistenceProtocolCompatibility(LoadBalancer inLb, LoadBalancer dbLb) throws BadRequestException, UnprocessableEntityException {
SessionPersistence persistenceType = inLb.getSessionPersistence();
LoadBalancerProtocol dbProtocol = dbLb.getProtocol();
String httpErrMsg = "HTTP_COOKIE Session persistence is only valid with HTTP protocol with or without SSL termination.";
String sslErrMsg = "SSL_ID session persistence is only valid with the HTTPS protocol. ";
LOG.info("Verifying session persistence protocol..." + persistenceType);
if (persistenceType != NONE) {
if (persistenceType == HTTP_COOKIE && (dbProtocol != HTTP)) {
LOG.info(httpErrMsg);
throw new BadRequestException(httpErrMsg);
}
if (persistenceType == SSL_ID && (dbProtocol != HTTPS)) {
LOG.info(sslErrMsg);
throw new BadRequestException(sslErrMsg);
}
}
LOG.info("Successfully verified session persistence protocol..." + inLb.getSessionPersistence());
}
}
| 5,242 | 0.752957 | 0.752766 | 100 | 51.41 | 44.052036 | 160 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.75 | false | false | 8 |
795a9aae281430fd1be1a6aec4baf2604f68a82e | 14,362,370,644,552 | 37134b3880480113bc7e86f969c55984a188feaa | /app/src/main/java/com/gat/data/user/PaperUserDataSource.java | 893012771550314bc6f965bacab09a2702c5fb13 | [
"Apache-2.0"
] | permissive | truongxuantran/GAT | https://github.com/truongxuantran/GAT | 897779b83433f38a020b55884cef9e92ea3faa55 | 759174f63ac7aaf6a393b348032dab9e983d3001 | refs/heads/master | 2021-06-21T14:22:49.642000 | 2017-05-24T10:07:12 | 2017-05-24T10:07:12 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.gat.data.user;
import android.location.Address;
import android.util.Log;
import com.gat.common.util.Strings;
import com.gat.data.response.DataResultListResponse;
import com.gat.data.response.ServerResponse;
import com.gat.data.response.UserResponse;
import com.gat.data.response.impl.Keyword;
import com.gat.data.response.impl.LoginResponseData;
import com.gat.data.response.impl.NotifyEntity;
import com.gat.data.response.impl.ResetPasswordResponseData;
import com.gat.data.response.impl.VerifyTokenResponseData;
import com.gat.feature.bookdetailsender.entity.ChangeStatusResponse;
import com.gat.feature.editinfo.entity.EditInfoInput;
import com.gat.feature.personal.entity.BookChangeStatusInput;
import com.gat.feature.personal.entity.BookInstanceInput;
import com.gat.feature.personal.entity.BookReadingInput;
import com.gat.feature.personal.entity.BookRequestInput;
import com.gat.feature.personal.entity.RequestStatusInput;
import com.gat.feature.personaluser.entity.BookSharingUserInput;
import com.gat.feature.personaluser.entity.BorrowRequestInput;
import com.gat.repository.datasource.UserDataSource;
import com.gat.repository.entity.Data;
import com.gat.repository.entity.FirebasePassword;
import com.gat.repository.entity.LoginData;
import com.gat.repository.entity.User;
import com.gat.repository.entity.UserNearByDistance;
import com.google.android.gms.maps.model.LatLng;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import io.paperdb.Book;
import io.paperdb.Paper;
import io.reactivex.Observable;
/**
* Created by Rey on 2/23/2017.
* An implementation of UserDataSource that use PaperDb as local database.
*/
public class PaperUserDataSource implements UserDataSource {
private static final String TAG = PaperUserDataSource.class.getSimpleName();
private static final String BOOK = "user";
private static final String KEY_USER = "user";
private static final String KEY_LOGINDATA = "loginData";
private static final String KEY_RESET_TOKEN = "resetToken";
private static final String KEY_VERIFY_TOKEN = "verifiedToken";
private static final String KEY_LOGIN_TOKEN = "loginToken";
private static final String EMAIL = "email";
private static final String KEY_USER_LIST = "userList";
private List<User> userList = new ArrayList<>();
private final Book book = Paper.book(BOOK);
@Override
public Observable<User> loadUser() {
return Observable.fromCallable(() -> book.read(KEY_USER, User.NONE));
}
@Override
public void persitUser(User user) {
if (user == null) {
book.delete(KEY_USER);
} else {
book.write(KEY_USER, user);
}
}
@Override
public Observable<LoginData> loadLoginData() {
Log.d(TAG, "loadLoginData");
return Observable.fromCallable(()-> {
LoginData loginData = book.read(KEY_LOGINDATA, LoginData.EMPTY);
return loginData;
});
}
@Override
public void saveLoginData(LoginData loginData) {
book.write(KEY_LOGINDATA, loginData);
return;
}
@Override
public Observable<ServerResponse<ResetPasswordResponseData>> storeResetToken(String email, ServerResponse<ResetPasswordResponseData> data) {
return Observable.fromCallable(() -> {
book.write(KEY_RESET_TOKEN, data);
book.write(EMAIL, email);
return data;
});
}
@Override
public Observable<String> getEmailLogin() {
return Observable.fromCallable(() -> book.read(EMAIL));
}
@Override
public Observable<ServerResponse<ResetPasswordResponseData>> getResetToken() {
return Observable.fromCallable(() -> book.read(KEY_RESET_TOKEN));
}
@Override
public Observable<ServerResponse<VerifyTokenResponseData>> storeVerifyToken(ServerResponse<VerifyTokenResponseData> data) {
return Observable.fromCallable(() -> {
book.write(KEY_VERIFY_TOKEN, data);
return data;
});
}
@Override
public Observable<ServerResponse<VerifyTokenResponseData>> getVerifyToken() {
return Observable.fromCallable(() -> book.read(KEY_VERIFY_TOKEN));
}
@Override
public void storeLoginToken(String loginToken) {
if (loginToken != null)
book.write(KEY_LOGIN_TOKEN, loginToken);
else
book.delete(KEY_LOGIN_TOKEN);
return;
}
@Override
public Observable<String> getLoginToken() {
return Observable.fromCallable(() -> book.read(KEY_LOGIN_TOKEN, Strings.EMPTY));
}
@Override
public Observable<Boolean> signOut() {
return Observable.fromCallable(() -> {
book.delete(KEY_LOGINDATA);
book.delete(KEY_USER);
return true;
});
}
@Override
public Observable<Boolean> messageNotification(int receiver, String message) {
throw new UnsupportedOperationException();
}
@Override
public Observable<Boolean> registerFirebaseToken(String token) {
throw new UnsupportedOperationException();
}
@Override
public Observable<List<User>> getListUserInfo(List<Integer> userIdList) {
throw new UnsupportedOperationException();
}
@Override
public Observable<String> updateUserInfo(EditInfoInput input) {
return null;
}
@Override
public Observable<Data> getBookUserSharing(BookSharingUserInput input) {
return null;
}
@Override
public Observable<Data> getBookDetail(Integer input) {
return null;
}
@Override
public Observable<DataResultListResponse<NotifyEntity>> getUserNotification(int page, int per_page) {
return null;
}
@Override
public Observable<String> requestBookByBorrower(RequestStatusInput input) {
return null;
}
@Override
public Observable<ChangeStatusResponse> requestBookByOwner(RequestStatusInput input) {
return null;
}
@Override
public Observable<Data> requestBorrowBook(BorrowRequestInput input) {
return null;
}
@Override
public Observable<ServerResponse> unlinkSocialAccount(int socialType) {
return null;
}
@Override
public Observable<ServerResponse> linkSocialAccount(String socialID, String socialName, int socialType) {
return null;
}
@Override
public Observable<ServerResponse<FirebasePassword>> addEmailPassword(String email, String password) {
return null;
}
@Override
public Observable<ServerResponse> changeOldPassword(String newPassword, String oldPassword) {
return null;
}
@Override
public Observable<String> removeBook(int instanceId) {
return null;
}
@Override
public Observable<ServerResponse<LoginResponseData>> login(LoginData data) {
throw new UnsupportedOperationException();
}
@Override
public Observable<ServerResponse<LoginResponseData>> register(LoginData loginData) {
throw new UnsupportedOperationException();
}
@Override
public Observable<ServerResponse<ResetPasswordResponseData>> sendRequestResetPassword(String email) {
throw new UnsupportedOperationException();
}
@Override
public Observable<ServerResponse<VerifyTokenResponseData>> verifyToken(String code, String tokenReset) {
throw new UnsupportedOperationException();
}
@Override
public Observable<ServerResponse<LoginResponseData>> changePassword(String password, String tokenVerified) {
throw new UnsupportedOperationException();
}
@Override
public Observable<List<Address>> getAddress(LatLng location) {
throw new UnsupportedOperationException();
}
@Override
public Observable<ServerResponse> updateLocation(String address, float longitude, float latitude) {
throw new UnsupportedOperationException();
}
@Override
public Observable<ServerResponse> updateCategories(List<Integer> categories) {
throw new UnsupportedOperationException();
}
@Override
public Observable<DataResultListResponse<UserNearByDistance>> getPeopleNearByUserByDistance(float currentLongitude, float currentLatitude, float neLongitude, float neLatitude, float wsLongitude, float wsLatitude, int page, int size_of_page) {
throw new UnsupportedOperationException();
}
@Override
public Observable<DataResultListResponse<UserResponse>> searchUser(String name, int page, int sizeOfPage) {
throw new UnsupportedOperationException();
}
@Override
public Observable<DataResultListResponse<UserResponse>> searchUserTotal(String name, int userId) {
throw new UnsupportedOperationException();
}
@Override
public Observable<List<Keyword>> getUsersSearchedKeyword() {
return null;
}
@Override
public Observable<Data<User>> getPersonalInfo() {
return null;
}
@Override
public Observable<Data> getBookInstance(BookInstanceInput instanceInput) {
return null;
}
@Override
public Observable<Data> getBookRequest(BookRequestInput instanceInput) {
return null;
}
@Override
public Observable<String> changeBookSharingStatus(BookChangeStatusInput input) {
return null;
}
@Override
public Observable<Data> getReadingBook(BookReadingInput input) {
return null;
}
@Override
public Observable<User> getUserInformation(int userId) {
return null;
}
}
| UTF-8 | Java | 9,602 | java | PaperUserDataSource.java | Java | [
{
"context": "import io.reactivex.Observable;\n\n/**\n * Created by Rey on 2/23/2017.\n * An implementation of UserDataSou",
"end": 1583,
"score": 0.7796498537063599,
"start": 1580,
"tag": "NAME",
"value": "Rey"
},
{
"context": "\";\n private static final String KEY_USER = \"us... | null | [] | package com.gat.data.user;
import android.location.Address;
import android.util.Log;
import com.gat.common.util.Strings;
import com.gat.data.response.DataResultListResponse;
import com.gat.data.response.ServerResponse;
import com.gat.data.response.UserResponse;
import com.gat.data.response.impl.Keyword;
import com.gat.data.response.impl.LoginResponseData;
import com.gat.data.response.impl.NotifyEntity;
import com.gat.data.response.impl.ResetPasswordResponseData;
import com.gat.data.response.impl.VerifyTokenResponseData;
import com.gat.feature.bookdetailsender.entity.ChangeStatusResponse;
import com.gat.feature.editinfo.entity.EditInfoInput;
import com.gat.feature.personal.entity.BookChangeStatusInput;
import com.gat.feature.personal.entity.BookInstanceInput;
import com.gat.feature.personal.entity.BookReadingInput;
import com.gat.feature.personal.entity.BookRequestInput;
import com.gat.feature.personal.entity.RequestStatusInput;
import com.gat.feature.personaluser.entity.BookSharingUserInput;
import com.gat.feature.personaluser.entity.BorrowRequestInput;
import com.gat.repository.datasource.UserDataSource;
import com.gat.repository.entity.Data;
import com.gat.repository.entity.FirebasePassword;
import com.gat.repository.entity.LoginData;
import com.gat.repository.entity.User;
import com.gat.repository.entity.UserNearByDistance;
import com.google.android.gms.maps.model.LatLng;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import io.paperdb.Book;
import io.paperdb.Paper;
import io.reactivex.Observable;
/**
* Created by Rey on 2/23/2017.
* An implementation of UserDataSource that use PaperDb as local database.
*/
public class PaperUserDataSource implements UserDataSource {
private static final String TAG = PaperUserDataSource.class.getSimpleName();
private static final String BOOK = "user";
private static final String KEY_USER = "user";
private static final String KEY_LOGINDATA = "loginData";
private static final String KEY_RESET_TOKEN = "resetToken";
private static final String KEY_VERIFY_TOKEN = "verifiedToken";
private static final String KEY_LOGIN_TOKEN = "loginToken";
private static final String EMAIL = "email";
private static final String KEY_USER_LIST = "userList";
private List<User> userList = new ArrayList<>();
private final Book book = Paper.book(BOOK);
@Override
public Observable<User> loadUser() {
return Observable.fromCallable(() -> book.read(KEY_USER, User.NONE));
}
@Override
public void persitUser(User user) {
if (user == null) {
book.delete(KEY_USER);
} else {
book.write(KEY_USER, user);
}
}
@Override
public Observable<LoginData> loadLoginData() {
Log.d(TAG, "loadLoginData");
return Observable.fromCallable(()-> {
LoginData loginData = book.read(KEY_LOGINDATA, LoginData.EMPTY);
return loginData;
});
}
@Override
public void saveLoginData(LoginData loginData) {
book.write(KEY_LOGINDATA, loginData);
return;
}
@Override
public Observable<ServerResponse<ResetPasswordResponseData>> storeResetToken(String email, ServerResponse<ResetPasswordResponseData> data) {
return Observable.fromCallable(() -> {
book.write(KEY_RESET_TOKEN, data);
book.write(EMAIL, email);
return data;
});
}
@Override
public Observable<String> getEmailLogin() {
return Observable.fromCallable(() -> book.read(EMAIL));
}
@Override
public Observable<ServerResponse<ResetPasswordResponseData>> getResetToken() {
return Observable.fromCallable(() -> book.read(KEY_RESET_TOKEN));
}
@Override
public Observable<ServerResponse<VerifyTokenResponseData>> storeVerifyToken(ServerResponse<VerifyTokenResponseData> data) {
return Observable.fromCallable(() -> {
book.write(KEY_VERIFY_TOKEN, data);
return data;
});
}
@Override
public Observable<ServerResponse<VerifyTokenResponseData>> getVerifyToken() {
return Observable.fromCallable(() -> book.read(KEY_VERIFY_TOKEN));
}
@Override
public void storeLoginToken(String loginToken) {
if (loginToken != null)
book.write(KEY_LOGIN_TOKEN, loginToken);
else
book.delete(KEY_LOGIN_TOKEN);
return;
}
@Override
public Observable<String> getLoginToken() {
return Observable.fromCallable(() -> book.read(KEY_LOGIN_TOKEN, Strings.EMPTY));
}
@Override
public Observable<Boolean> signOut() {
return Observable.fromCallable(() -> {
book.delete(KEY_LOGINDATA);
book.delete(KEY_USER);
return true;
});
}
@Override
public Observable<Boolean> messageNotification(int receiver, String message) {
throw new UnsupportedOperationException();
}
@Override
public Observable<Boolean> registerFirebaseToken(String token) {
throw new UnsupportedOperationException();
}
@Override
public Observable<List<User>> getListUserInfo(List<Integer> userIdList) {
throw new UnsupportedOperationException();
}
@Override
public Observable<String> updateUserInfo(EditInfoInput input) {
return null;
}
@Override
public Observable<Data> getBookUserSharing(BookSharingUserInput input) {
return null;
}
@Override
public Observable<Data> getBookDetail(Integer input) {
return null;
}
@Override
public Observable<DataResultListResponse<NotifyEntity>> getUserNotification(int page, int per_page) {
return null;
}
@Override
public Observable<String> requestBookByBorrower(RequestStatusInput input) {
return null;
}
@Override
public Observable<ChangeStatusResponse> requestBookByOwner(RequestStatusInput input) {
return null;
}
@Override
public Observable<Data> requestBorrowBook(BorrowRequestInput input) {
return null;
}
@Override
public Observable<ServerResponse> unlinkSocialAccount(int socialType) {
return null;
}
@Override
public Observable<ServerResponse> linkSocialAccount(String socialID, String socialName, int socialType) {
return null;
}
@Override
public Observable<ServerResponse<FirebasePassword>> addEmailPassword(String email, String password) {
return null;
}
@Override
public Observable<ServerResponse> changeOldPassword(String newPassword, String oldPassword) {
return null;
}
@Override
public Observable<String> removeBook(int instanceId) {
return null;
}
@Override
public Observable<ServerResponse<LoginResponseData>> login(LoginData data) {
throw new UnsupportedOperationException();
}
@Override
public Observable<ServerResponse<LoginResponseData>> register(LoginData loginData) {
throw new UnsupportedOperationException();
}
@Override
public Observable<ServerResponse<ResetPasswordResponseData>> sendRequestResetPassword(String email) {
throw new UnsupportedOperationException();
}
@Override
public Observable<ServerResponse<VerifyTokenResponseData>> verifyToken(String code, String tokenReset) {
throw new UnsupportedOperationException();
}
@Override
public Observable<ServerResponse<LoginResponseData>> changePassword(String password, String tokenVerified) {
throw new UnsupportedOperationException();
}
@Override
public Observable<List<Address>> getAddress(LatLng location) {
throw new UnsupportedOperationException();
}
@Override
public Observable<ServerResponse> updateLocation(String address, float longitude, float latitude) {
throw new UnsupportedOperationException();
}
@Override
public Observable<ServerResponse> updateCategories(List<Integer> categories) {
throw new UnsupportedOperationException();
}
@Override
public Observable<DataResultListResponse<UserNearByDistance>> getPeopleNearByUserByDistance(float currentLongitude, float currentLatitude, float neLongitude, float neLatitude, float wsLongitude, float wsLatitude, int page, int size_of_page) {
throw new UnsupportedOperationException();
}
@Override
public Observable<DataResultListResponse<UserResponse>> searchUser(String name, int page, int sizeOfPage) {
throw new UnsupportedOperationException();
}
@Override
public Observable<DataResultListResponse<UserResponse>> searchUserTotal(String name, int userId) {
throw new UnsupportedOperationException();
}
@Override
public Observable<List<Keyword>> getUsersSearchedKeyword() {
return null;
}
@Override
public Observable<Data<User>> getPersonalInfo() {
return null;
}
@Override
public Observable<Data> getBookInstance(BookInstanceInput instanceInput) {
return null;
}
@Override
public Observable<Data> getBookRequest(BookRequestInput instanceInput) {
return null;
}
@Override
public Observable<String> changeBookSharingStatus(BookChangeStatusInput input) {
return null;
}
@Override
public Observable<Data> getReadingBook(BookReadingInput input) {
return null;
}
@Override
public Observable<User> getUserInformation(int userId) {
return null;
}
}
| 9,602 | 0.705895 | 0.705166 | 310 | 29.974194 | 32.21299 | 246 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.43871 | false | false | 8 |
d9f5e92b04b779175fd7dfcc4a9ac864efac812e | 16,277,926,109,926 | e4135147ba57474b4d1a353e813a7a6de46c57af | /easy-root/.svn/pristine/d9/d9f5e92b04b779175fd7dfcc4a9ac864efac812e.svn-base | 142be5cee5cf7c633b4ff040cbe052bdbb7a0169 | [] | no_license | huscachafe/ftbladmin | https://github.com/huscachafe/ftbladmin | eb3963637d0e478fd4c15f83cf333d126d181c42 | 2814e9a1ea3b0b86e1f86ddb658fad42dee7ed4f | refs/heads/master | 2017-12-08T20:38:12.388000 | 2017-02-22T23:40:09 | 2017-02-22T23:40:09 | 79,281,017 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package cl.easy.module.integration.fo.order.syncronization.test;
import cl.easy.module.integration.fo.order.synchronization.dto.SyncOrderDTO;
import cl.easy.module.integration.fo.order.synchronization.dto.SyncOrderItemDTO;
import cl.easy.module.integration.fo.order.synchronization.spring.SpringOrderSynchronizationService;
import cl.easy.module.test.spring.WebServiceTestTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.ws.test.client.MockWebServiceServer;
import org.springframework.ws.test.client.RequestMatcher;
import org.springframework.ws.test.client.RequestMatchers;
import org.springframework.ws.test.client.ResponseActions;
import org.springframework.ws.test.client.ResponseCreator;
import org.springframework.ws.test.client.ResponseCreators;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.xml.transform.Source;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:order-syncronization-service-configuration.xml")
public class SpringOrderSyncronizationServiceTest {
private static final String REQUEST_XML_PATH = "classpath:data/order-sync-request.xml";
private static final String RESPONSE_OK_XML_PATH = "classpath:data/order-sync-response-ok.xml";
private static final String RESPONSE_NOK_XML_PATH = "classpath:data/order-sync-response-nok.xml";
private static final String RESPONSE_NOK_USER_XML_PATH = "classpath:data/order-sync-response-nok-user.xml";
@Autowired
private SpringOrderSynchronizationService springOrderSynchronizationService;
@Test
public void testSuccessSyncOrder() {
Source requestPayload = WebServiceTestTool.resolveXmlSource(REQUEST_XML_PATH);
RequestMatcher request = RequestMatchers.payload(requestPayload);
MockWebServiceServer mockServer = WebServiceTestTool.buildMockServer(springOrderSynchronizationService);
ResponseActions expectedResponse = mockServer.expect(request);
Source responsePayload = WebServiceTestTool.resolveXmlSource(RESPONSE_OK_XML_PATH);
ResponseCreator response = ResponseCreators.withPayload(responsePayload);
expectedResponse.andRespond(response);
try {
springOrderSynchronizationService.updateStatus(setSyncOrder());
Assert.assertNotNull(true);
} catch (Exception exception) {
exception.printStackTrace();
Assert.fail("This assertion error should not have been threw. Please check exception stack trace.");
}
}
@Test
public void testFailureSyncOrder() {
Source requestPayload = WebServiceTestTool.resolveXmlSource(REQUEST_XML_PATH);
RequestMatcher request = RequestMatchers.payload(requestPayload);
MockWebServiceServer mockServer = WebServiceTestTool.buildMockServer(springOrderSynchronizationService);
ResponseActions expectedResponse = mockServer.expect(request);
Source responsePayload = WebServiceTestTool.resolveXmlSource(RESPONSE_NOK_XML_PATH);
ResponseCreator response = ResponseCreators.withPayload(responsePayload);
expectedResponse.andRespond(response);
try {
springOrderSynchronizationService.updateStatus(setSyncOrder());
Assert.assertNotNull(true);
} catch (Exception exception) {
exception.printStackTrace();
Assert.fail("This assertion error should not have been threw. Please check exception stack trace.");
}
}
@Test
public void testFailureUserSyncOrder() {
Source requestPayload = WebServiceTestTool.resolveXmlSource(REQUEST_XML_PATH);
RequestMatcher request = RequestMatchers.payload(requestPayload);
MockWebServiceServer mockServer = WebServiceTestTool.buildMockServer(springOrderSynchronizationService);
ResponseActions expectedResponse = mockServer.expect(request);
Source responsePayload = WebServiceTestTool.resolveXmlSource(RESPONSE_NOK_USER_XML_PATH);
ResponseCreator response = ResponseCreators.withPayload(responsePayload);
expectedResponse.andRespond(response);
try {
springOrderSynchronizationService.updateStatus(setSyncOrder());
Assert.assertNotNull(true);
} catch (Exception exception) {
exception.printStackTrace();
Assert.fail("This assertion error should not have been threw. Please check exception stack trace.");
}
}
private SyncOrderDTO setSyncOrder(){
SyncOrderDTO syncOrder = new SyncOrderDTO();
syncOrder.setStoredId("10151");
syncOrder.setUniqueId(46001L);
syncOrder.setStatusUniqueId("M");
SyncOrderItemDTO syncOrderItemDTO = new SyncOrderItemDTO();
syncOrderItemDTO.setItemUniqueId(210001L);
syncOrderItemDTO.setStatusItemUnique("S");
syncOrder.getItems().add(syncOrderItemDTO);
syncOrder.setPassdb("passw0rd4");
syncOrder.setUserdb("wcsadmin");
return syncOrder;
}
}
| UTF-8 | Java | 5,196 | d9f5e92b04b779175fd7dfcc4a9ac864efac812e.svn-base | Java | [
{
"context": "d(syncOrderItemDTO);\n syncOrder.setPassdb(\"passw0rd4\");\n syncOrder.setUserdb(\"wcsadmin\");\n ",
"end": 5117,
"score": 0.9991528391838074,
"start": 5108,
"tag": "PASSWORD",
"value": "passw0rd4"
}
] | null | [] | package cl.easy.module.integration.fo.order.syncronization.test;
import cl.easy.module.integration.fo.order.synchronization.dto.SyncOrderDTO;
import cl.easy.module.integration.fo.order.synchronization.dto.SyncOrderItemDTO;
import cl.easy.module.integration.fo.order.synchronization.spring.SpringOrderSynchronizationService;
import cl.easy.module.test.spring.WebServiceTestTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.ws.test.client.MockWebServiceServer;
import org.springframework.ws.test.client.RequestMatcher;
import org.springframework.ws.test.client.RequestMatchers;
import org.springframework.ws.test.client.ResponseActions;
import org.springframework.ws.test.client.ResponseCreator;
import org.springframework.ws.test.client.ResponseCreators;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.xml.transform.Source;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:order-syncronization-service-configuration.xml")
public class SpringOrderSyncronizationServiceTest {
private static final String REQUEST_XML_PATH = "classpath:data/order-sync-request.xml";
private static final String RESPONSE_OK_XML_PATH = "classpath:data/order-sync-response-ok.xml";
private static final String RESPONSE_NOK_XML_PATH = "classpath:data/order-sync-response-nok.xml";
private static final String RESPONSE_NOK_USER_XML_PATH = "classpath:data/order-sync-response-nok-user.xml";
@Autowired
private SpringOrderSynchronizationService springOrderSynchronizationService;
@Test
public void testSuccessSyncOrder() {
Source requestPayload = WebServiceTestTool.resolveXmlSource(REQUEST_XML_PATH);
RequestMatcher request = RequestMatchers.payload(requestPayload);
MockWebServiceServer mockServer = WebServiceTestTool.buildMockServer(springOrderSynchronizationService);
ResponseActions expectedResponse = mockServer.expect(request);
Source responsePayload = WebServiceTestTool.resolveXmlSource(RESPONSE_OK_XML_PATH);
ResponseCreator response = ResponseCreators.withPayload(responsePayload);
expectedResponse.andRespond(response);
try {
springOrderSynchronizationService.updateStatus(setSyncOrder());
Assert.assertNotNull(true);
} catch (Exception exception) {
exception.printStackTrace();
Assert.fail("This assertion error should not have been threw. Please check exception stack trace.");
}
}
@Test
public void testFailureSyncOrder() {
Source requestPayload = WebServiceTestTool.resolveXmlSource(REQUEST_XML_PATH);
RequestMatcher request = RequestMatchers.payload(requestPayload);
MockWebServiceServer mockServer = WebServiceTestTool.buildMockServer(springOrderSynchronizationService);
ResponseActions expectedResponse = mockServer.expect(request);
Source responsePayload = WebServiceTestTool.resolveXmlSource(RESPONSE_NOK_XML_PATH);
ResponseCreator response = ResponseCreators.withPayload(responsePayload);
expectedResponse.andRespond(response);
try {
springOrderSynchronizationService.updateStatus(setSyncOrder());
Assert.assertNotNull(true);
} catch (Exception exception) {
exception.printStackTrace();
Assert.fail("This assertion error should not have been threw. Please check exception stack trace.");
}
}
@Test
public void testFailureUserSyncOrder() {
Source requestPayload = WebServiceTestTool.resolveXmlSource(REQUEST_XML_PATH);
RequestMatcher request = RequestMatchers.payload(requestPayload);
MockWebServiceServer mockServer = WebServiceTestTool.buildMockServer(springOrderSynchronizationService);
ResponseActions expectedResponse = mockServer.expect(request);
Source responsePayload = WebServiceTestTool.resolveXmlSource(RESPONSE_NOK_USER_XML_PATH);
ResponseCreator response = ResponseCreators.withPayload(responsePayload);
expectedResponse.andRespond(response);
try {
springOrderSynchronizationService.updateStatus(setSyncOrder());
Assert.assertNotNull(true);
} catch (Exception exception) {
exception.printStackTrace();
Assert.fail("This assertion error should not have been threw. Please check exception stack trace.");
}
}
private SyncOrderDTO setSyncOrder(){
SyncOrderDTO syncOrder = new SyncOrderDTO();
syncOrder.setStoredId("10151");
syncOrder.setUniqueId(46001L);
syncOrder.setStatusUniqueId("M");
SyncOrderItemDTO syncOrderItemDTO = new SyncOrderItemDTO();
syncOrderItemDTO.setItemUniqueId(210001L);
syncOrderItemDTO.setStatusItemUnique("S");
syncOrder.getItems().add(syncOrderItemDTO);
syncOrder.setPassdb("<PASSWORD>");
syncOrder.setUserdb("wcsadmin");
return syncOrder;
}
}
| 5,197 | 0.754426 | 0.750385 | 108 | 47.111111 | 34.508812 | 112 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.62037 | false | false | 8 | |
ac8ded65250dc164942a0e2225aa3e5b2ae22fba | 13,975,823,627,283 | 6bd00bf1cd09f50793f061b85dcfcf3244a84a10 | /src/main/java/com/example/bootbegin/services/imp/DirectorService.java | 935c641a3e27a909457cc2e8502b282f9549e8bf | [] | no_license | TarikoDan/bootbegin | https://github.com/TarikoDan/bootbegin | d75702761dedd812ed310a50d328856e7ab8cf8e | 968a0bbdb3a5c0f4841401b5e276dc0a51a30422 | refs/heads/master | 2023-01-04T13:57:53.354000 | 2020-10-24T14:15:41 | 2020-10-24T14:15:41 | 296,167,161 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.example.bootbegin.services.imp;
import com.example.bootbegin.dao.DirectorDAO;
import com.example.bootbegin.entity.Director;
import com.example.bootbegin.services.IDirectorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class DirectorService implements IDirectorService {
@Autowired
DirectorDAO directorDAO;
@Override
public Director insert(Director director) {
return directorDAO.save(director);
}
@Override
public List<Director> getAll() {
return directorDAO.findAll();
}
@Override
public Director getById(int id) {
return directorDAO.findById(id).orElseThrow(() ->
new NullPointerException("There is no such Director with id = " + id));
}
@Override
public Director getByMovieTitle(String movieTitle) {
return directorDAO.getDirectorByMovieTitle(movieTitle);
}
@Override
public Director edit(int id, Director director) {
if (directorDAO.existsById(id)){
director.setId(id);
return directorDAO.saveAndFlush(director);
}else {
throw new NullPointerException("There is no such Director with id = " + id);
}
}
@Override
public void deleteById(int id) {
if (directorDAO.existsById(id)){
directorDAO.deleteById(id);
}else {
throw new NullPointerException("There is no such Director with id = " + id);
}
}
@Override
public void clear() {
directorDAO.deleteAll();
}
}
| UTF-8 | Java | 1,651 | java | DirectorService.java | Java | [] | null | [] | package com.example.bootbegin.services.imp;
import com.example.bootbegin.dao.DirectorDAO;
import com.example.bootbegin.entity.Director;
import com.example.bootbegin.services.IDirectorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class DirectorService implements IDirectorService {
@Autowired
DirectorDAO directorDAO;
@Override
public Director insert(Director director) {
return directorDAO.save(director);
}
@Override
public List<Director> getAll() {
return directorDAO.findAll();
}
@Override
public Director getById(int id) {
return directorDAO.findById(id).orElseThrow(() ->
new NullPointerException("There is no such Director with id = " + id));
}
@Override
public Director getByMovieTitle(String movieTitle) {
return directorDAO.getDirectorByMovieTitle(movieTitle);
}
@Override
public Director edit(int id, Director director) {
if (directorDAO.existsById(id)){
director.setId(id);
return directorDAO.saveAndFlush(director);
}else {
throw new NullPointerException("There is no such Director with id = " + id);
}
}
@Override
public void deleteById(int id) {
if (directorDAO.existsById(id)){
directorDAO.deleteById(id);
}else {
throw new NullPointerException("There is no such Director with id = " + id);
}
}
@Override
public void clear() {
directorDAO.deleteAll();
}
}
| 1,651 | 0.662629 | 0.662629 | 62 | 25.629032 | 24.360355 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.306452 | false | false | 8 |
c491794fc4d03548140dea6ff410f17be37bde78 | 11,819,750,035,257 | fb46ba2b9290e7f1cabc1dcdda031bb2f47513e3 | /src/main/java/training/busboard/RequestPostcode.java | cc4389de1ecaf1b9d5f42e5f788cf8ec07e59dfa | [] | no_license | kapil-krishna/busboard-java | https://github.com/kapil-krishna/busboard-java | b4f52b32a6928a20d7c5bea86a933f7ebca076d8 | 0959c932c9a90c07f5f38fe2557b4cabf807cf14 | refs/heads/master | 2020-08-29T11:20:17.144000 | 2019-10-30T17:16:28 | 2019-10-30T17:16:28 | 218,017,165 | 0 | 0 | null | true | 2019-10-28T10:04:31 | 2019-10-28T10:04:31 | 2019-10-15T14:29:55 | 2019-10-15T14:29:52 | 34 | 0 | 0 | 0 | null | false | false | package training.busboard;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RequestPostcode {
public static String RequestPostcode() {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Bus Stop finder! Input your postcode to find out the next 5 buses" +
" arriving at your two nearest stops!");
String postCode = input.nextLine();
Pattern pattern = Pattern.compile("([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\\s?[0-9][A-Za-z]{2})");
Matcher matcher = pattern.matcher(postCode);
while (!(matcher.matches())) {
Scanner repeat = new Scanner(System.in);
System.out.println("I'll need a valid postcode to work my magic.");
postCode = repeat.nextLine();
}
return postCode;
}
}
| UTF-8 | Java | 986 | java | RequestPostcode.java | Java | [] | null | [] | package training.busboard;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RequestPostcode {
public static String RequestPostcode() {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the Bus Stop finder! Input your postcode to find out the next 5 buses" +
" arriving at your two nearest stops!");
String postCode = input.nextLine();
Pattern pattern = Pattern.compile("([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\\s?[0-9][A-Za-z]{2})");
Matcher matcher = pattern.matcher(postCode);
while (!(matcher.matches())) {
Scanner repeat = new Scanner(System.in);
System.out.println("I'll need a valid postcode to work my magic.");
postCode = repeat.nextLine();
}
return postCode;
}
}
| 986 | 0.599391 | 0.581136 | 25 | 38.439999 | 45.053818 | 216 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.76 | false | false | 2 |
858d550bad7135cd7d3790ee9e74dd6e03789dd4 | 16,973,710,784,722 | 1c632157c66ed963f8417f5ef2756d3e32a04e71 | /src/main/java/com/company/jobServer/executors/ConnectorJobExecutor.java | dfef0c13a4e53fde9fa6db553a75b2347700d1fe | [] | no_license | JeffRisberg/Seq01 | https://github.com/JeffRisberg/Seq01 | da36b6776d081db966f8e81e80baca0f4356849f | aa17c4344c0b7d2dd57db4ce0b007f2bf016375b | refs/heads/master | 2020-03-26T07:21:21.470000 | 2018-09-27T19:59:18 | 2018-09-27T19:59:18 | 144,650,553 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.company.jobServer.executors;
import com.company.jobServer.beans.Job;
import com.company.jobServer.beans.JobExecution;
import lombok.extern.slf4j.Slf4j;
import org.json.simple.JSONObject;
@Slf4j
public class ConnectorJobExecutor extends BaseJobExecutor {
@Override
public JobExecution start(Job job, JobExecution parentExecution, JSONObject envVars) {
return super.start(job, parentExecution, envVars);
}
@Override
public void stop(JobExecution jobExecution, boolean force) {
super.stop(jobExecution, force);
}
@Override
public void destroy(JobExecution jobExecution) {
super.destroy(jobExecution);
}
}
| UTF-8 | Java | 649 | java | ConnectorJobExecutor.java | Java | [] | null | [] | package com.company.jobServer.executors;
import com.company.jobServer.beans.Job;
import com.company.jobServer.beans.JobExecution;
import lombok.extern.slf4j.Slf4j;
import org.json.simple.JSONObject;
@Slf4j
public class ConnectorJobExecutor extends BaseJobExecutor {
@Override
public JobExecution start(Job job, JobExecution parentExecution, JSONObject envVars) {
return super.start(job, parentExecution, envVars);
}
@Override
public void stop(JobExecution jobExecution, boolean force) {
super.stop(jobExecution, force);
}
@Override
public void destroy(JobExecution jobExecution) {
super.destroy(jobExecution);
}
}
| 649 | 0.776579 | 0.771957 | 25 | 24.959999 | 24.76042 | 88 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.56 | false | false | 2 |
850e0fce99f591f7853af75029fd828a3869d219 | 68,719,507,585 | 28b6ee54ee07a923e2f1739d0195f3f250578b69 | /feature/src/main/java/com/wlady/app/whereareyou/feature/services/MessagingService.java | 04ad327980e3389d4874758aa32e2e7bedc1fb73 | [] | no_license | instamaven/whereareyou-android | https://github.com/instamaven/whereareyou-android | d5f1fa3629122b1d825382b0ba96c001387b7b55 | c643dff0214aaa65bc60d7305792bfdab9263dee | refs/heads/master | 2020-04-16T03:32:16.948000 | 2019-01-27T11:36:50 | 2019-01-27T11:36:50 | 165,235,074 | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package com.wlady.app.whereareyou.feature.services;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.wlady.app.whereareyou.feature.App;
import com.wlady.app.whereareyou.feature.R;
import com.wlady.app.whereareyou.feature.activities.InviteActivity;
import com.wlady.app.whereareyou.feature.activities.MainActivity;
import com.wlady.app.whereareyou.feature.helpers.FirestoreHelper;
import com.wlady.app.whereareyou.feature.models.FCMPushNotification;
import java.util.Map;
public class MessagingService extends FirebaseMessagingService {
private FCMPushNotification.Data fromData;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
fromData = null;
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
handleMessage(remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
sendNotification(remoteMessage.getNotification());
} else if (fromData != null) {
Intent intent;
if (fromData.getType().equals(FCMPushNotification.PING_MESSAGE)) {
// somebody ask to post our location
intent = new Intent(this, PingService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent);
} else {
startService(intent);
}
}
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
private void handleMessage(Map<String, String> data) {
if (data.containsKey("type")) {
// our custom data message
fromData = new FCMPushNotification.Data();
String type = data.get("type");
if (type == null) {
type = "";
}
fromData.setType(Integer.parseInt(type));
fromData.setName(data.get("name"));
fromData.setAvatar(data.get("avatar"));
fromData.setUid(data.get("uId"));
fromData.setToken(data.get("token"));
}
}
@Override
public void onNewToken(String token) {
if (App.currentUser != null) {
FirestoreHelper.saveDevice(App.currentUser.getUid(), App.device);
}
}
/**
* Create and show a simple notification containing the received FCM message.
*
* @param message RemoteMessage.Notification
*/
private void sendNotification(RemoteMessage.Notification message) {
Intent intent;
if (fromData != null && fromData.getType().equals(FCMPushNotification.INVITE_MESSAGE)) {
intent = new Intent(this, InviteActivity.class);
intent.putExtra("from", fromData);
} else {
intent = new Intent(this, MainActivity.class);
intent.putExtra("reload", true);
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
String channelName = getString(R.string.background_notification_channel);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_binoculars)
.setContentTitle(message.getTitle())
.setContentText(message.getBody())
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
channelName,
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
| UTF-8 | Java | 5,007 | java | MessagingService.java | Java | [] | null | [] | package com.wlady.app.whereareyou.feature.services;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import com.wlady.app.whereareyou.feature.App;
import com.wlady.app.whereareyou.feature.R;
import com.wlady.app.whereareyou.feature.activities.InviteActivity;
import com.wlady.app.whereareyou.feature.activities.MainActivity;
import com.wlady.app.whereareyou.feature.helpers.FirestoreHelper;
import com.wlady.app.whereareyou.feature.models.FCMPushNotification;
import java.util.Map;
public class MessagingService extends FirebaseMessagingService {
private FCMPushNotification.Data fromData;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
fromData = null;
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
handleMessage(remoteMessage.getData());
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
sendNotification(remoteMessage.getNotification());
} else if (fromData != null) {
Intent intent;
if (fromData.getType().equals(FCMPushNotification.PING_MESSAGE)) {
// somebody ask to post our location
intent = new Intent(this, PingService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent);
} else {
startService(intent);
}
}
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
private void handleMessage(Map<String, String> data) {
if (data.containsKey("type")) {
// our custom data message
fromData = new FCMPushNotification.Data();
String type = data.get("type");
if (type == null) {
type = "";
}
fromData.setType(Integer.parseInt(type));
fromData.setName(data.get("name"));
fromData.setAvatar(data.get("avatar"));
fromData.setUid(data.get("uId"));
fromData.setToken(data.get("token"));
}
}
@Override
public void onNewToken(String token) {
if (App.currentUser != null) {
FirestoreHelper.saveDevice(App.currentUser.getUid(), App.device);
}
}
/**
* Create and show a simple notification containing the received FCM message.
*
* @param message RemoteMessage.Notification
*/
private void sendNotification(RemoteMessage.Notification message) {
Intent intent;
if (fromData != null && fromData.getType().equals(FCMPushNotification.INVITE_MESSAGE)) {
intent = new Intent(this, InviteActivity.class);
intent.putExtra("from", fromData);
} else {
intent = new Intent(this, MainActivity.class);
intent.putExtra("reload", true);
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String channelId = getString(R.string.default_notification_channel_id);
String channelName = getString(R.string.background_notification_channel);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_binoculars)
.setContentTitle(message.getTitle())
.setContentText(message.getBody())
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
channelName,
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
| 5,007 | 0.648292 | 0.647493 | 122 | 40.040985 | 27.288801 | 99 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 0.540984 | false | false | 2 |
0e40eeb4eb4e6c2ae3bb7e44444d18edbf3867f5 | 21,217,138,470,832 | 65a6655c10536db536bd01ab999683ed20bcf410 | /src/aRocktail/Main.java | 404aa47af5b7d6ce67420553dab354250dcaa91a | [] | no_license | LoveLeAnon/aRocktail | https://github.com/LoveLeAnon/aRocktail | b8cba528f8890e05736d2dec1a46681c169fda05 | 9063c291ee6121695efca4d781245bc20770c796 | refs/heads/master | 2018-01-05T02:49:07.424000 | 2015-03-25T21:40:20 | 2015-03-25T21:40:20 | null | 0 | 0 | null | null | null | null | null | null | null | null | null | null | null | null | null | package aRocktail;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.text.DecimalFormat;
import java.util.ArrayList;
import org.parabot.environment.api.interfaces.Paintable;
import org.parabot.environment.scripts.Category;
import org.parabot.environment.scripts.Script;
import org.parabot.environment.scripts.ScriptManifest;
import org.parabot.environment.scripts.framework.Strategy;
import org.rev317.min.api.methods.Inventory;
@ScriptManifest(author = "Atex", category = Category.FISHING, description = "Fishes rocktails in living rock caverns.", name = "aRocktail", servers = { "Ikov" }, version = 0.1)
public class Main extends Script implements Paintable {
public static long startTime = System.currentTimeMillis();
private final ArrayList<Strategy> strategies = new ArrayList<Strategy>();
public static String status = "Idle";
public static int startingCount = Inventory.getCount(true, Action.idLivingMinerals);
public static int count = 0;
@Override
public boolean onExecute() {
startTime = System.currentTimeMillis();
strategies.add(new Action());
provide(strategies);
return true;
}
@Override
public void onFinish() {
}
@Override
public void paint(Graphics iFace) {
if(Inventory.getCount(true, Action.idLivingMinerals) > 0) {
count = (startingCount - Inventory.getCount(true, Action.idLivingMinerals));
}
iFace.setColor(Color.white);
iFace.setFont(new Font("Verdana", Font.BOLD, 12));
iFace.drawString("aRocktail", 545, 350);
iFace.drawString(runTime(startTime), 545, 363);
iFace.drawString("Status: "+status, 545, 376);
iFace.drawString("Count: "+count, 545, 389);
}
public int amountPerHour() {
long currentTime = System.currentTimeMillis() - startTime;
int rate = 0;
rate = (startingCount - Inventory.getCount(true, Action.idLivingMinerals)) / ((int)(currentTime) / (3600000));
return rate;
}
public static String runTime(long start) {
DecimalFormat df = new DecimalFormat("00");
long currentTime = System.currentTimeMillis() - start;
long hours = currentTime / (3600000);
currentTime -= hours * (3600000);
long minutes = currentTime / (60000);
currentTime -= minutes * (60000);
long seconds = currentTime / (1000);
return df.format(hours) + ":" + df.format(minutes) + ":" + df.format(seconds);
}
}
| UTF-8 | Java | 2,341 | java | Main.java | Java | [
{
"context": "api.methods.Inventory;\n\n@ScriptManifest(author = \"Atex\", category = Category.FISHING, description = \"Fis",
"end": 495,
"score": 0.9806389808654785,
"start": 491,
"tag": "USERNAME",
"value": "Atex"
}
] | null | [] | package aRocktail;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.text.DecimalFormat;
import java.util.ArrayList;
import org.parabot.environment.api.interfaces.Paintable;
import org.parabot.environment.scripts.Category;
import org.parabot.environment.scripts.Script;
import org.parabot.environment.scripts.ScriptManifest;
import org.parabot.environment.scripts.framework.Strategy;
import org.rev317.min.api.methods.Inventory;
@ScriptManifest(author = "Atex", category = Category.FISHING, description = "Fishes rocktails in living rock caverns.", name = "aRocktail", servers = { "Ikov" }, version = 0.1)
public class Main extends Script implements Paintable {
public static long startTime = System.currentTimeMillis();
private final ArrayList<Strategy> strategies = new ArrayList<Strategy>();
public static String status = "Idle";
public static int startingCount = Inventory.getCount(true, Action.idLivingMinerals);
public static int count = 0;
@Override
public boolean onExecute() {
startTime = System.currentTimeMillis();
strategies.add(new Action());
provide(strategies);
return true;
}
@Override
public void onFinish() {
}
@Override
public void paint(Graphics iFace) {
if(Inventory.getCount(true, Action.idLivingMinerals) > 0) {
count = (startingCount - Inventory.getCount(true, Action.idLivingMinerals));
}
iFace.setColor(Color.white);
iFace.setFont(new Font("Verdana", Font.BOLD, 12));
iFace.drawString("aRocktail", 545, 350);
iFace.drawString(runTime(startTime), 545, 363);
iFace.drawString("Status: "+status, 545, 376);
iFace.drawString("Count: "+count, 545, 389);
}
public int amountPerHour() {
long currentTime = System.currentTimeMillis() - startTime;
int rate = 0;
rate = (startingCount - Inventory.getCount(true, Action.idLivingMinerals)) / ((int)(currentTime) / (3600000));
return rate;
}
public static String runTime(long start) {
DecimalFormat df = new DecimalFormat("00");
long currentTime = System.currentTimeMillis() - start;
long hours = currentTime / (3600000);
currentTime -= hours * (3600000);
long minutes = currentTime / (60000);
currentTime -= minutes * (60000);
long seconds = currentTime / (1000);
return df.format(hours) + ":" + df.format(minutes) + ":" + df.format(seconds);
}
}
| 2,341 | 0.730884 | 0.700555 | 65 | 35 | 30.375092 | 176 | false | false | 0 | 0 | 0 | 0 | 0 | 0 | 1.969231 | false | false | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.