blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2
values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 132
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 9.45M | extension stringclasses 28
values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 352 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c7dc9a162596f84a03d63ab3f6c386c3f797ae65 | 7242bb0476076b61f97feee82e436f02b5c17da1 | /src/main/java/ru/azerusteam/game/puzzlewars/world/VoidChunkLoader.java | 4d6754f3ac7a9e3f6095961d8bda18425b0dba14 | [] | no_license | Sirboys/MinestomGame | e4accf1b9adcd80f70ed6bdaf585655e85bdba22 | 813d0e5ac75d0d675bf7ffbde3ddbbce03bab27a | refs/heads/main | 2023-03-10T03:55:47.408267 | 2021-02-12T09:02:21 | 2021-02-12T09:02:21 | 326,808,943 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,108 | java | package ru.azerusteam.game.puzzlewars.world;
import net.minestom.server.MinecraftServer;
import net.minestom.server.instance.*;
import net.minestom.server.instance.batch.ChunkBatch;
import net.minestom.server.instance.block.Block;
import net.minestom.server.utils.chunk.ChunkCallback;
import net.minestom.server.world.biomes.Biome;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.List;
public class VoidChunkLoader implements ChunkGenerator {
@Override
public void generateChunkData(@NotNull ChunkBatch batch, int chunkX, int chunkZ) {
/*for (int x = 0; x < Chunk.CHUNK_SIZE_X; x++) {
for (int z = 0; z < Chunk.CHUNK_SIZE_Z; z++) {
//batch.setBlock(x, 0, z, Block.STONE);
}
}*/
}
@Override
public void fillBiomes(@NotNull Biome[] biomes, int chunkX, int chunkZ) {
Arrays.fill(biomes, MinecraftServer.getBiomeManager().getById(0));
}
@Override
public @Nullable List<ChunkPopulator> getPopulators() {
return null;
}
}
| [
"khannanovalmaz1@gmail.com"
] | khannanovalmaz1@gmail.com |
4a8aee0e825ba7ee8d48ed2dededa3a5cdba9b01 | ed367c82b654f3276075c12e9c0899903e46f84f | /Collectionneur/src/vue/Navigateur.java | 8a80685d3cb66ac2452800011aca848db511884f | [] | no_license | cegepmatane/devoir-collections-2020-thomas192 | f0e84819a0b688ddba0bec878f520fe53bd9f33c | a02a667e10f3b60d3e542e5ff35f43fa2be0db59 | refs/heads/master | 2022-12-29T08:10:55.509489 | 2020-09-17T11:33:48 | 2020-09-17T11:33:48 | 291,097,304 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 964 | java | package vue;
import com.sun.media.jfxmedia.logging.Logger;
import javafx.application.Application;
import javafx.stage.Stage;
// Classe qui regroupe toutes les vues et permet de changer de page
public abstract class Navigateur extends Application{ // Application de javafx est en réalité une fenêtre
protected Stage stade;
private static Navigateur instance = null;
public static Navigateur getInstance() {return instance;}
protected Navigateur()
{
instance = this;
Logger.setLevel(Logger.INFO);
VueChainesDeMontagnes.getInstance().activerControles();
VueChaineDeMontagne.getInstance().activerControles();
VueAjouterSommet.getInstance().activerControles();
VueModifierSommet.getInstance().activerControles();
VueModifierSommet.getInstance().controleur = VueAjouterSommet.getInstance().controleur = VueChaineDeMontagne.getInstance().controleur;
}
public void afficherVue(Vue vue)
{
stade.setScene(vue);
stade.show();
}
}
| [
"65908739+thomas192@users.noreply.github.com"
] | 65908739+thomas192@users.noreply.github.com |
91846b91810e8340b1197de3095d25722234a476 | 19ecfcf3ab91416b607af48b877d48acd373d17e | /HerbertSchildtBook/src/main/java/Chap03/NoBreak.java | d0b205a119f1078bed2e523a15f14a1c6981c42f | [] | no_license | GianlucaPal/JavaBeginner | 182fc966751b33db7fad5966f7b4a8efc83a0a68 | 1a6ecddfa805861ebdb07cf7c3c51d093eaa0b09 | refs/heads/master | 2023-08-20T21:09:01.263974 | 2021-10-18T09:34:08 | 2021-10-18T09:34:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 772 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Chap03;
/**
*
* @author Y520
*/
public class NoBreak {
public static void main(String args[]) {
int i;
for(i=0; i<=5; i++) {
switch(i) {
case 0:
System.out.println("i is less than one");
case 1:
System.out.println("i is less than two");
case 2:
System.out.println("i is less than three");
case 3:
System.out.println("i is less than four");
case 4:
System.out.println("i is less than five");
}
System.out.println();
}
}
}
| [
"gianlucapalmarozza@gmail.com"
] | gianlucapalmarozza@gmail.com |
9736bfae14a258f45cbee388d09d0e8ca03a6eac | a053dacd2f66dd2da5e199fc09fc2ee08c50c791 | /src/main/java/com/sun/corba/se/PortableActivationIDL/ServerHeldDownHolder.java | 6db8d2a19d7428ffe3ac2d07f0fd8f4a7cc6c652 | [] | no_license | franklions/JDK8SourceCode | 0ba9952fc7618a12af45ed060bbce9c0e6c69ded | c81a15212217a055dc2ed62524e5fc3a0df356c5 | refs/heads/master | 2020-04-19T03:08:58.698460 | 2019-02-20T01:04:48 | 2019-02-20T01:04:48 | 167,926,002 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 966 | java | package com.sun.corba.se.PortableActivationIDL;
/**
* com/sun/corba/se/PortableActivationIDL/ServerHeldDownHolder.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from /Users/java_re/workspace/8-2-build-macosx-x86_64/jdk8u201/12322/corba/src/share/classes/com/sun/corba/se/PortableActivationIDL/activation.idl
* Saturday, December 15, 2018 6:37:00 PM PST
*/
public final class ServerHeldDownHolder implements org.omg.CORBA.portable.Streamable
{
public ServerHeldDown value = null;
public ServerHeldDownHolder ()
{
}
public ServerHeldDownHolder (ServerHeldDown initialValue)
{
value = initialValue;
}
public void _read (org.omg.CORBA.portable.InputStream i)
{
value = ServerHeldDownHelper.read (i);
}
public void _write (org.omg.CORBA.portable.OutputStream o)
{
ServerHeldDownHelper.write (o, value);
}
public org.omg.CORBA.TypeCode _type ()
{
return ServerHeldDownHelper.type ();
}
}
| [
"franklions@sina.com"
] | franklions@sina.com |
de83e4fc63f0491b574b80bc75ae7d46b83f08e2 | 473b76b1043df2f09214f8c335d4359d3a8151e0 | /benchmark/bigclonebenchdata_completed/22930145.java | bf781059e4d190d7192759b471afcfd6ff31bcd5 | [] | no_license | whatafree/JCoffee | 08dc47f79f8369af32e755de01c52d9a8479d44c | fa7194635a5bd48259d325e5b0a190780a53c55f | refs/heads/master | 2022-11-16T01:58:04.254688 | 2020-07-13T20:11:17 | 2020-07-13T20:11:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 992 | java |
import java.io.UncheckedIOException;
class c22930145 {
public MyHelperClass url;
private long getLastModification() {
try {
MyHelperClass connection = new MyHelperClass();
if (connection == null) connection = url.openConnection();
// MyHelperClass connection = new MyHelperClass();
return(long)(Object) connection.getLastModified();
} catch (UncheckedIOException e) {
MyHelperClass LOG = new MyHelperClass();
LOG.warn("URL could not be opened: " + e.getMessage(),(IOException)(Object) e);
return 0;
}
}
}
// Code below this line has been added to remove errors
class MyHelperClass {
public MyHelperClass getLastModified(){ return null; }
public MyHelperClass openConnection(){ return null; }
public MyHelperClass warn(String o0, IOException o1){ return null; }}
class IOException extends Exception{
public IOException(String errorMessage) { super(errorMessage); }
}
| [
"piyush16066@iiitd.ac.in"
] | piyush16066@iiitd.ac.in |
7f6bd74f2988e0cd3470c0ef9b3ce5f245be0967 | c910666fad3dd07db4be24f0597c23e8b085ec48 | /src/main/java/com/example/edulearnsm/model/VerificationToken.java | aa67e8655cf97c1d80f30ebcfbe68f26e8a43ed0 | [] | no_license | alexmanoliu/AngularSpringBOOT-full-app | c11b7c26a63d5b12d90064682e21826ec0c3569f | a114c6481a0a9c7ef9eaa709635ec91513785947 | refs/heads/master | 2023-04-19T04:34:59.157483 | 2021-05-08T10:19:07 | 2021-05-08T10:19:07 | 365,483,166 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 579 | java | package com.example.edulearnsm.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.Instant;
import static javax.persistence.FetchType.LAZY;
import static javax.persistence.GenerationType.IDENTITY;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "token")
public class VerificationToken {
@Id
@GeneratedValue(strategy = IDENTITY)
private Long id;
private String token;
@OneToOne(fetch = LAZY)
private User user;
private Instant expiryDate;
}
| [
"alexandru.manoliu@gmail.com"
] | alexandru.manoliu@gmail.com |
b67444751380f8027b026685c942d84d0e233e3f | 0eee87a67c48a168a36d45b260f8cb0780800ec2 | /back_stage/springMvc_springSecurity_myBatis/src/com/lanyuan/service/UserService.java | a40f18f835d86d36204b4ef657b867d227339b2a | [] | no_license | damonli0724/SVN2 | 8feafb45ef9e6806e9c552071f11d45e4c582aae | 4344a8d6537da1690f01fc3498cd55fb27511698 | refs/heads/master | 2018-10-22T20:14:23.389690 | 2018-07-21T07:18:52 | 2018-07-21T07:18:52 | 104,313,813 | 1 | 2 | null | null | null | null | UTF-8 | Java | false | false | 532 | java | package com.lanyuan.service;
import com.lanyuan.entity.Roles;
import com.lanyuan.entity.User;
import com.lanyuan.util.PageView;
public interface UserService{
public PageView query(PageView pageView,User user);
public void add(User user);
public void delete(String id);
public void modify(User user);
public User getById(String id);
public int countUser(String userName,String userPassword);
public User querySingleUser(String userName);
public Roles findbyUserRole(String userId);
}
| [
"lkd@f89b1fc9-7c5e-455b-8322-85e5e281e6e7"
] | lkd@f89b1fc9-7c5e-455b-8322-85e5e281e6e7 |
ede3bfc84105a1706fa4c93ba39c9a1128a7ebbc | a7ad95e023f7a9f945f99ad3de6f547a113585d0 | /querydsl-jpa/src/main/java/com/mysema/query/jpa/hibernate/HibernateDomainExporter.java | 3d50dcf9cd5ca19371772ac9b798307fb06751e7 | [] | no_license | h2000/querydsl | 37532ae92ec126d92c55f127a76bb7dbeff2c049 | a2960cf446a863cffc0b70e544a935d1e97f3b5a | refs/heads/master | 2021-01-18T12:47:43.514818 | 2012-02-23T19:46:05 | 2012-02-23T19:46:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 14,529 | java | /*
* Copyright 2011, Mysema Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mysema.query.jpa.hibernate;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
import javax.xml.stream.XMLStreamException;
import org.hibernate.cfg.Configuration;
import org.hibernate.mapping.Component;
import org.hibernate.mapping.MappedSuperclass;
import org.hibernate.mapping.PersistentClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mysema.codegen.CodeWriter;
import com.mysema.codegen.JavaWriter;
import com.mysema.codegen.model.ClassType;
import com.mysema.codegen.model.Type;
import com.mysema.codegen.model.TypeCategory;
import com.mysema.query.QueryException;
import com.mysema.query.annotations.PropertyType;
import com.mysema.query.annotations.QueryInit;
import com.mysema.query.annotations.QueryType;
import com.mysema.query.codegen.*;
import com.mysema.util.BeanUtils;
/**
* @author tiwe
*
*/
public class HibernateDomainExporter {
private static final Logger logger = LoggerFactory.getLogger(HibernateDomainExporter.class);
private final File targetFolder;
private final Map<String,EntityType> allTypes = new HashMap<String,EntityType>();
private final Map<String,EntityType> entityTypes = new HashMap<String,EntityType>();
private final Map<String,EntityType> embeddableTypes = new HashMap<String,EntityType>();
private final Map<String,EntityType> superTypes = new HashMap<String,EntityType>();
private final Set<EntityType> serialized = new HashSet<EntityType>();
private final TypeFactory typeFactory = new TypeFactory();
private final Configuration configuration;
private final QueryTypeFactory queryTypeFactory;
private final TypeMappings typeMappings;
private final Serializer embeddableSerializer;
private final Serializer entitySerializer;
private final Serializer supertypeSerializer;
private final SerializerConfig serializerConfig;
public HibernateDomainExporter(File targetFolder, Configuration configuration) {
this("Q", "", targetFolder, SimpleSerializerConfig.DEFAULT, configuration);
}
public HibernateDomainExporter(String namePrefix, File targetFolder, Configuration configuration) {
this(namePrefix, "", targetFolder, SimpleSerializerConfig.DEFAULT, configuration);
}
public HibernateDomainExporter(String namePrefix, String nameSuffix, File targetFolder,
Configuration configuration) {
this(namePrefix, nameSuffix, targetFolder, SimpleSerializerConfig.DEFAULT, configuration);
}
public HibernateDomainExporter(String namePrefix, File targetFolder,
SerializerConfig serializerConfig, Configuration configuration) {
this(namePrefix, "", targetFolder, serializerConfig, configuration);
}
public HibernateDomainExporter(String namePrefix, String nameSuffix, File targetFolder,
SerializerConfig serializerConfig, Configuration configuration) {
this.targetFolder = targetFolder;
this.serializerConfig = serializerConfig;
this.configuration = configuration;
configuration.buildMappings();
CodegenModule module = new CodegenModule();
module.bind(CodegenModule.PREFIX, namePrefix);
module.bind(CodegenModule.SUFFIX, nameSuffix);
module.bind(CodegenModule.KEYWORDS, Constants.keywords);
this.queryTypeFactory = module.get(QueryTypeFactory.class);
this.typeMappings = module.get(TypeMappings.class);
this.embeddableSerializer = module.get(EmbeddableSerializer.class);
this.entitySerializer = module.get(EntitySerializer.class);
this.supertypeSerializer = module.get(SupertypeSerializer.class);
typeFactory.setUnknownAsEntity(true);
}
public void execute() throws IOException {
// collect types
try {
collectTypes();
} catch (SecurityException e) {
throw new QueryException(e);
} catch (XMLStreamException e) {
throw new QueryException(e);
} catch (ClassNotFoundException e) {
throw new QueryException(e);
} catch (NoSuchMethodException e) {
throw new QueryException(e);
}
// merge supertype fields into subtypes
Set<EntityType> handled = new HashSet<EntityType>();
for (EntityType type : superTypes.values()) {
addSupertypeFields(type, allTypes, handled);
}
for (EntityType type : entityTypes.values()) {
addSupertypeFields(type, allTypes, handled);
}
for (EntityType type : embeddableTypes.values()) {
addSupertypeFields(type, allTypes, handled);
}
// serialize them
serialize(superTypes, supertypeSerializer);
serialize(embeddableTypes, embeddableSerializer);
serialize(entityTypes, entitySerializer);
}
private void addSupertypeFields(EntityType model, Map<String, EntityType> superTypes,
Set<EntityType> handled) {
if (handled.add(model)) {
for (Supertype supertype : model.getSuperTypes()) {
EntityType entityType = superTypes.get(supertype.getType().getFullName());
if (entityType != null) {
addSupertypeFields(entityType, superTypes, handled);
supertype.setEntityType(entityType);
model.include(supertype);
}
}
}
}
private void collectTypes() throws IOException, XMLStreamException, ClassNotFoundException,
SecurityException, NoSuchMethodException {
// super classes
Iterator<?> superClassMappings = configuration.getMappedSuperclassMappings();
while (superClassMappings.hasNext()) {
MappedSuperclass msc = (MappedSuperclass)superClassMappings.next();
EntityType entityType = createSuperType(msc.getMappedClass());
if (msc.getDeclaredIdentifierProperty() != null) {
handleProperty(entityType, msc.getMappedClass(), msc.getDeclaredIdentifierProperty());
}
Iterator<?> properties = msc.getDeclaredPropertyIterator();
while (properties.hasNext()) {
handleProperty(entityType, msc.getMappedClass(), (org.hibernate.mapping.Property) properties.next());
}
}
// entity classes
Iterator<?> classMappings = configuration.getClassMappings();
while (classMappings.hasNext()) {
PersistentClass pc = (PersistentClass)classMappings.next();
EntityType entityType = createEntityType(pc.getMappedClass());
if (pc.getDeclaredIdentifierProperty() != null) {
handleProperty(entityType, pc.getMappedClass(), pc.getDeclaredIdentifierProperty());
}else if (!pc.isInherited() && pc.hasIdentifierProperty()) {
logger.info(entityType.toString() + pc.getIdentifierProperty());
handleProperty(entityType, pc.getMappedClass(), pc.getIdentifierProperty());
}
Iterator<?> properties = pc.getDeclaredPropertyIterator();
while (properties.hasNext()) {
handleProperty(entityType, pc.getMappedClass(), (org.hibernate.mapping.Property) properties.next());
}
}
}
private void handleProperty(EntityType entityType, Class<?> cl, org.hibernate.mapping.Property p)
throws NoSuchMethodException, ClassNotFoundException {
Type propertyType = getType(cl, p.getName());
if (p.isComposite()) {
Class<?> embeddedClass = Class.forName(propertyType.getFullName());
EntityType embeddedType = createEmbeddableType(embeddedClass);
Iterator<?> properties = ((Component)p.getValue()).getPropertyIterator();
while (properties.hasNext()) {
handleProperty(embeddedType, embeddedClass, (org.hibernate.mapping.Property)properties.next());
}
propertyType = embeddedType;
}else if (propertyType.getCategory() == TypeCategory.ENTITY) {
propertyType = createEntityType(Class.forName(propertyType.getFullName()));
}
AnnotatedElement annotated = getAnnotatedElement(cl, p.getName());
Property property = createProperty(entityType, p.getName(), propertyType, annotated);
entityType.addProperty(property);
}
@Nullable
private Property createProperty(EntityType entityType, String propertyName, Type propertyType,
AnnotatedElement annotated) {
String[] inits = new String[0];
if (annotated.isAnnotationPresent(QueryInit.class)) {
inits = annotated.getAnnotation(QueryInit.class).value();
}
if (annotated.isAnnotationPresent(QueryType.class)) {
QueryType queryType = annotated.getAnnotation(QueryType.class);
if (queryType.value().equals(PropertyType.NONE)) {
return null;
}
propertyType = propertyType.as(queryType.value().getCategory());
}
return new Property(entityType, propertyName, propertyType, inits);
}
private EntityType createEntityType(Class<?> cl) {
return createEntityType(cl, entityTypes);
}
private EntityType createEmbeddableType(Class<?> cl) {
return createEntityType(cl, embeddableTypes);
}
private EntityType createEntityType(Class<?> cl, Map<String,EntityType> types) {
if (types.containsKey(cl.getName())) {
return types.get(cl.getName());
} else {
EntityType type = new EntityType(new ClassType(TypeCategory.ENTITY, cl));
typeMappings.register(type, queryTypeFactory.create(type));
if (!cl.getSuperclass().equals(Object.class)) {
type.addSupertype(new Supertype(new ClassType(cl.getSuperclass())));
}
types.put(cl.getName(), type);
allTypes.put(cl.getName(), type);
return type;
}
}
private EntityType createSuperType(Class<?> cl) {
return createEntityType(cl, superTypes);
}
private Type getType(Class<?> cl, String propertyName) throws NoSuchMethodException {
try {
Field field = cl.getDeclaredField(propertyName);
return typeFactory.create(field.getType(), field.getGenericType());
} catch (NoSuchFieldException e) {
String getter = "get"+BeanUtils.capitalize(propertyName);
String bgetter = "is"+BeanUtils.capitalize(propertyName);
for (Method method : cl.getDeclaredMethods()) {
if ((method.getName().equals(getter) || method.getName().equals(bgetter))
&& method.getParameterTypes().length == 0) {
return typeFactory.create(method.getReturnType(), method.getGenericReturnType());
}
}
if (cl.getSuperclass().equals(Object.class)) {
throw new IllegalArgumentException("No property found for " + cl.getName() + "." + propertyName);
} else {
return getType(cl.getSuperclass(), propertyName);
}
}
}
private AnnotatedElement getAnnotatedElement(Class<?> cl, String propertyName) throws NoSuchMethodException {
try {
return cl.getDeclaredField(propertyName);
} catch (NoSuchFieldException e) {
String getter = "get"+BeanUtils.capitalize(propertyName);
String bgetter = "is"+BeanUtils.capitalize(propertyName);
for (Method method : cl.getDeclaredMethods()) {
if ((method.getName().equals(getter) || method.getName().equals(bgetter))
&& method.getParameterTypes().length == 0) {
return method;
}
}
if (cl.getSuperclass().equals(Object.class)) {
throw new IllegalArgumentException("No property found for " + cl.getName() + "." + propertyName);
} else {
return getAnnotatedElement(cl.getSuperclass(), propertyName);
}
}
}
private void serialize(Map<String,EntityType> types, Serializer serializer) throws IOException {
for (EntityType entityType : types.values()) {
if (serialized.add(entityType)) {
Type type = typeMappings.getPathType(entityType, entityType, true);
String packageName = type.getPackageName();
String className = packageName.length() > 0 ? (packageName + "." + type.getSimpleName()) : type.getSimpleName();
write(serializer, className.replace('.', '/') + ".java", entityType);
}
}
}
private void write(Serializer serializer, String path, EntityType type) throws IOException {
File targetFile = new File(targetFolder, path);
Writer w = writerFor(targetFile);
try{
CodeWriter writer = new JavaWriter(w);
serializer.serialize(type, serializerConfig, writer);
}finally{
w.close();
}
}
private Writer writerFor(File file) {
if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
logger.error("Folder " + file.getParent() + " could not be created");
}
try {
return new OutputStreamWriter(new FileOutputStream(file));
} catch (FileNotFoundException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
}
| [
"timo.westkamper@mysema.com"
] | timo.westkamper@mysema.com |
7494c54cdd8874426813220fbc4aad340ff571a2 | b55343312f12b6673dfbc53829a6ba0431275b50 | /src/main/java/com/cwoongc/kafka/kafkacommittest/producer/ProducerGeneratedTxWithdrawalCreated.java | db96d4821cba125bd8817bd6a10f3a738b0c8bab | [] | no_license | cwoongc/kafka-test | 61414b1d8a86cddce4f548d2080a968426b38e9d | 084a88ba3f660bee663bd892c231716a1efb6461 | refs/heads/master | 2020-08-05T21:13:21.595567 | 2019-12-19T05:01:02 | 2019-12-19T05:01:02 | 212,713,046 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,209 | java | package com.cwoongc.kafka.kafkacommittest.producer;
import com.cwoongc.kafka.kafkacommittest.message.DeployAccountCreated;
import com.cwoongc.kafka.kafkacommittest.message.WithdrawalCreated;
import com.cwoongc.kafka.kafkacommittest.util.TimeUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.afterburner.AfterburnerModule;
import com.sun.tools.javac.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.header.Headers;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Properties;
@Slf4j
public class ProducerGeneratedTxWithdrawalCreated {
private static final ObjectMapper objectMapper;
static {
objectMapper = new ObjectMapper();
objectMapper.registerModule(new AfterburnerModule());
}
private final Properties secureProducerConfig;
public ProducerGeneratedTxWithdrawalCreated(Properties secureProducerConfig) {
this.secureProducerConfig = secureProducerConfig;
}
public void start(String topic) throws JsonProcessingException {
Producer<String, String> kafkaProducer = new KafkaProducer<>(secureProducerConfig);
long currentEpochTime = TimeUtils.getCurrentEpochTime();
WithdrawalCreated withdrawalCreated = WithdrawalCreated.builder()
.statusCode("0000")
.requestId("2000444888589")
.coinCode("ETH")
.transferAmount(new BigDecimal("12.345"))
.from(List.of(
WithdrawalCreated.Withdrawal.builder()
.organizationId("orgO")
.walletId("walletW")
.address("addrA")
.amount(new BigDecimal("12.345"))
.index(0)
.build()
))
.to(List.of(
WithdrawalCreated.Deposit.builder()
.address("addrD")
.amount(new BigDecimal("12.345"))
.index(0)
.tag("")
.build()
))
.fee(WithdrawalCreated.Fee.builder()
.organizationId("orgO")
.walletId("walletW")
.address("addrF")
.estimatedAmount(new BigDecimal("3.456"))
.coinCode("ETH")
.build()
).build();
// DeployAccountCreated deployAccountCreated = DeployAccountCreated.builder()
// .statusCode("0000")
// .requestId(Long.toString(currentEpochTime))
// .coinCode("LN")
// .organizationId("orgA")
// .walletId("walletA")
// .build();
ProducerRecord<String, String> producerRecord = new ProducerRecord<String,String>(
topic
,0
,null
, objectMapper.writeValueAsString(withdrawalCreated)
);
Headers headers = producerRecord.headers();
headers.add("eliKafkaHeader", "{\"transactionType\":\"WITHDRAWAL\",\"transactionStatus\":\"CREATED\"}".getBytes());
try {
kafkaProducer.send(producerRecord, (metadata, exception) -> {
if (metadata != null) {
log.info("[P] Topic: {}, Partition: {}, offset: {}",
metadata.topic(),
metadata.partition(),
metadata.offset()
);
} else {
log.error(exception.getMessage(), exception);
}
});
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
kafkaProducer.close();
}
}
} | [
"woongchul.choi@linecorp.com"
] | woongchul.choi@linecorp.com |
ba6b3fc6b16fb6dd513706af5003bc084d144939 | 31f609157ae46137cf96ce49e217ce7ae0008b1e | /bin/ext-commerce/commercefacades/testsrc/de/hybris/platform/commercefacades/product/converters/populator/ProductPromotionsPopulatorTest.java | 248074fc9a3c7166cb88492d6b231d45525236ad | [] | no_license | natakolesnikova/hybrisCustomization | 91d56e964f96373781f91f4e2e7ca417297e1aad | b6f18503d406b65924c21eb6a414eb70d16d878c | refs/heads/master | 2020-05-23T07:16:39.311703 | 2019-05-15T15:08:38 | 2019-05-15T15:08:38 | 186,672,599 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,882 | java | /*
* [y] hybris Platform
*
* Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* ("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 SAP.
*/
package de.hybris.platform.commercefacades.product.converters.populator;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.basecommerce.model.site.BaseSiteModel;
import de.hybris.platform.commercefacades.product.data.ProductData;
import de.hybris.platform.commercefacades.product.data.PromotionData;
import de.hybris.platform.core.model.product.ProductModel;
import de.hybris.platform.promotions.PromotionsService;
import de.hybris.platform.promotions.model.AbstractPromotionModel;
import de.hybris.platform.promotions.model.PromotionGroupModel;
import de.hybris.platform.servicelayer.dto.converter.Converter;
import de.hybris.platform.servicelayer.model.ModelService;
import de.hybris.platform.servicelayer.time.TimeService;
import de.hybris.platform.site.BaseSiteService;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.time.DateUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
/**
* Test suite for {@link ProductPromotionsPopulator}
*/
@UnitTest
public class ProductPromotionsPopulatorTest
{
@Mock
private PromotionsService promotionsService;
@Mock
private Converter<AbstractPromotionModel, PromotionData> promotionsConverter;
@Mock
private TimeService timeService;
@Mock
private ModelService modelService;
@Mock
private BaseSiteService baseSiteService;
private ProductPromotionsPopulator productPromotionsPopulator;
@Before
public void setUp()
{
MockitoAnnotations.initMocks(this);
productPromotionsPopulator = new ProductPromotionsPopulator();
productPromotionsPopulator.setModelService(modelService);
productPromotionsPopulator.setTimeService(timeService);
productPromotionsPopulator.setPromotionsConverter(promotionsConverter);
productPromotionsPopulator.setPromotionsService(promotionsService);
productPromotionsPopulator.setBaseSiteService(baseSiteService);
}
@Test
public void testPopulate()
{
final ProductModel source = mock(ProductModel.class);
final PromotionGroupModel defaultPromotionGroup = mock(PromotionGroupModel.class);
final Date currentDate = DateUtils.round(new Date(), Calendar.MINUTE);
final AbstractPromotionModel abstractPromotionModel = mock(AbstractPromotionModel.class);
final PromotionData promotionData = mock(PromotionData.class);
final BaseSiteModel baseSiteModel = mock(BaseSiteModel.class);
given(timeService.getCurrentTime()).willReturn(currentDate);
given(baseSiteService.getCurrentBaseSite()).willReturn(baseSiteModel);
given(baseSiteModel.getDefaultPromotionGroup()).willReturn(defaultPromotionGroup);
Mockito
.<List<? extends AbstractPromotionModel>> when(promotionsService
.getAbstractProductPromotions(Collections.singletonList(defaultPromotionGroup), source, true, currentDate))
.thenReturn(Collections.singletonList(abstractPromotionModel));
given(promotionsConverter.convertAll(Collections.singletonList(abstractPromotionModel)))
.willReturn(Collections.singletonList(promotionData));
final ProductData result = new ProductData();
productPromotionsPopulator.populate(source, result);
Assert.assertEquals(1, result.getPotentialPromotions().size());
Assert.assertEquals(promotionData, result.getPotentialPromotions().iterator().next());
}
}
| [
"nataliia@spadoom.com"
] | nataliia@spadoom.com |
7b2d543f03ef5e1b3e697616530da5a0b3d01d4e | 474623446c654fece6d864fbbc9892c15b052103 | /src/com/mvc/theam/service/ImageProcess.java | 9063c1711bc5809840d97ced3f573e7d10bcd0d2 | [] | no_license | ronuS6470/MVC_Theme | 9f2c8e442047284c4aba7e09ce607340f0aeb3ab | 824b1ee8c1f1e1fa0743e74c9c33e237335c3387 | refs/heads/master | 2020-03-22T07:16:57.185833 | 2018-07-04T08:18:51 | 2018-07-04T08:18:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,180 | java | package com.mvc.theam.service;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import org.apache.commons.fileupload.FileItem;
public class ImageProcess {
private static final int IMG_WIDTH = 600;
private static final int IMG_HEIGHT = 300;
public static boolean processfile(FileItem item, String imgName, String path) {
try {
String name = new File(item.getName()).getName();
File f = new File(path + File.separator + name);
item.write(f);
// this code will help you to resize and rename your image....
File resizefile = new File(path + File.separator + imgName);
BufferedImage originalImage = ImageIO.read(f);
int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
BufferedImage resizeImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
Graphics2D g = resizeImage.createGraphics();
g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
g.dispose();
ImageIO.write(resizeImage, "jpg", resizefile);
f.delete();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
| [
"ronakspatel1234@gmail.com"
] | ronakspatel1234@gmail.com |
aa5b8eb94e9f5447b11343d3c476471d74f55331 | 340f8061b6f330c0824a14f2b01eb48f8dd0ed4a | /MobileApplicationManagement/app/src/main/java/vn/fintechviet/mobileplatforms/application/management/utils/AndroidAgentException.java | 5283be9d0f783177389549ef3858ca500907fdc4 | [] | no_license | longtran84/mobileplatforms | 34c2c5cfd6e4ce14fb069fe1afcb11aa24cf8de9 | 4192f7a747c3edc7a258c500cf26ebce69d43d99 | refs/heads/master | 2021-09-24T01:52:44.539340 | 2018-07-05T10:29:17 | 2018-07-05T10:29:17 | 151,090,093 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,226 | java | /*
* Copyright (C) 2018 - 2019 FINTECHVIET
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://mindorks.com/license/apache-v2
*
* 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 vn.fintechviet.mobileplatforms.application.management.utils;
/**
* Custom exception class for IDP plug-in related exceptions.
*/
public class AndroidAgentException extends Exception {
private static final long serialVersionUID = 1L;
public AndroidAgentException(String msg, Exception nestedEx) {
super(msg, nestedEx);
}
public AndroidAgentException(String message, Throwable cause) {
super(message, cause);
}
public AndroidAgentException(String msg) {
super(msg);
}
public AndroidAgentException() {
super();
}
public AndroidAgentException(Throwable cause) {
super(cause);
}
}
| [
"tqlong.net@gmail.com"
] | tqlong.net@gmail.com |
73cadf0eb881b5f7ba0a13cda443a077717ba59e | c9e51564babf7de532fb65886b7ac435a4c03446 | /src/main/java/com/gestankbratwurst/ferocore/modules/racemodule/RecipeViewGUI.java | 497d3433057d4f5d1a1d28933c9a187cfc1cdad7 | [] | no_license | Projekt-Sidusgames/FeroCore | 0a1ab30440f55b11019a955bbfd85d9372f4aa26 | ed291a741cf04dd6a9f30e39f2f810057230aee8 | refs/heads/master | 2023-03-10T01:06:59.819138 | 2021-02-27T09:27:37 | 2021-02-27T09:27:37 | 340,214,490 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,294 | java | package com.gestankbratwurst.ferocore.modules.racemodule;
import com.gestankbratwurst.ferocore.modules.customrecipes.CustomShapedRecipe;
import com.gestankbratwurst.ferocore.resourcepack.skins.Model;
import com.gestankbratwurst.ferocore.util.common.UtilPlayer;
import com.gestankbratwurst.ferocore.util.items.ItemBuilder;
import lombok.RequiredArgsConstructor;
import net.crytec.inventoryapi.SmartInventory;
import net.crytec.inventoryapi.api.ClickableItem;
import net.crytec.inventoryapi.api.InventoryContent;
import net.crytec.inventoryapi.api.InventoryProvider;
import net.crytec.inventoryapi.api.SlotPos;
import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
/*******************************************************
* Copyright (C) Gestankbratwurst suotokka@gmail.com
*
* This file is part of FeroCore and was created at the 22.02.2021
*
* FeroCore can not be copied and/or distributed without the express
* permission of the owner.
*
*/
@RequiredArgsConstructor
public class RecipeViewGUI implements InventoryProvider {
public static void open(final Player player, final CustomShapedRecipe recipe) {
SmartInventory.builder().title("Rezept Ansicht").size(5).provider(new RecipeViewGUI(recipe)).build().open(player);
}
private final CustomShapedRecipe recipe;
@Override
public void init(final Player player, final InventoryContent content) {
final ItemStack[] matrix = this.recipe.getCraftingMatrix();
for (int x = 0; x < 3; x++) {
for (int y = 0; y < 3; y++) {
content.set(SlotPos.of(y + 1, x + 2), ClickableItem.empty(matrix[x + y * 3]));
}
}
content.set(SlotPos.of(2, 6), ClickableItem.empty(this.recipe.getHandle().getResult()));
content.set(SlotPos.of(4, 0), this.getBackIcon());
content.set(SlotPos.of(4, 4), ClickableItem.empty(new ItemBuilder(Model.RECIPE_VIEW_UI.getItem()).name(" ").build()));
}
private ClickableItem getBackIcon() {
final ItemStack icon = new ItemBuilder(Model.DOUBLE_GRAY_ARROW_LEFT.getItem()).name("§eZurück").build();
return ClickableItem.of(icon, event -> {
final Player player = (Player) event.getWhoClicked();
UtilPlayer.playSound(player, Sound.UI_BUTTON_CLICK);
RecipeSelectionGUI.open(player);
});
}
} | [
"unconfigured@null.spigotmc.org"
] | unconfigured@null.spigotmc.org |
f067d8411bd1553ffdeb88efaeff62b271983731 | ac03154cab749511238487861c23ccb86414e450 | /src/java/org/foi/nwtis/vlspoljar/rest/serveri/KorisniciRESTResourceContainer.java | 364029cd1bc1282ee6b956955a27d6e1867546f9 | [] | no_license | vlspoljar/vlspoljar_aplikacija_2_2 | 99a6b6e1f0afccddbf8e2d93ad97ed826b99f132 | 5ed18c67200f40e289bcb65a6fc611ded8342ca2 | refs/heads/master | 2021-01-01T05:30:56.073285 | 2015-03-30T13:40:49 | 2015-03-30T13:40:49 | 33,125,307 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,089 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.foi.nwtis.vlspoljar.rest.serveri;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.POST;
import javax.ws.rs.PathParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.foi.nwtis.vlspoljar.ejb.eb.Korisnici;
import org.foi.nwtis.vlspoljar.ejb.sb.KorisniciFacade;
import org.foi.nwtis.vlspoljar.web.slusaci.SlusacSesije;
import org.primefaces.json.JSONArray;
import org.primefaces.json.JSONException;
import org.primefaces.json.JSONObject;
/**
* REST Web Service
*
* @author Branko
*/
@Path("/korisniciREST")
public class KorisniciRESTResourceContainer {
KorisniciFacade korisniciFacade = lookupKorisniciFacadeBean();
@Context
private UriInfo context;
/**
* Creates a new instance of KorisniciRESTResourceContainer
*/
public KorisniciRESTResourceContainer() {
}
/**
* Retrieves representation of an instance of org.foi.nwtis.vlspoljar.rest.serveri.KorisniciRESTResourceContainer
* @return an instance of java.lang.String
*/
@GET
@Produces("application/json;charset=utf-8")
public String getJson() {
JSONObject rezultat = new JSONObject();
try {
JSONArray korisnici = new JSONArray();
int i = 0;
for (Korisnici k : SlusacSesije.listaKorisnika) {
JSONObject jo = new JSONObject();
jo.put("id", k.getIdkorisnici());
jo.put("kor_ime", k.getKorIme());
jo.put("ime", k.getIme());
jo.put("prezime", k.getPrezime());
jo.put("lozinka", k.getLozinka());
jo.put("email", k.getEmailAdresa());
jo.put("vrsta", k.getVrsta());
korisnici.put(i, jo);
i++;
}
rezultat.put("korisnici", korisnici);
return rezultat.toString();
} catch (JSONException ex) {
Logger.getLogger(KorisniciRESTResourceContainer.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* POST method for creating an instance of KorisniciRESTResource
* @param content representation for the new resource
* @return an HTTP response with content of the created resource
*/
@POST
@Consumes("application/json")
@Produces("application/json")
public Response postJson(String content) {
//TODO
return Response.created(context.getAbsolutePath()).build();
}
/**
* Sub-resource locator method for {id}
*/
@Path("{korisnik}")
public PortfeljRESTResource getPortfeljRESTResource(@PathParam("korisnik") String korisnik) {
return PortfeljRESTResource.getInstance(korisnik);
}
@Path("{korisnik}/{portfelj}")
public AdreseRESTResource getAdreseRESTResource(@PathParam("korisnik") String korisnik, @PathParam("portfelj") String portfelj) {
return AdreseRESTResource.getInstance(korisnik, portfelj);
}
private KorisniciFacade lookupKorisniciFacadeBean() {
try {
javax.naming.Context c = new InitialContext();
return (KorisniciFacade) c.lookup("java:global/vlspoljar_aplikacija_2/vlspoljar_aplikacija_2_1/KorisniciFacade!org.foi.nwtis.vlspoljar.ejb.sb.KorisniciFacade");
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}
}
| [
"vlatko.spoljaric29@gmail.com"
] | vlatko.spoljaric29@gmail.com |
717b10bf31298601c5d0298e33f6093f3ec7710a | d99bf90affb4199a2b3a185d691e53a9bc5d8d81 | /.svn/pristine/71/717b10bf31298601c5d0298e33f6093f3ec7710a.svn-base | 28e298a0fb267cb0ad5ea3b44da754a52bea6b37 | [] | no_license | weisong3/Dochoo | 5b8b381febeedc7de1f672b52272701cced980dc | 25350dd9019c822f104798276f5c8349f3433673 | refs/heads/master | 2021-01-10T19:01:40.179787 | 2014-12-23T02:27:51 | 2014-12-23T02:27:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,617 | package com.chc.found.models;
import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import com.chc.found.network.NetworkRequestsUtil;
import com.j256.ormlite.field.DatabaseField;
public abstract class EntityUser {
private static final String TYPE_MEDICAL_CENTER = "MEDICALGROUP";
private static final String TYPE_DOCTOR = "PHYSICIAN";
private static final String TYPE_PATIENT = "PATIENT";
public static final String COLUMN_NAME_ID = "id";
@DatabaseField(id = true)
private String id;
@DatabaseField
private String fullname;
@DatabaseField
private String description;
@DatabaseField
private String profileIconUrl;
@DatabaseField
private String workingHours;
@DatabaseField
private String acceptedInsurances;
@DatabaseField
private int numUnread;
@DatabaseField
private long lastMsgTime;
@DatabaseField
private String pin;
@DatabaseField
private String username;
@DatabaseField
private String loginEmail;
//for pinyin index
@DatabaseField
private String pinyinName;
public EntityUser() {
super();
}
public EntityUser(JSONObject jsonObject) throws JSONException {
this.id = jsonObject.optString("id");
this.profileIconUrl = NetworkRequestsUtil.getIconImageUrlString(getId());
this.workingHours = jsonObject.optString("officeHours");
this.acceptedInsurances = jsonObject.optString("acceptedInsurances");
this.pin = jsonObject.optString("pin");
this.username = jsonObject.optString("username");
if (isStringNull(username)) username = "";
loginEmail = jsonObject.optString("loginEmail");
if (isStringNull(loginEmail)) loginEmail = "";
}
public static final EntityUser parseJson(String json) throws JSONException {
JSONObject jo = new JSONObject(json);
String type = jo.optString("type");
if (StringUtils.isEmpty(type)) throw new IllegalArgumentException("empty type");
EntityUser res;
if (type.equals(TYPE_MEDICAL_CENTER)) {
res = new MedicalCenterUser(jo.optJSONObject("data"));
} else if (type.equals(TYPE_DOCTOR)) {
res = new DoctorUser(jo.optJSONObject("data"));
} else if (type.equals(TYPE_PATIENT)) {
res = new PatientUser(jo.optJSONObject("data"));
} else {
throw new IllegalArgumentException("Wrong type: " + type);
}
return res;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getProfileIconUrl() {
return profileIconUrl;
}
public void setProfileIconUrl(String profileIconUrl) {
this.profileIconUrl = profileIconUrl;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getWorkingHours() {
return workingHours;
}
public void setWorkingHours(String workingHours) {
this.workingHours = workingHours;
}
public String getAcceptedInsurances() {
return acceptedInsurances;
}
public void setAcceptedInsurances(String acceptedInsurances) {
this.acceptedInsurances = acceptedInsurances;
}
public int getNumUnread() {
return numUnread;
}
public void setNumUnread(int numUnread) {
this.numUnread = numUnread;
}
public long getLastMsgTime() {
return lastMsgTime;
}
public void setLastMsgTime(long lastMsgTime) {
this.lastMsgTime = lastMsgTime;
}
public String getPinyinName() {
return pinyinName;
}
public void setPinyinName(String pinyinName) {
this.pinyinName = pinyinName;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.id)
.append(',')
.append(this.fullname)
.append(',')
.append(this.description);
return sb.toString();
}
public String getPin() {
return pin;
}
public void setPin(String pin) {
this.pin = pin;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getLoginEmail() {
return loginEmail;
}
public void setLoginEmail(String loginEmail) {
this.loginEmail = loginEmail;
}
private boolean isStringNull(String s) {
return s == null || StringUtils.isBlank(s) || s.equals("null");
}
}
| [
"weisong3@gmail.com"
] | weisong3@gmail.com | |
401cee58c80b876ddc60815449e5b6049e21f8b9 | 5c49bf282ba13ec54504ef3749bf4fa5ee8fde3d | /src/ExecuteVM.java | 05b0fe0307b596c6b2e79df8ce107c74a5f7d189 | [] | no_license | scumatteo/FOOL-compiler | 3f1d6c9aca7faf1f2515702370faf537b05ae192 | 7fbe1b3d7483b46806f38ed0e5d2e1a8685dedfe | refs/heads/master | 2023-03-01T12:10:25.760576 | 2021-02-14T19:08:17 | 2021-02-14T19:08:17 | 338,867,715 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,315 | java | import lib.FOOLlib;
public class ExecuteVM {
public static final int CODESIZE = 10000;
private int[] code;
private int[] memory = new int[FOOLlib.MEMSIZE]; //Area di memoria STACK + HEAP
private int ip = 0; // INSTRUCTION POINTER
private int sp = FOOLlib.MEMSIZE; //STACK POINTER
private int hp = 0; //HEAP POINTER
private int fp = FOOLlib.MEMSIZE; //FRAME POINTER all'ActivationRecord (per chiamate di metodo) retValue, par, spazioLocalVar, cl(frame prec sullo stack), ra (next istr)
private int ra; //RETURN ADDRESS
private int tm; //generico
public ExecuteVM(int[] code) {
this.code = code;
}
public void cpu() {
while ( true ) {
int bytecode = code[ip++]; // fetch
int v1,v2;
int address;
switch ( bytecode ) {
case SVMParser.PUSH:
push( code[ip++] );
break;
case SVMParser.POP:
pop();
break;
case SVMParser.ADD :
v1=pop();
v2=pop();
push(v2 + v1);
break;
case SVMParser.MULT :
v1=pop();
v2=pop();
push(v2 * v1);
break;
case SVMParser.DIV :
v1=pop();
v2=pop();
push(v2 / v1);
break;
case SVMParser.SUB :
v1=pop();
v2=pop();
push(v2 - v1);
break;
case SVMParser.STOREW : //
address = pop();
memory[address] = pop();
break;
case SVMParser.LOADW : //
push(memory[pop()]);
break;
case SVMParser.BRANCH :
address = code[ip];
ip = address;
break;
case SVMParser.BRANCHEQ :
address = code[ip++];
v1=pop();
v2=pop();
if (v2 == v1) ip = address;
break;
case SVMParser.BRANCHLESSEQ :
address = code[ip++];
v1=pop();
v2=pop();
if (v2 <= v1) ip = address;
break;
case SVMParser.JS : //
address = pop();
ra = ip;
ip = address;
break;
case SVMParser.STORERA : //
ra=pop();
break;
case SVMParser.LOADRA : //
push(ra);
break;
case SVMParser.STORETM :
tm=pop();
break;
case SVMParser.LOADTM :
push(tm);
break;
case SVMParser.LOADFP : //
push(fp);
break;
case SVMParser.STOREFP : //
fp=pop();
break;
case SVMParser.COPYFP : //
fp=sp;
break;
case SVMParser.STOREHP : //
hp=pop();
break;
case SVMParser.LOADHP : //
push(hp);
break;
case SVMParser.PRINT :
System.out.println((sp<FOOLlib.MEMSIZE)?memory[sp]:"Empty stack!");
break;
case SVMParser.HALT :
return;
}
}
}
private int pop() {
return memory[sp++];
}
private void push(int v) {
memory[--sp] = v;
}
} | [
"matteo.scucchia@studio.unibo.it"
] | matteo.scucchia@studio.unibo.it |
28e57906b34de501b44723b4037c8b6fcd630a51 | 4af345f7b24a27c0702f899fdbf2fe81768a88c7 | /Spring/InventoryManagement/src/main/java/com/ctech/admin/BaseController.java | 90adf440738a49e3b5fcfac2be3fab0f5829ec95 | [] | no_license | cybertechsystems/workplace | f4023a936539e8251738be222b454aa266cfcdff | 982df4bdc3c8321adc60b6ad5199158579f86470 | refs/heads/master | 2020-04-13T02:37:55.343240 | 2014-04-10T05:38:43 | 2014-04-10T05:38:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,117 | java | package com.ctech.admin;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import com.ctech.admin.beans.Paging;
import com.ctech.admin.util.Util;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* This controller has been used as a template for the implementations such as manage the paging for different sections
* and saving the image.
*
* @author Cybertech
*
*/
public abstract class BaseController {
protected String managePaging(HttpServletRequest req) throws IOException {
int start = Util.convertToNumber(req.getParameter("iDisplayStart"));
int length = Util.convertToNumber(req.getParameter("iDisplayLength"));
Paging paging = new Paging();
paging.setStart(start);
paging.setSize(length);
String search = req.getParameter("sSearch");
if(search != null && search.trim().length() > 0) {
paging.setSearch("%"+search+"%");
}
String orderCol = req.getParameter("iSortCol_0");
if(orderCol != null && orderCol.trim().length() > 0) {
paging.setOrderCol(Util.convertToNumber(orderCol) + 1);
} else {
paging.setOrderCol(99);
}
String orderBy = req.getParameter("sSortDir_0");
if(orderBy != null && orderBy.trim().length() > 0) {
paging.setOrderBy(orderBy);
} else {
paging.setOrderBy("desc");
}
HttpSession session = req.getSession();
String totalCount = (String)session.getAttribute("totalCount");
totalCount = (totalCount == null || start == 0) ? getTotalCount(paging): totalCount;
session.setAttribute("totalCount", totalCount);
Map<String, Object> data = new HashMap<String, Object>();
data.put("sEcho", req.getParameter("sEcho"));
data.put("iTotalRecords", new Integer(length));
data.put("iTotalDisplayRecords", totalCount);
data.put("aaData", loadPageRecords(paging));
JsonFactory factory = new JsonFactory();
StringWriter out = new StringWriter();
JsonGenerator g = factory.createGenerator(out);
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(g, data);
String output = out.toString();
out.flush();
return output;
}
abstract protected Object loadPageRecords(Paging input);
abstract protected String getTotalCount(Paging input) ;
protected String saveImage(MultipartFile rawImage, String name, String path) throws IOException {
if(rawImage != null && rawImage.getOriginalFilename().trim().length() > 0) {
int start = rawImage.getOriginalFilename().indexOf(".");
String fileName = rawImage.getOriginalFilename().substring(0,start) +"_" + name +
rawImage.getOriginalFilename().substring(start,rawImage.getOriginalFilename().length());
FileCopyUtils.copy(rawImage.getBytes(), new FileOutputStream(path + fileName));
return fileName;
}
return null;
}
}
| [
"support@cybertechsystems.net"
] | support@cybertechsystems.net |
f88b693c961856fedcc55b1f723c9ec0d9992ac1 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/4/4_ee698e98325ee5fa3c4892e645fae0ad0d318d0b/HTMLBaseFontElementTest/4_ee698e98325ee5fa3c4892e645fae0ad0d318d0b_HTMLBaseFontElementTest_t.java | 449a86ea36934550816373f1721052df040f2ca3 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 5,644 | java | /*
* Copyright (c) 2002-2013 Gargoyle Software Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gargoylesoftware.htmlunit.javascript.host.html;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.gargoylesoftware.htmlunit.BrowserRunner;
import com.gargoylesoftware.htmlunit.BrowserRunner.Alerts;
import com.gargoylesoftware.htmlunit.BrowserRunner.Browser;
import com.gargoylesoftware.htmlunit.BrowserRunner.NotYetImplemented;
import com.gargoylesoftware.htmlunit.WebDriverTestCase;
/**
* Tests for {@link HTMLBaseFontElement}.
* @version $Revision$
* @author Ronald Brill
*/
@RunWith(BrowserRunner.class)
public class HTMLBaseFontElementTest extends WebDriverTestCase {
/**
* @throws Exception if an error occurs
*/
@Test
@NotYetImplemented(Browser.FF3_6)
@Alerts(DEFAULT = { "[object HTMLSpanElement]", "undefined", "undefined", "undefined" },
FF3_6 = { "[object HTMLBaseFontElement]", "", "-1", "" },
IE = { "[object]", "", "3", "" })
public void defaults() throws Exception {
final String html =
"<html>\n"
+ " <head>\n"
+ " <basefont id='base' />\n"
+ " <script>\n"
+ " function test() {\n"
+ " var base = document.getElementById('base');\n"
+ " alert(base);\n"
+ " alert(base.face);\n"
+ " alert(base.size);\n"
+ " alert(base.color);\n"
+ " }\n"
+ " </script>\n"
+ " </head>\n"
+ " <body onload='test()'>foo</body>\n"
+ "</html>";
loadPageWithAlerts2(html);
}
/**
* @throws Exception if an error occurs
*/
@Test
@NotYetImplemented({ Browser.FF10, Browser.FF17 })
@Alerts(DEFAULT = { "undefined", "42" },
FF3_6 = { "4", "42" },
IE = { "4", "42" })
public void size() throws Exception {
final String html =
"<html>\n"
+ " <head>\n"
+ " <basefont id='base' color='red' face='swiss' size='4' />\n"
+ " <script>\n"
+ " function test() {\n"
+ " var base = document.getElementById('base');\n"
+ " alert(base.size);\n"
+ " try {\n"
+ " base.size=42;\n"
+ " alert(base.size);\n"
+ " } catch(e) {\n"
+ " alert('exception');\n"
+ " }\n"
+ " }\n"
+ " </script>\n"
+ " </head>\n"
+ " <body onload='test()'>foo</body>\n"
+ "</html>";
loadPageWithAlerts2(html);
}
/**
* @throws Exception if an error occurs
*/
@Test
@NotYetImplemented({ Browser.FF10, Browser.FF17 })
@Alerts(DEFAULT = { "undefined", "helvetica" },
FF3_6 = { "swiss", "helvetica" },
IE = { "swiss", "helvetica" })
public void face() throws Exception {
final String html =
"<html>\n"
+ " <head>\n"
+ " <basefont id='base' color='red' face='swiss' size='5' />\n"
+ " <script>\n"
+ " function test() {\n"
+ " var base = document.getElementById('base');\n"
+ " alert(base.face);\n"
+ " try {\n"
+ " base.face='helvetica';\n"
+ " alert(base.face);\n"
+ " } catch(e) {\n"
+ " alert('exception');\n"
+ " }\n"
+ " }\n"
+ " </script>\n"
+ " </head>\n"
+ " <body onload='test()'>foo</body>\n"
+ "</html>";
loadPageWithAlerts2(html);
}
/**
* @throws Exception if an error occurs
*/
@Test
@NotYetImplemented({ Browser.FF10, Browser.FF17, Browser.IE })
@Alerts(DEFAULT = { "undefined", "blue" },
FF3_6 = { "red", "blue" },
IE = { "#ff0000", "#0000ff" })
public void color() throws Exception {
final String html =
"<html>\n"
+ " <head>\n"
+ " <basefont id='base' color='red' face='swiss' size='4' />\n"
+ " <script>\n"
+ " function test() {\n"
+ " var base = document.getElementById('base');\n"
+ " alert(base.color);\n"
+ " try {\n"
+ " base.color='blue';\n"
+ " alert(base.color);\n"
+ " } catch(e) {\n"
+ " alert('exception');\n"
+ " }\n"
+ " }\n"
+ " </script>\n"
+ " </head>\n"
+ " <body onload='test()'>foo</body>\n"
+ "</html>";
loadPageWithAlerts2(html);
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
bc87c7f3d7684336f062a37b2b8e8077a7453e9b | f5841e2b315fb3a27d23feff39ada98270b7f352 | /src/main/java/vehiculo/Conductor.java | 99e927ea04018de44841ea7d62914f6efb3f19fa | [] | no_license | Desterpunk/challengeCarros | b336626ad07df5f9e87a6ecbc161b6e8787663a9 | 6bd0e94aebba03f60ba8baa9a730404afcd17c5e | refs/heads/master | 2023-06-19T16:55:03.414854 | 2021-07-08T23:21:41 | 2021-07-08T23:21:41 | 384,267,212 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 650 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package vehiculo;
/**
*
* @author Pc-pro
*/
public class Conductor {
private String nombre;
public Conductor() {
}
//Constructor del conductor
public Conductor(String nombre) {
this.nombre = nombre;
}
public String getNombre() {
return nombre;
}
public Integer lanzarDado() {
int dadoAleatorio = (int) (Math.random() * 6 + 1);
return dadoAleatorio;
}
}
| [
"jhonalfaber@hotmail.com"
] | jhonalfaber@hotmail.com |
8d6da7f4681c32c5094c4dd841c358f8cafa2846 | db07718c00299dc838c2cfd672476cbf41fb2662 | /Lab7/src/main/java/Database/Book.java | 9bb5c556f4a22d325fa62416fbf0390f07ebe4ed | [] | no_license | michalkilian/Programowanie_Obiektowe | 884b41368317c81eaf4d1e796b74088371a82375 | 186d42ee01d0cb6f8943b46c45d86714dc825253 | refs/heads/master | 2020-03-30T13:08:09.177447 | 2019-05-16T20:58:18 | 2019-05-16T20:58:18 | 151,258,027 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,092 | java | package Database;
public class Book {
private String isbn;
private String title;
private String author;
private String year;
public Book(String isbn, String title, String author, String year){
this.isbn = isbn;
this.title = title;
this.author = author;
this.year = year;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public void print() {
System.out.println("ISBN " + isbn);
System.out.println("Title " + title);
System.out.println("Author " + author);
System.out.println("Year " + year +'\n');
}
}
| [
"mkilian@mielec.com.pl"
] | mkilian@mielec.com.pl |
cdf63d10c3a48740fcd7f3ca02886abe97b29f73 | b7e5cd0d70471d8c0ae4a9b2b8e657d22ea2e08e | /sac/src/br/com/meganet/bo/ContratoBO.java | 0e89e334fe793eacdbfbbda4f4ce8eb5d1fed6af | [] | no_license | Letractively/saum | d0868b967cf934ef59367e87f6e3eceb8432d39b | 1b4887ecb335e484e612fa87ad7da43082fc1354 | refs/heads/master | 2021-01-10T16:54:29.604440 | 2012-10-30T20:27:21 | 2012-10-30T20:27:21 | 45,963,503 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,058 | java | package br.com.meganet.bo;
import java.util.List;
import br.com.meganet.exception.GAPBDException;
import br.com.meganet.hbm.DAO.ContratoDAO;
import br.com.meganet.hbm.DAO.UsuarioDAO;
import br.com.meganet.hbm.vo.Contrato;
import br.com.meganet.hbm.vo.Usuario;
public class ContratoBO {
private ContratoDAO contratoDAO;
private UsuarioDAO usuarioDAO;
public void setUsuarioDAO(UsuarioDAO usuarioDAO) {
this.usuarioDAO = usuarioDAO;
}
public void setContratoDAO(ContratoDAO contratoDAO) {
this.contratoDAO = contratoDAO;
}
public List<Contrato> buscaContratos() {
return contratoDAO.findAll();
}
public Contrato buscaContrato(Long id) {
return contratoDAO.findById(id);
}
public void salvaContrato(Contrato contrato) throws GAPBDException{
contratoDAO.attachDirty(contrato);
}
public Contrato getContratoPeloCliente(long idCliente) {
Usuario usr = usuarioDAO.findById(idCliente);
Contrato ret = contratoDAO.findById(usr.getContrato().getContratoId());
return ret;
}
}
| [
"efrenjunior@gmail.com"
] | efrenjunior@gmail.com |
ac119df3983579d657794f0a6b87f3aa0f2c3428 | ee97a72cf9b18613fec84462ae1c0b2f3b3ab2e1 | /src/main/java/main/content/ContentFiterController.java | 433b6bae1a09d27884014ba0dbf67b39057f9cc3 | [] | no_license | HSJMichael/Springboot-contenFiter-HSJ | 8d3a0c9556ee90fd18020795f0efaa332b4b93bd | f1d00bb72b187c9dc2325a6cb50d4257685bf6c2 | refs/heads/master | 2021-03-21T12:34:18.225303 | 2020-03-14T14:42:41 | 2020-03-14T14:42:41 | 247,293,201 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,976 | java | package main.content;
import com.baidu.aip.contentcensor.AipContentCensor;
import com.baidu.aip.contentcensor.EImgType;
import com.google.gson.Gson;
import main.dto.ImgResponDto;
import main.dto.MassageDto;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
/**
* @author HeJun
* @version 1.0
* @description
* @Date $time$ $date$
*/
@RestController
public class ContentFiterController {
@PostMapping("/getToken")
public String sendDirectMessage() {
return AuthService.getAuth();
}
@Autowired
/**图片内容审核客户端*/
private static AipContentCensor contentCensorClient;
/**
* @return
* @throws Exception
* @Author HeJun
* @Description 检测文本内容
* @Date 15:16 2020/3/14
* @Param
**/
@PostMapping("/chackText")
public String chackText(@RequestBody MassageDto dto) {
JSONObject response = ConnecrClient.getContent().textCensorUserDefined(dto.getContent());
Gson gson = new Gson();
ImgResponDto imgResponDto =new ImgResponDto();
imgResponDto = gson.fromJson(response.toString(), ImgResponDto.class);
return response.toString();
}
/**
* @return
* @throws Exception
* @Author HeJun
* @Description 检测图像内容
* @Date 21:33 2020/3/14
* @Param
**/
@PostMapping("/testImage")
public String testImage(@RequestBody MassageDto dto) {
AipContentCensor client = ConnecrClient.getContent();
JSONObject response = new JSONObject();
Gson gson = new Gson();
ImgResponDto imgResponDto =new ImgResponDto();
if (dto.getType() == 1) {
String path = dto.getPathOrUrl();
// String path = "D:\\HSJ\\桌面文件\\111.jpg";
response = client.imageCensorUserDefined(path, EImgType.FILE, null);
System.out.println(response.toString());
imgResponDto = gson.fromJson(response.toString(), ImgResponDto.class);
return response.toString();
}
// 参数为url
// String url = dto.getPathOrUrl();
String url = "http://piedaochuan.oss-cn-shenzhen.aliyuncs.com/erp/u%3D2454486949%2C718417276%26fm%3D26%26gp%3D0_1571644278000.jpg";
response = client.imageCensorUserDefined(url, EImgType.URL, null);
imgResponDto = gson.fromJson(response.toString(), ImgResponDto.class);
System.out.println(response.toString());
return response.toString();
// 参数为本地图片文件二进制数组
// byte[] file = readImageFile(imagePath);
// response = client.imageCensorUserDefined(file, null);
// System.out.println(response.toString());
}
}
| [
"1013327563@qq.com"
] | 1013327563@qq.com |
b68cacfd53dd446f07d4734ab3e3f48746bea5a2 | be3ab5373eeb73da50f09062b518f54c59e3897a | /src/main/java/com/shani/vehicle/utils/Validation.java | 19805659f9f092a014d47be30975fe04a36fa1b4 | [] | no_license | ardra-2805/Vehicle-Management-System | 71d7833e92597624e09e2dc43455d5830b31b54b | 6b241e9cac53ac6558e3f9d6d87599adbee87c55 | refs/heads/master | 2022-11-10T08:47:43.607180 | 2019-09-29T09:06:50 | 2019-09-29T09:06:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 560 | java | package com.shani.vehicle.utils;
import com.shani.vehicle.exceptions.ApplicationException;
public class Validation {
// year between 1900-2099
public static boolean isYearValid(String year) throws ApplicationException{
String regex = "^(19|20)\\d{2}$";
return year.matches(regex);
}
// license number contains between 5 - 8 numbers
public static boolean isLicenseNumberValid(long licenseNumber) throws ApplicationException{
String licenseString = licenseNumber+"";
String regex = "^[0-9]{5,8}$";
return licenseString.matches(regex);
}
} | [
"shanifouks@gmail.com"
] | shanifouks@gmail.com |
176fc74cf16d2b5b3d66ca0a3eb2165d3d97a575 | ced9667de4d838d4736d047240bbb4533c9a9078 | /app/src/androidTest/java/ghostl/com/facebookrecipesexample/ExampleInstrumentedTest.java | 902905bc479b34175addfe34b2c1ad95301ca554 | [] | no_license | Litman/FacebookRecipe | 4dd7909522556c9987930d6d2cf86eed2b27774e | 5700a0006ea3e9fc0dbf96084c7097f7711ddea9 | refs/heads/master | 2020-04-02T01:25:28.263467 | 2018-10-20T00:28:20 | 2018-10-20T00:28:20 | 153,854,812 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 750 | java | package ghostl.com.facebookrecipesexample;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("ghostl.com.facebookrecipesexample", appContext.getPackageName());
}
}
| [
"layala@vectoritcgroup.com"
] | layala@vectoritcgroup.com |
246ca99bec95797e7fd1e48d99e675f0536ce5e6 | f711bd83f428b9b56981c8a9bca6bdaab478d6a8 | /app/src/main/java/com/example/projectappkelasbesar/MainActivity.java | 67c30091b46fcce3eefb51e3e8c5ea7b0396fffa | [] | no_license | GazicAditya/Board-Game-Market-App | 74dfba95ac8dcf6bd287c8bbc9420fd8f0bf9237 | cf6b17ff986b608c624c763326639e6a2762b6e0 | refs/heads/main | 2023-09-05T03:40:23.924712 | 2021-11-08T16:22:26 | 2021-11-08T16:22:26 | 425,910,369 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,123 | java | package com.example.projectappkelasbesar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView onProgressButton, doneButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onProgressButton = findViewById(R.id.onProgressButton);
doneButton = findViewById(R.id.doneButton);
}
@Override
protected void onResume() {
super.onResume();
ToDoFragment toDoFragment = ToDoFragment.newInstance();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragments, toDoFragment);
transaction.commit();
}
public void toProgress(View view) {
ToDoFragment toDoFragment = ToDoFragment.newInstance();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragments, toDoFragment);
transaction.commit();
doneButton.setTextColor(Color.parseColor("#bfbfbf"));
onProgressButton.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.navy));
}
public void toDone(View view) {
DoneFragment doneFragment = DoneFragment.newInstance();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragments, doneFragment);
transaction.commit();
onProgressButton.setTextColor(Color.parseColor("#bfbfbf"));
doneButton.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.navy));
}
public void toAdd(View view) {
Intent intent = new Intent(this, AddToDoPage.class);
startActivity(intent);
}
} | [
"gazictotti@gmail.com"
] | gazictotti@gmail.com |
1fd8c02686e308fbadc62c786274a3fc791a69a4 | 9926a6a4ac88171c98b07b848f5861728fd18239 | /.history/assignment8_20211031192419.java | 8701045698a648032f8b7d5c1263378d143a2ef7 | [] | no_license | magikflowz/JavaAssignments | 4dadee2f0f23d581f94c998680ab188c1247013c | a4f01f60cedd08dd216841ba98fadac9c09bbe76 | refs/heads/master | 2023-08-28T13:08:43.877417 | 2021-11-02T10:47:55 | 2021-11-02T10:47:55 | 423,601,478 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,368 | java | /* Programming Assignment 8. CSET 1200.
* University of Toledo.
* Instructor: Jared Oluoch, Ph.D.
* Due Date: Sunday October 31, 2021 at 11:59 PM.
* Total Points:20
*/
/* Your program must compile and run to get credit.
* If your program does not compile, you may get 0.
* If you copy from your classmate, both of you get 0.
* If you copy from a website, you get 0.
* Your program must have the following information at the top.
# Name : Your First and Last Name
# Class: CSET 1200
# Instructor: Dr. Jared Oluoch
# Programming Assignment: 8
# Date: MMDDYY
# Summary: A brief description of what the program does.
# You must put this line as a comment at the top of your Java source file.
“This code is my own work. I did not get any help from any online source
such as chegg.com; from a classmate, or any other person other than the instructor
or TA for this course. I understand that getting outside help from this course
other than from the instructor or TA will result in a grade of 0 in this
assignment and other disciplinary actions for academic dishonesty.â€
*/
import java.io.*;
import java.util.*;
public class assignment8{
public static void Single(String Name, int Income){
double tax = 0;
if(Income >=0 && Income <= 9750){
tax = .1;
}
if(Income >= 9701 && Income <=39475){
tax = .12;
}
if(Income >= 39476 && Income <= 82200){
tax = .22;
}
if(Income >= 82201 && Income <= 160725){
tax = .24;
}
if(Income >= 160726 && Income <= 204100){
tax = .32;
}
if(Income >= 204101 && Income <= 510300){
tax = .35;
}
if(Income >= 510301){
tax = .37;
}
tax = (Income/100)*tax;
System.out.print(Name +", the federal income tax for an annual salary of "+Income+" for single status "+tax);
}
public static void headofHousehold(String Name, int Income){
double tax = 0;
if(Income >= 0 && Income <= 13850){
tax = .1;
}
if(Income >= 13851 && Income <= 52850){
tax = .12;
}
if(Income >= 52851 && Income <= 84200){
tax = .22;
}
if(Income >= 84201 && Income <= 160700){
tax = .24;
}
if(Income >= 160701 && Income <= 204100){
tax = .32;
}
if(Income >= 204101 && Income <= 510300){
tax = .35;
}
if(Income >= 510301){
tax = .37;
}
tax = (Income/100)*tax;
System.out.print(Name +", the federal income tax for an annual salary of " +Income+" for single status "+tax);
}
public String marriedJointly(String Name, int Income){
double tax = 0;
if(Income >=0 && Income<=19400){
tax = .1;
}
if(Income >= 19401 && Income <= 78950){
tax = .12;
}
if(Income >= 78951 && Income <= 168400){
tax = .22;
}
if(Income >= 168401 && Income <= 321450){
tax = .24;
}
if(Income >= 321451 && Income<=408200){
tax = .32;
}
if(Income >= 408201 && Income<=612350){
tax = .35;
}
if(Income >= 612351){
tax = .37;
}
tax = (Income/100)*tax;
System.out.print(Name +", the federal income tax for an annual salary of "+Income+" for single status "+tax);
}
public String marriedSeparately(String Name, int Income){
double tax = 0;
if(Income >=0 && Income <= 9700){
tax = .1;
}
if(Income >= 9701 && Income <= 39475){
tax = .12;
}
if(Income >= 39476 && Income <= 84200){
tax = .22;
}
if(Income >= 84201 && Income <= 160725){
tax = .24;
}
if(Income >= 160726 && Income <= 204100){
tax = .32;
}
if(Income >= 204101 && Income <= 306175){
tax = .35;
}
if(Income >= 306176){
tax = .37;
}
tax = (Income/100)*tax;
return (Name+", the federal income tax for an annual salary of "+Income+" for a married separate status filer is "+tax);
}
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
String Name;
int Income;
String Status;
System.out.print("What is your name: ");
Name = keyboard.next();
System.out.print("What is annual income: ");
Income = keyboard.nextInt();
System.out.print("Enter 0 - Single, '\n' 2 - head of household '\n' 3 - married filling jointly '\n' 4 - married filling '\n' Enter your option: ");
Status = keyboard.next();
if(Status.equals("0")){
System.out.println("test complete");
Single(Name, Income);
}
else if (Status.equals("2")){
headofHousehold(Name, Income);
}
else if(Status.equals("3")){
taxinfo2.marriedJointly(Name, Income);
}
else if(Status.equals("4")){
taxinfo2.marriedSeparately(Name, Income);
}
}
} | [
"75277480+ImNotMagik@users.noreply.github.com"
] | 75277480+ImNotMagik@users.noreply.github.com |
14e40ac7c8c68413f5991a946abc0039505e49ab | a5ec0b3cd264e5cf236553feda3b346a9bc4d8a3 | /src/ControllerAPP/ClassControllerHRA.java | 301a2742ed713d42af99439679c9b98e2946c36d | [] | no_license | slava101219/ResidenHouseAPP | bcce309deeafb76232182b70bdbbee438c26471e | 2423f122e9eb59bc7086eb66fef29648ce459018 | refs/heads/master | 2022-11-06T17:10:26.248844 | 2020-06-25T17:32:13 | 2020-06-25T17:32:13 | 274,754,507 | 0 | 0 | null | null | null | null | WINDOWS-1251 | Java | false | false | 5,088 | java | package ControllerAPP;
import java.io.*;
import ServiceAPP.ClassForServiceHRA;
import ViewAPP.ClassForView;
public class ClassControllerHRA {
private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
ClassForView view = new ClassForView();
ClassForServiceHRA service = new ClassForServiceHRA();
private String strq, str2, str3, str4, str5;
private String st1, st2;
public void start() throws IOException {
view.printMenuEntrance();
strq = reader.readLine();
switch (strq) {
case "1" : registration(); break;
case "2" : entrance(); break;
case "3" : actionChairman(); break;
default : start();
}
}
public void registration() throws IOException {
System.out.println("Введите логин. Логин должен содержать от 5 до 15 цифр или букв латинского алфавита.");
str2 = reader.readLine();
if (str2.toCharArray().length<5||str2.toCharArray().length>15) {
System.out.println("Недопустимая длина. Попробуйте еще раз.");
registration(); return;
}
if (service.checkExistLogin(str2)==true) {
System.out.println("такой логин занят. Попробуйте еще раз.");
registration(); return;
}
if (!str2.matches("[0-9a-zA-Z]+")) {
System.out.println("Вы используете недопустимые символы. Попробуйте еще раз.");
registration(); return;
}
System.out.println("Введите пароль. Пароль должен содержать от 5 до 10 символов.");
str3 = reader.readLine();
if (str3.toCharArray().length<5||str3.toCharArray().length>10) {
System.out.println("ошибка. Попробуйте еще раз.");
registration(); return;
}
System.out.println("Введите имя. От 2 до 15 символов кирилицей.");
str4 = reader.readLine();
if (str4.toCharArray().length<2||str4.toCharArray().length>15) {
System.out.println("Недопустимая длина Имени. Попробуйте еще раз.");
registration(); return;
}
if (!str4.matches("[а-яА-Я]+")) {
System.out.println("Вы используете недопустимые символы. Попробуйте еще раз.");
registration(); return;
}
System.out.println("Введите Фамилию. От 2 до 15 символов кирилицей.");
str5 = reader.readLine();
if (str5.toCharArray().length<2||str4.toCharArray().length>15) {
System.out.println("Недопустимая длина Имени. Попробуйте еще раз.");
registration(); return;
}
if (!str5.matches("[а-яА-Я]+")) {
System.out.println("Вы используете недопустимые символы. Попробуйте еще раз.");
registration(); return;
}
service.writeRegistrationData(str2, str3, str4, str5);
System.out.println("Регистрация прошла успешно!");
entrance();
}
public void entrance() throws IOException {
System.out.println("Для входа необходимо ввести логин и пароль.");
System.out.println("Ведите логин.");
st1 = reader.readLine();
if (st1.toCharArray().length<5||st1.toCharArray().length>15) {
System.out.println("Недопустимая длина. Попробуйте еще раз.");
entrance(); return;
}
if (!st1.matches("[0-9a-zA-Z]+")) {
System.out.println("Вы используете недопустимые символы. Попробуйте еще раз.");
entrance(); return;
}
if (!service.checkExistLogin(st1)) {
System.out.println("такой логин не существует. Попробуйте еще раз.");
entrance(); return;
}
System.out.println("Ведите пароль.");
st2 = reader.readLine();
if (st2.toCharArray().length<5||st2.toCharArray().length>10) {
System.out.println("ошибка. Попробуйте еще раз.");
entrance(); return;
}
if (!service.checkPassword(st1, st2)) {
System.out.println("Не верный пароль");
entrance(); return;
}
actionResident(st1);
}
private void actionResident(String login) throws IOException {
view.printMenuForResident(login);
String str = reader.readLine();
switch (str) {
case "1" : service.createNewVote(login); actionResident(login); break;
case "2" : service.checkResultPollings(); actionResident(login); break;
case "3" : service.checkPollingWithoutVote(login); actionResident(login); break;
case "4" : start(); break;
default : actionResident(login);
}
}
public void actionChairman() throws IOException {
view.printMenuForChairman();
String str = reader.readLine();
switch (str) {
case "1" : service.createNewpolling(); actionChairman(); break;
case "2" : service.checkResultPollings(); actionChairman(); break;
case "3" : service.deletePolling(); actionChairman(); break;
case "4" : start(); break;
default : actionChairman();
}
}
}
| [
"58745476+slava101219@users.noreply.github.com"
] | 58745476+slava101219@users.noreply.github.com |
430feb52296262b03c7a31e1a639cc0225758a0b | 9949e94ac7be605e4a7d4ead7bb009e68961df53 | /HelloWorld/src/com/mrybak834/patterns/builder/foodItem/FoodItem.java | ac438819aba9d68c1161503b306de16fafbec7c5 | [] | no_license | mrybak834/java | e96d38eda76e50d378c5c732ed3c4de0704d7506 | 3f45a1a8c9210be500a14af453608cf677e172af | refs/heads/master | 2020-03-27T18:25:27.135775 | 2018-09-05T02:19:20 | 2018-09-05T02:19:20 | 146,921,343 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 200 | java | package com.mrybak834.patterns.builder.foodItem;
import com.mrybak834.patterns.builder.container.Container;
public interface FoodItem {
String name();
Container pack();
float price();
}
| [
"mrybak3@uic.edu"
] | mrybak3@uic.edu |
b8f899eb7fb3ef7d19f92849d3120c6ef7788a70 | 76e71f3e192de9a1488cfc283162ab481e10bd2e | /src/qihu/Object1.java | b4589e0831174ea71c5ad3452098c7ff6e42a38c | [] | no_license | FHfirehuo/Interview | 02754f4053189b44d6e247ecedfa13b2c7b03d1a | 7a2d1e035f431717196ff158e6cfb68a4c6ea815 | refs/heads/master | 2021-01-24T19:24:21.758137 | 2018-02-28T06:42:10 | 2018-02-28T06:42:10 | 123,241,512 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 795 | java | package qihu;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Object 有哪些方法
*
* @author fire
*
*/
public class Object1 {
public static void main(String[] args) {
Object o =new Object();
o.getClass();
/**
* equals 和 hashCode 作用
*/
o.equals("");
o.hashCode();
//o.notify();
//o.notifyAll();
//o.toString();
/*try {
o.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
Map<String, String> map = new ConcurrentHashMap<String, String>();
map.put("a", "a");
map.size();
map.get("a");
map.putAll(map);
Map<String, String> map1 = new HashMap<>();
String a = map1.put("a", "a");
System.out.println(a);
}
}
| [
"gegeaininiaige@outlook.com"
] | gegeaininiaige@outlook.com |
f345df64e2fa120e0251f605e5952500d3e4f6e6 | 9fd8901e56e51029301c43b296c8b2071e0e8fa9 | /prog_p2/src/IndexFilesBM25.java | f8dfd1bf90089fb2c11ff7452cb103d85a98c28e | [] | no_license | rachely3n/info4300 | 4171d809b42e11275a1a002c773f5c38d48e8c15 | ae052ad1ca394ad6ddbf279917b595c2b6f9f264 | refs/heads/master | 2020-05-17T12:35:29.928595 | 2013-11-08T23:37:19 | 2013-11-08T23:37:19 | 14,217,705 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,456 | java | import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.util.CharArraySet;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.search.similarities.BM25Similarity;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
/** Index all text files under a directory, the directory is at data/txt/
*/
public class IndexFilesBM25 {
private IndexFilesBM25() {}
/** Index all text files under a directory. */
public static void buildIndex(String indexPath, String docsPath, CharArraySet stopwords) {
// Check whether docsPath is valid
if (docsPath == null || docsPath.isEmpty()) {
System.err.println("Document directory cannot be null");
System.exit(1);
}
// Check whether the directory is readable
final File docDir = new File(docsPath);
if (!docDir.exists() || !docDir.canRead()) {
System.out.println("Document directory '" +docDir.getAbsolutePath()+ "' does not exist or is not readable, please check the path");
System.exit(1);
}
Date start = new Date();
IndexWriter writer = null;
try {
System.out.println("Indexing to directory '" + indexPath + "'...");
Directory dir = FSDirectory.open(new File(indexPath));
Analyzer analyzer = new MyAnalyzer(Version.LUCENE_44, stopwords);
IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_44, analyzer);
BM25Similarity temp = new BM25Similarity();
iwc.setSimilarity(temp);
// Create a new index in the directory, removing any
// previously indexed documents:
iwc.setOpenMode(OpenMode.CREATE);
writer = new IndexWriter(dir, iwc);
// Write the index into them.
indexDocs(writer, docDir);
Date end = new Date();
System.out.println(end.getTime() - start.getTime() + " total milliseconds");
} catch (IOException e) {
System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage());
} finally {
try {
writer.close();
} catch(IOException e) {
System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage());
}
}
}
/**
* Indexes the given file using the given writer, or if a directory is given,
* recurses over files and directories found under the given directory.
*/
static void indexDocs(IndexWriter writer, File file) {
if (file.canRead()) {
if (file.isDirectory()) {
String[] files = file.list();
if (files != null) {
for (int i = 0; i < files.length; i++) {
indexDocs(writer, new File(file, files[i]));
}
}
} else {
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage());
}
try {
// make a new, empty document
Document doc = new Document();
// Add the path of the file as a field named "path". Use a
// field that is indexed (i.e. searchable), but don't tokenize
// the field into separate words and don't index term frequency
// or positional information:
Field pathField = new StringField("path", file.getName(), Field.Store.YES);
doc.add(pathField);
// Add the contents of the file to a field named "contents". Specify a Reader,
// so that the text of the file is tokenized and indexed, but not stored.
doc.add(new TextField("contents", new BufferedReader(new InputStreamReader(fis))));
// New index, so we just add the document (no old document can be there):
// System.out.println("adding " + file);
writer.addDocument(doc);
} catch (IOException e) {
System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage());
} finally {
try {
fis.close();
} catch(IOException e) {
System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage());
}
}
}
}
}
}
| [
"cc733@cornell.edu"
] | cc733@cornell.edu |
290794aa29d5141f613fc0a7ade0082ede8f7aba | e108d65747c07078ae7be6dcd6369ac359d098d7 | /com/google/common/collect/Interners.java | c3d89ac76dc9c1d470f6635298f9643dcb339f19 | [
"MIT"
] | permissive | kelu124/pyS3 | 50f30b51483bf8f9581427d2a424e239cfce5604 | 86eb139d971921418d6a62af79f2868f9c7704d5 | refs/heads/master | 2020-03-13T01:51:42.054846 | 2018-04-24T21:03:03 | 2018-04-24T21:03:03 | 130,913,008 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,542 | java | package com.google.common.collect;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Equivalence;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import java.util.concurrent.ConcurrentMap;
@GwtIncompatible
@Beta
public final class Interners {
private static class InternerFunction<E> implements Function<E, E> {
private final Interner<E> interner;
public InternerFunction(Interner<E> interner) {
this.interner = interner;
}
public E apply(E input) {
return this.interner.intern(input);
}
public int hashCode() {
return this.interner.hashCode();
}
public boolean equals(Object other) {
if (!(other instanceof InternerFunction)) {
return false;
}
return this.interner.equals(((InternerFunction) other).interner);
}
}
private static class WeakInterner<E> implements Interner<E> {
private final MapMakerInternalMap<E, Dummy, ?, ?> map;
private enum Dummy {
VALUE
}
private WeakInterner() {
this.map = new MapMaker().weakKeys().keyEquivalence(Equivalence.equals()).makeCustomMap();
}
public E intern(E sample) {
do {
InternalEntry<E, Dummy, ?> entry = this.map.getEntry(sample);
if (entry != null) {
E canonical = entry.getKey();
if (canonical != null) {
return canonical;
}
}
} while (((Dummy) this.map.putIfAbsent(sample, Dummy.VALUE)) != null);
return sample;
}
}
private Interners() {
}
public static <E> Interner<E> newStrongInterner() {
final ConcurrentMap<E, E> map = new MapMaker().makeMap();
return new Interner<E>() {
public E intern(E sample) {
E canonical = map.putIfAbsent(Preconditions.checkNotNull(sample), sample);
return canonical == null ? sample : canonical;
}
};
}
@GwtIncompatible("java.lang.ref.WeakReference")
public static <E> Interner<E> newWeakInterner() {
return new WeakInterner();
}
public static <E> Function<E, E> asFunction(Interner<E> interner) {
return new InternerFunction((Interner) Preconditions.checkNotNull(interner));
}
}
| [
"kelu124@gmail.com"
] | kelu124@gmail.com |
6ed3a01b04351e475965944a4f0e8194d7a964ce | 3f28947486fa8bb231f6541023a368b804c6274e | /src/main/java/fr/cnam/usal3b/luczak/justin/repository/EtapeRepository.java | 6e24f42e09ce2d22b4c813ae16ac84ff03b330e6 | [] | no_license | justinlczk/apichasseautresor | 78e3f2c53bfc2ca8b0410b503a9ae36150f374df | 2e91628056197487800ca13c45bdc75e83f794be | refs/heads/main | 2023-06-11T00:13:13.712197 | 2021-07-05T21:16:04 | 2021-07-05T21:16:04 | 380,052,362 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 362 | java | package fr.cnam.usal3b.luczak.justin.repository;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import fr.cnam.usal3b.luczak.justin.model.Etape;
import fr.cnam.usal3b.luczak.justin.model.Scenario;
public interface EtapeRepository extends CrudRepository<Etape, Integer> {
List<Etape> findByScenario(Scenario scenario);
} | [
"justin.luczak@hotmail.fr"
] | justin.luczak@hotmail.fr |
b39ebe8ab259900fbc6eb059e5430a4f676e333b | 33e8bace9ea2451aceb81c0567286289ed851471 | /src/main/java/com/nishant/ecommerce/service/OrderService.java | a12d9443965877d9889e9d37424672ec6cbbf92d | [] | no_license | ni8hant/ecommerce | 1633de398a1aa0a3b5637a3facda7d364aa18a21 | 420b33a309f2c308e910a812abdbd61a6192fdd9 | refs/heads/master | 2022-10-25T04:50:35.742463 | 2020-06-14T14:21:58 | 2020-06-14T14:21:58 | 270,327,325 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 477 | java | package com.nishant.ecommerce.service;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import org.springframework.validation.annotation.Validated;
import com.nishant.ecommerce.model.Order;
@Validated
public interface OrderService {
@NotNull
Iterable<Order> getAllOrders();
Order create(@NotNull(message = "The order cannot be null.") @Valid Order order);
void update(@NotNull(message = "The order cannot be null.") @Valid Order order);
}
| [
"nkumar@msewa.com"
] | nkumar@msewa.com |
299516fddd96b2398d3e43b16df116e853fc2cdc | 1578ce84debd8a1a6a0428317d2e0b2b58f04df2 | /proyecto-limpio-spring-master/src/main/java/ar/edu/unlam/tallerweb1/controladores/ControladorMensajes.java | 9c26f92403c064053068a68f650777800417ec53 | [] | no_license | nahuelpierotti/libreria | 53c500615db7ae56087ba67e066535f18ba88b9a | 19ce0c9226f498a5bba46e8cc19834c732a53e14 | refs/heads/master | 2023-01-29T22:51:08.762627 | 2020-12-10T14:07:45 | 2020-12-10T14:07:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,529 | java | package ar.edu.unlam.tallerweb1.controladores;
import java.util.ArrayList;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import ar.edu.unlam.tallerweb1.modelo.Mensaje;
import ar.edu.unlam.tallerweb1.servicios.ServicioMensaje;
@Controller
public class ControladorMensajes {
@Inject
private ServicioMensaje servicioMensaje;
@RequestMapping(path="/mensajes")
public ModelAndView verMensajes (HttpServletRequest request)
{
HttpSession session=request.getSession();
ArrayList<Mensaje> lista=(ArrayList<Mensaje>) session.getAttribute("mensajes");
ArrayList<Mensaje> mensajes_leidos=session.getAttribute("mensajes_leidos")!=null ? (ArrayList<Mensaje>)session.getAttribute("mensajes_leidos"):null;
int cant_mjes_no_leidos=servicioMensaje.consultarMensajesNoLeidosUsuario(lista);
if(mensajes_leidos!=null) {
servicioMensaje.actualizarListaMensajes(mensajes_leidos);
}
ModelMap modelo = new ModelMap();
modelo.put("lista_mensajes",lista);
modelo.put("no_leidos",cant_mjes_no_leidos);
return new ModelAndView("mensajes",modelo);
}
public ServicioMensaje getServicioMensaje() {
return servicioMensaje;
}
public void setServicioMensaje(ServicioMensaje servicioMensaje) {
this.servicioMensaje = servicioMensaje;
}
}
| [
"npie@unlam.edu.ar"
] | npie@unlam.edu.ar |
effa30d4e90230aa35ba9404733888186b7a7cf4 | e49472c183e11ae0169a7cd6832142e1e6b90467 | /SIF3InfraREST/sif3InfraCommon/src/sif3/infra/common/env/ops/DirectProviderEnvStoreOps.java | b7b403d32c98379736d315cd8430c1bc62e50943 | [
"Apache-2.0"
] | permissive | elo8/sif3-framework-java | 70d692aceb460d045d3ecae49df3fe86269e094b | 1ecf368707539efd6e31504557e0ad155bdb3c00 | refs/heads/master | 2021-01-18T13:45:09.478353 | 2014-06-10T01:25:17 | 2014-06-10T01:25:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 18,492 | java | /*
* DirectProviderEnvStoreOps.java
* Created: 20/02/2014
*
* Copyright 2014 Systemic Pty Ltd
*
* 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 sif3.infra.common.env.ops;
import java.util.List;
import sif3.common.CommonConstants;
import sif3.common.CommonConstants.AdapterType;
import sif3.common.exception.PersistenceException;
import sif3.common.model.EnvironmentKey;
import sif3.common.persist.model.SIF3Session;
import sif3.common.persist.service.SIF3SessionService;
import sif3.infra.common.env.types.ConsumerEnvironment;
import sif3.infra.common.env.types.ProviderEnvironment;
import sif3.infra.common.model.EnvironmentType;
import sif3.infra.common.model.EnvironmentTypeType;
import sif3.infra.common.model.InfrastructureServiceType;
import sif3.infra.common.model.InfrastructureServicesType;
import au.com.systemic.framework.utils.StringUtils;
/**
* This class implements operations required by a direct environment provider. They are quite distinct and therefore warrant having its own
* implementation.
*
* @author Joerg Huber
*
*/
public class DirectProviderEnvStoreOps extends AdapterBaseEnvStoreOperations
{
private SIF3SessionService service = new SIF3SessionService();
/**
* @param adapterFileNameWithoutExt The property file name for Store Operation class.
*/
public DirectProviderEnvStoreOps(String adapterFileNameWithoutExt)
{
super(adapterFileNameWithoutExt);
}
/**
* Check of an environment template for the given filename exists. TRUE: it exists, FALSE it doesn't.
*
* @param templateFileName The name of the environment template file to check for in template directory. This name must
* include the extension ".xml".
*
* @return TRUE: Environment Template exists. FALSE: The environment template for the given file name doen't exists.
*/
public boolean existEnvironmentTemplate(String templateFileName)
{
return existEnvironmentTemplate(templateFileName, AdapterType.ENVIRONMENT_PROVIDER, sif3.infra.common.env.types.EnvironmentInfo.EnvironmentType.DIRECT);
}
/**
* This method loads the given environment from the template store and returns it. If no such environment exists then null
* is returned.
*
* @param envFileName The name of the environment file to load from template directory. This name must include the extension ".xml".
*
* @return Null => Failed to load data due to some error. See error log for details.
*/
public EnvironmentType loadEnvironmentFromTemplate(String envFileName)
{
return loadTemplateEnvironmentData(envFileName, AdapterType.ENVIRONMENT_PROVIDER, sif3.infra.common.env.types.EnvironmentInfo.EnvironmentType.DIRECT);
}
/**
* Checks if an environment does already exists in the workstore for the given environmentKey.
*
* @param environmentKey solutionID Mandatory, applicationKey Mandatory, userToken Optional, instanceID Optional:
*
* @return Returns true if an environment does already exist, which means an existing session is available.
*
* @throws IllegalArgumentException Any of the mandatory parameters is null or empty.
* @throws PersistenceException Could not access the underlying workstore.
*/
public boolean existEnvInWorkstore(EnvironmentKey environmentKey) throws IllegalArgumentException, PersistenceException
{
return service.getSessionBySolutionAppkeyUserInst(environmentKey, CommonConstants.AdapterType.ENVIRONMENT_PROVIDER) != null;
}
/**
* This method loads the environment for a the workstore. Before it is loaded it checks if it does already exist. If it
* doesn't then null is returned, otherwise the environment is returned. Note if it doesn't exist it WON'T create it.
* To create the environment from a template then the 'createAndStoreEnvIronment(...)' method in this class must be called.
*
* @param environmentKey solutionID Mandatory, applicationKey Mandatory, userToken Optional, instanceID Optional
* @param useSecured TRUE => Indicates that HTTPS end-points shall be returned. FALSE => Return HTTP end-points if available
*
* @return see Desc.
*
* @throws IllegalArgumentException Any of the mandatory parameters is null or empty.
* @throws PersistenceException Could not access the underlying workstore.
*/
public EnvironmentType loadEnvironmentFromWorkstore(EnvironmentKey environmentKey, boolean useSecured) throws IllegalArgumentException, PersistenceException
{
SIF3Session session = loadAndUpdateSession(environmentKey, useSecured);
if (session != null)
{
return loadEnvironmentFromString(session.getEnvironmentXML());
}
return null;
}
/**
* This method will load a SIF3 Session from the workstore and update it with the latest values form the template if needed. The updated
* values are then stored back to the work store and the final session is returned. If there is no known session in the workstore for the
* for the given session token then null is returned.
*
* @param sessionToken The sessionToken for which the SIF3 session shall be loaded, updated and returned.
* @param useSecured TRUE => Indicates that HTTPS end-points shall be returned. FALSE => Return HTTP end-points if available
*
* @return See Desc.
*
* @throws IllegalArgumentException sessionToken is null or empty.
* @throws PersistenceException Could not access the underlying workstore.
*/
public SIF3Session loadSessionFromWorkstore(String sessionToken, boolean useSecured) throws IllegalArgumentException, PersistenceException
{
if (StringUtils.isEmpty(sessionToken))
{
throw new IllegalArgumentException("sessionToken is null or empty. Cannot retrive environment/session for this session token.");
}
SIF3Session sif3Session = getSIF3SessionBySessionToken(sessionToken,AdapterType.ENVIRONMENT_PROVIDER, service);
if (sif3Session != null)
{
ProviderEnvironment envInfo = (ProviderEnvironment) getEnvironmentStore().getEnvironment();
updateSessionInfo(sif3Session, envInfo, useSecured);
}
return sif3Session;
}
/**
* This method takes the inputEnv and uses its data to create a new full environment and associated session. The reminder of the
* environment data is read from the template directory (environment services and permissions). A SessionToken and Environment ID
* is also created before the final environment created and stored. The input environment is modified before the final
* environment is returned. It is expected that the final returned environment is a full environment with all applicable
* infrastructure end-points, ACLs, environmentID, sessionToken etc that is applicable for the context (brokered vs direct).
* If the environment cannot be created in the environment store then the error is logged and null is returned.<br/><br/>
*
* NOTE:<br/>
* If an environment does already exist for the given input environment then that environment is returned and no new one
* is created.
*
* @param inputEnv The environment as provided by a environment provider (brokered) or the consumer (direct - in this case
* is a cut-down version with minimal data as specified in the SIF3 spec).
* @param useSecured TRUE => Indicates that HTTPS end-points shall be returned. FALSE => Return HTTP end-points if available
*
* @return The new Environment that has been created based on the inputEnv parameter and the context.
*/
public EnvironmentType createEnvironmentAndSession(EnvironmentType inputEnv, boolean useSecured)
{
SIF3Session sif3Session = createSession(inputEnv, useSecured);
if (sif3Session != null) //we are all good
{
return loadEnvironmentFromString(sif3Session.getEnvironmentXML());
}
else
{
return null; // error already logged
}
}
/**
* The same behaviour as the createEnvironmentAndSession() method except that the returned value is a SIF3 Session
* where the environment is returned as an XML string value in the SIF3Session.environmentXML property.
*
* @param inputEnv The environment as provided by a environment provider (brokered) or the consumer (direct - in this case
* is a cut-down version with minimal data as specified in the SIF3 spec).
* @param useSecured TRUE => Indicates that HTTPS end-points shall be returned. FALSE => Return HTTP end-points if available
*
* @return A SIF3 Session object with all values populated that are relevant to the newly created session.
*/
public SIF3Session createSession(EnvironmentType inputEnv, boolean useSecured)
{
if ((inputEnv == null) || (inputEnv.getApplicationInfo() == null))
{
logger.error("The consumer input environment is null or does not have the Application Info set. Environment cannot be created.");
return null;
}
if (StringUtils.isEmpty(inputEnv.getSolutionId()) || StringUtils.isEmpty(inputEnv.getApplicationInfo().getApplicationKey()))
{
logger.error("The application key and/or the solution id in the consumer input environment is null or empty. Environment cannot be created.");
return null;
}
ProviderEnvironment envInfo = (ProviderEnvironment)getEnvironmentStore().getEnvironment();
try
{
EnvironmentKey envKey = new EnvironmentKey(inputEnv.getSolutionId(), inputEnv.getApplicationInfo().getApplicationKey(), inputEnv.getUserToken(), inputEnv.getInstanceId());
SIF3Session sif3Session = loadAndUpdateSession(envKey, useSecured);
if (sif3Session != null) // Session exists. All done => return it.
{
logger.info("SIF3 Session for "+envInfo.getEnvironmentName()+" exists already. Simply updated connector URLs, ACLs etc if needed and return it and do not create it again.");
return sif3Session;
}
// If we get here then we don't have an environment, yet => create and store it
EnvironmentType environment = loadEnvironmentFromTemplate(envInfo.getTemplateXMLFileName());
if (environment == null) // does not exist in template directory. we cannot create it.
{
return null; // error already logged.
}
//TODO: JH - Check if inputEnv parameters match the environment and environment Template parameter!
// SolutionID from Template must match inputEnv.SolutionId; env.ApplicationKey must match inputEnv.ApplKey etc
// Create a session the environment in the store.
sif3Session = service.createNewSession(envKey, CommonConstants.AdapterType.ENVIRONMENT_PROVIDER);
if (sif3Session != null) // all good
{
// Now we have a session token and a environmentID. Store them in the environment.
environment.setSessionToken(sif3Session.getSessionToken());
environment.setId(sif3Session.getEnvironmentID());
// Other important values can be taken from the input environment. SolutionId should be in the template, so no need to
// use it from the inputEnv. But the following values need to be used
environment.setApplicationInfo(inputEnv.getApplicationInfo()); // this has the application key
environment.setConsumerName(inputEnv.getConsumerName());
environment.setType(EnvironmentTypeType.DIRECT); // IT is a direct environment, so set it accordingly
environment.setUserToken(inputEnv.getUserToken());
environment.setInstanceId(inputEnv.getInstanceId());
updateConnectorURLs(environment, envInfo, useSecured); //update URLs for infrastructure services.
// All is set now. We can update the session in the session store with the final values.
sif3Session.setPassword(envInfo.getPassword());
sif3Session.setAdapterName(inputEnv.getConsumerName());
if (storeEnvDataToWorkstore(sif3Session, environment, service))
{
return sif3Session;
}
else
{
return null; // error already logged
}
}
else
{
return null; // error already logged
}
}
catch (Exception ex) // really should only be PersistenceException or IllegarArgumentException
{
// errors should already be logged. Just return null as environment
return null;
}
}
/**
* This removes the environment data stored in the environment store. This operation should be used with care! A deletion
* of an environment means that it is no longer recoverable and a consumer/provider can no longer connect to the
* environment because the information relating to that environment are lost for good! A loss of an environment also means
* a loss of all data that relate to an environment such as SIF events, responses etc. All things that are potentially
* stored in queues.
*
* @param environmentID Uniquely identifies the environment to be removed.
*
* @return TRUE: Operation successful. FALSE: Error occurred. Session might not be removed! See error log for details.
*/
public boolean removeEnvFromWorkstoreByEnvID(String environmentID)
{
return removeEnvFromWorkstoreByEnvID(environmentID, AdapterType.ENVIRONMENT_PROVIDER, service);
}
/**
* As above but deletion occurs based on environment ID.
*
* @param sessionToken Uniquely identifies the environment to be removed.
*
* @return TRUE: Operation successful. FALSE: Error occurred. Session might not be removed! See error log for details.
*/
public boolean removeEnvFromWorkstoreBySessionToken(String sessionToken)
{
return removeEnvFromWorkstoreBySessionToken(sessionToken, AdapterType.ENVIRONMENT_PROVIDER, service);
}
/*---------------------*/
/*-- Private Methods --*/
/*---------------------*/
/*
* This method will attempt to load an existing session from the workstore and then update the XML with the latest template values
* such as connector URLSs, ACLs etc that may have changed since the last time the session was loaded. The changes are stored back to
* the session store and the updated session is returned.
* If no session exists to start of with then null is returned.
*/
private SIF3Session loadAndUpdateSession(EnvironmentKey environmentKey, boolean useSecured) throws IllegalArgumentException, PersistenceException
{
ProviderEnvironment envInfo = (ProviderEnvironment)getEnvironmentStore().getEnvironment();
SIF3Session sif3Session = service.getSessionBySolutionAppkeyUserInst(environmentKey, CommonConstants.AdapterType.ENVIRONMENT_PROVIDER);
if (sif3Session != null) // Session exists. May need to update some values
{
updateSessionInfo(sif3Session, envInfo, useSecured);
return sif3Session;
}
return null;
}
private void updateSessionInfo(SIF3Session sif3Session, ProviderEnvironment envInfo, boolean useSecured)
{
if (sif3Session != null) // Session exists. May need to update some values
{
EnvironmentType environment = loadEnvironmentFromString(sif3Session.getEnvironmentXML());
if (environment != null) // all fine
{
// We may need to replace infrastructure URLs depending on how the environment is used (http, https).
// Lookup the template this provider supports and replace things as required.
EnvironmentType templateEnv = loadEnvironmentFromTemplate(envInfo.getTemplateXMLFileName());
if (templateEnv != null)
{
// Ensure that all ACLs are updated.
reloadServiceInfo(environment, templateEnv);
// Update infrastructure service URIs in case they have changed.
environment.setInfrastructureServices(templateEnv.getInfrastructureServices());
updateConnectorURLs(environment, envInfo, useSecured);
// Store the updated values. Note even if this fails it is no drama as it will be recreated the next
// time a consumer connects.
storeEnvDataToWorkstore(sif3Session, environment, service);
}
else
{
logger.error("No environment template found for "+envInfo.getTemplateXMLFileName()+". Cannot update connector URLs.");
}
}
// else (no XML with session) error already logged. This would be a strange setup. Should not really happen!
}
}
private void updateConnectorURLs(EnvironmentType environment, ProviderEnvironment envInfo, boolean useSecured)
{
String baseURIStr = useSecured ? envInfo.getSecureConnectorBaseURI().toString() : envInfo.getConnectorBaseURI().toString();
InfrastructureServicesType infraServices = environment.getInfrastructureServices();
if (infraServices != null)
{
List<InfrastructureServiceType> services = infraServices.getInfrastructureService();
for (InfrastructureServiceType infraService : services)
{
String connectorURL = infraService.getValue();
// Remove trailing '/' if it is there
if (connectorURL.endsWith("/"))
{
connectorURL = connectorURL.substring(0, connectorURL.length()-1);
}
//check if it has a leading '/'
boolean hasSlash = connectorURL.startsWith("/");
// Search for service called "environment" and also add the environment ID
if (infraService.getName().value().equals(ConsumerEnvironment.ConnectorName.environment.toString()))
{
infraService.setValue(baseURIStr+(hasSlash?"":"/")+connectorURL+"/"+environment.getId());
}
else
{
infraService.setValue(baseURIStr+(hasSlash?"":"/")+connectorURL);
}
}
}
else
{
logger.error("Infrastructure Services not defined in environment template "+envInfo.getTemplateXMLFileName()+". This must be set.");
}
}
private void reloadServiceInfo(EnvironmentType environment, EnvironmentType templEnv)
{
environment.setProvisionedZones(templEnv.getProvisionedZones());
}
}
| [
"joerg.huber@systemic.com.au"
] | joerg.huber@systemic.com.au |
940f08e4a8c2e6f4ec815166f1fc987c92283edd | be6df835c3513afa0c83cadb5974f468c81a0004 | /ssh-module-common/src/main/java/com/xh/ssh/web/common/tool/LogTool.java | 316aa647275ec92bf83c4c0c74baee8d91bfadea | [] | no_license | deeplhub/ssh-module-parent | 8275f3067d0c40269bc82bd91ce285b050b9bfc9 | dfd6d722e488d6cd25213f00138d4e644d924b18 | refs/heads/master | 2021-10-09T08:26:49.926036 | 2018-12-24T07:20:44 | 2018-12-24T07:20:44 | 153,549,964 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,400 | java | package com.xh.ssh.web.common.tool;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <b>Title: 日志</b>
* <p>Description: </p>
*
* @author H.Yang
* @email xhaimail@163.com
* @date 2018年8月1日
*/
public class LogTool {
private static Logger LOG4J_LOGGER = null;
private static org.slf4j.Logger SLF4J_LOGGER = null;
private static final <T> void apache_init(Class<T> clazz) {
LOG4J_LOGGER = LogManager.getLogger(clazz);
}
private static final <T> void slf4j_init(Class<T> clazz) {
SLF4J_LOGGER = LoggerFactory.getLogger(clazz);
}
/**
* <b>Title: 普通打印</b>
* <p>Description: org.apache.log4j.Logger</p>
*
* @author H.Yang
*
* @param clazz
* @param message
*/
public static <T> void info(Class<T> clazz, Object message) {
LogTool.apache_init(clazz);
LOG4J_LOGGER.info(message);
}
/**
* <b>Title: 普通打印</b>
* <p>Description: org.apache.log4j.Logger</p>
*
* @author H.Yang
*
* @param clazz
* @param message
*/
public static <T> void debug(Class<T> clazz, Object message) {
LogTool.apache_init(clazz);
LOG4J_LOGGER.debug(message);
}
/**
* <b>Title: 普通打印</b>
* <p>Description: org.apache.log4j.Logger</p>
*
* @author H.Yang
*
* @param clazz
* @param message
*/
public static <T> void warn(Class<T> clazz, Object message) {
LogTool.apache_init(clazz);
LOG4J_LOGGER.warn(message);
}
/**
* <b>Title: 普通打印</b>
* <p>Description: org.apache.log4j.Logger</p>
*
* @author H.Yang
*
* @param clazz
* @param message
*/
public static <T> void error(Class<T> clazz, Object message) {
LogTool.apache_init(clazz);
LOG4J_LOGGER.error(message);
}
/**
* <b>Title: 打印平等线</b>
* <p>Description: org.apache.log4j.Logger</p>
*
* @author H.Yang
*
* @param clazz
* @param message
* @param isPrintEqualLine
*/
public static <T> void info(Class<T> clazz, Object message, boolean isPrintEqualLine) {
LogTool.apache_init(clazz);
if (isPrintEqualLine) {
if (LOG4J_LOGGER.isInfoEnabled()) {
LOG4J_LOGGER.info("===========================================================================\n" + message);
}
} else {
if (LOG4J_LOGGER.isDebugEnabled()) {
LOG4J_LOGGER.info(message);
}
}
}
/**
* <b>Title: 打印平等线</b>
* <p>Description: org.apache.log4j.Logger</p>
*
* @author H.Yang
*
* @param clazz
* @param message
* @param isPrintEqualLine
*/
public static <T> void debug(Class<T> clazz, Object message, boolean isPrintEqualLine) {
LogTool.apache_init(clazz);
if (isPrintEqualLine) {
if (LOG4J_LOGGER.isInfoEnabled()) {
LOG4J_LOGGER.debug("===========================================================================\n" + message);
}
} else {
if (LOG4J_LOGGER.isDebugEnabled()) {
LOG4J_LOGGER.debug(message);
}
}
}
/**
* <b>Title: 打印平等线</b>
* <p>Description: org.apache.log4j.Logger</p>
*
* @author H.Yang
*
* @param clazz
* @param message
* @param isPrintEqualLine
*/
public static <T> void warn(Class<T> clazz, Object message, boolean isPrintEqualLine) {
LogTool.apache_init(clazz);
if (isPrintEqualLine) {
if (LOG4J_LOGGER.isInfoEnabled()) {
LOG4J_LOGGER.warn("===========================================================================\n" + message);
}
} else {
if (LOG4J_LOGGER.isDebugEnabled()) {
LOG4J_LOGGER.warn(message);
}
}
}
/**
* <b>Title: 打印平等线</b>
* <p>Description: org.apache.log4j.Logger</p>
*
* @author H.Yang
*
* @param clazz
* @param message
* @param isPrintEqualLine
*/
public static <T> void error(Class<T> clazz, Object message, boolean isPrintEqualLine) {
LogTool.apache_init(clazz);
if (isPrintEqualLine) {
if (LOG4J_LOGGER.isInfoEnabled()) {
LOG4J_LOGGER.error("===========================================================================\n" + message);
}
} else {
if (LOG4J_LOGGER.isDebugEnabled()) {
LOG4J_LOGGER.error(message);
}
}
}
/**
* <b>Title: 打印异常</b>
* <p>Description: </p>
*
* @author H.Yang
*
* @param clazz
* @param e
*/
public static <T> void error(Class<T> clazz, Object message, Exception e) {
LogTool.apache_init(clazz);
LOG4J_LOGGER.error(message + " " + LogTool.getExceptionStr(e));
}
/**
* <b>Title: 打印异常</b>
* <p>Description: </p>
*
* @author H.Yang
*
* @param clazz
* @param e
*/
public static <T> void error(Class<T> clazz, Exception e) {
LogTool.apache_init(clazz);
LOG4J_LOGGER.error(LogTool.getExceptionStr(e));
}
/**
* <b>Title: 把异常信息转换成字符串</b>
* <p>Description: </p>
*
* @author H.Yang
*
* @param e
* @return
*/
private static String getExceptionStr(Exception e) {
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
e.printStackTrace(writer);
StringBuffer buffer = stringWriter.getBuffer();
return buffer.toString();
}
/**
* <b>Title: 占位符-打印日志 </b>
* <p>Description: org.slf4j.Logger</p>
*
* @author H.Yang
*
* @param clazz
* @param format 占位符
* @param arg
*/
public static <T> void info(Class<T> clazz, String format, Object arg) {
LogTool.slf4j_init(clazz);
SLF4J_LOGGER.info(format, arg);
}
/**
* <b>Title: 占位符-打印日志 </b>
* <p>Description: org.slf4j.Logger</p>
*
* @author H.Yang
*
* @param clazz
* @param format
* @param arg1
* @param arg2
*/
public static <T> void info(Class<T> clazz, String format, Object arg1, Object arg2) {
LogTool.slf4j_init(clazz);
SLF4J_LOGGER.info(format, arg1, arg2);
}
/**
* <b>Title: 占位符-打印日志 </b>
* <p>Description: org.slf4j.Logger</p>
*
* @author H.Yang
*
* @param clazz
* @param format
* @param argArray
*/
public static <T> void info(Class<T> clazz, String format, Object[] argArray) {
LogTool.slf4j_init(clazz);
SLF4J_LOGGER.info(format, argArray);
}
}
| [
"xhaimail@163.com"
] | xhaimail@163.com |
27bbe370bf2943967bf4c2a1f87e04f52ea57618 | 738dcee82fa1a2268e442bd47e81fada22dda142 | /licensing/src/main/java/com/franklin/licensing/action/MockDataLoaderActionBean.java | 9139210daea3d3367136369e43ab0980c36f5a29 | [
"MIT"
] | permissive | jseger/licensing | dc3b6d7bb5cbe5cd962f5863d6431441df038e53 | c824b0059758ddbf9e902067080daf05f1f57318 | refs/heads/master | 2020-05-17T19:57:33.933038 | 2013-11-25T14:39:04 | 2013-11-25T14:39:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 895 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.franklin.licensing.action;
import com.franklin.licensing.entities.Customer;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
public class MockDataLoaderActionBean extends BaseActionBean {
@DefaultHandler
public Resolution loadMockUser() throws Exception {
if (super.customerRepository.findByEmail("email@email.com") == null) {
Customer cust = new Customer();
cust.setName("FirstName LastName");
cust.setEmail("email@email.com");
super.customerRepository.save(cust);
}
else {
}
return new RedirectResolution(CustomerActionBean.class);
}
}
| [
"jesses@hawkridgesys.com"
] | jesses@hawkridgesys.com |
61226fad6e30b4e1d2759ae5a8a898b03173f6b1 | 426beb604e3a11f995712b90cd0d63d114b49568 | /Team2_Model2 MVC_BitMarket/src/kr/or/bit/service/admin/PurchaseList.java | 4a47f493be6acec70b26432241c7d7d201c2e211 | [] | no_license | taepd/2_team2 | 07e564d7a2007b0bb9694ae7903ebc6039c63dcc | 1bce84cc87bcf396b6660b58fa9e5a49e33d23b4 | refs/heads/master | 2021-05-19T04:00:10.163305 | 2020-10-18T11:41:30 | 2020-10-18T11:41:30 | 251,519,126 | 2 | 1 | null | 2020-04-30T09:15:32 | 2020-03-31T06:29:49 | CSS | UTF-8 | Java | false | false | 2,095 | java | package kr.or.bit.service.admin;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.or.bit.action.Action;
import kr.or.bit.action.ActionForward;
import kr.or.bit.dao.Bitdao;
import kr.or.bit.dto.Board;
import kr.or.bit.dto.BoardCt_Join;
import kr.or.bit.dto.Notice;
public class PurchaseList implements Action{
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) {
ActionForward forward = null;
String ps = request.getParameter("ps"); //pagesize
String cp = request.getParameter("cp"); //current page
String searchContent = request.getParameter("searchContent");
String ctname = request.getParameter("ctname");
//List 페이지 처음 호출 ...
if(ps == null || ps.trim().equals("")){
//default 값 설정
ps = "5"; //5개씩
}
if(cp == null || cp.trim().equals("")){
//default 값 설정
cp = "1"; // 1번째 페이지 보겠다
}
int pagesize = Integer.parseInt(ps);
int cpage = Integer.parseInt(cp);
int pagecount=0;
try {
Bitdao dao = new Bitdao();
List<BoardCt_Join> purchaselist = dao.getBoardSearchList(cpage, pagesize, searchContent, ctname);
request.setAttribute("purchaselist", purchaselist);
int totalpurchasecount = dao.getTotalBoardCount();
if(totalpurchasecount % pagesize == 0){
pagecount = totalpurchasecount / pagesize; // 20 << 100/5
}else{
pagecount = (totalpurchasecount / pagesize) + 1;
}
request.setAttribute("searchContent", searchContent);
request.setAttribute("ctname", ctname);
request.setAttribute("pagesize", pagesize);
request.setAttribute("cpage", cpage);
request.setAttribute("pagecount", pagecount);
request.setAttribute("totalpurchasecount", totalpurchasecount);
forward = new ActionForward();
forward.setRedirect(false); //forward
forward.setPath("/WEB-INF/views/admin/PurchaseList.jsp");
}catch (Exception e) {
System.out.println(e.getMessage());
}
return forward;
}
}
| [
"taepd1@gmail.com"
] | taepd1@gmail.com |
0d90a535f76425b12b2a1a44bf6136f9b3796934 | 95aafb88dd041c1bf41a500179507a9e4a82de8a | /src/main/java/ch/unil/doplab/geodabs/motif/BruteForce.java | ad78f3eec30c769bcf2385371c27aaa9bbfd13e4 | [] | no_license | geoHeil/geodabs | f109ed4374989419a76d41942d20836fac234b04 | 8b698c19a72868a99979c97368efb960c9b130f0 | refs/heads/master | 2020-06-11T20:06:33.910603 | 2019-01-17T12:57:28 | 2019-01-17T12:57:28 | 194,070,100 | 1 | 0 | null | 2019-06-27T09:56:45 | 2019-06-27T09:56:45 | null | UTF-8 | Java | false | false | 1,112 | java | package ch.unil.doplab.geodabs.motif;
import ch.unil.doplab.geodabs.distance.DFD;
import ch.unil.doplab.geodabs.model.Point;
import static ch.unil.doplab.geodabs.distance.DFD.distance;
import java.util.Arrays;
public class BruteForce {
public static MotifPair execute(Point[] ta, Point[] tb, int e) {
final int s = ta.length;
final int t = tb.length;
double bsf = Double.MAX_VALUE;
MotifPair bpair = null;
for (int i = 0; i <= s - e; i++) {
for (int j = 0; j <= t - e; j++) {
for (int ie = i + e; ie <= s; ie++) {
for (int je = j + e; je <= t; je++) {
Point[] ps = Arrays.copyOfRange(ta, i, ie);
Point[] qs = Arrays.copyOfRange(tb, j, je);
double d = DFD.distance(ps, qs);
if (d < bsf) {
bsf = d;
bpair = new MotifPair(i, j, ie, je, bsf);
}
}
}
}
}
return bpair;
}
}
| [
"bchapuis@gmail.com"
] | bchapuis@gmail.com |
7d66ca8ca7e3f3d4e398df30a97e9327127d9d1f | 6f1a773e816a4e54742cffe74bc883ed33857de8 | /finalworkshop/src/main/java/pl/atos/finalworkshop/city/CityServiceInterface.java | 9405cb3a3e681e6fd632046c360c8e0674e7197d | [] | no_license | pietrzykowski1995/SaleFinder | f1eda51d317c892ae66f0c1019ddba710278d16d | 48323bae8e7cfa01273c2b76ac6cdf1200cf939e | refs/heads/master | 2020-06-24T00:18:45.446634 | 2019-09-26T12:19:44 | 2019-09-26T12:19:44 | 196,042,301 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 210 | java | package pl.atos.finalworkshop.city;
import java.util.List;
public interface CityServiceInterface {
List<City> finById(Long id);
City findFirstByName(String name);
void save(String cityName);
}
| [
"pietrzykowski1995@gmail.com"
] | pietrzykowski1995@gmail.com |
c2cb2420b22429245ab41247c95ed7ad2c16604a | 3cef13e230a38ffc913d9e30f34568f2d2e36ae3 | /src/main/java/com/hackday/sns_timeline/searchMember/domain/dto/SearchMemberDto.java | 79d25f57e1fd9839e51446e03afdf924fdfa1976 | [] | no_license | KimYunsang-v/sns_timeline | 843fcd9fc3cb587865eaba4fdaf27a66db95c120 | ae3a1ee19a42ccae2d3f5ec3501d4b8611d8c73c | refs/heads/master | 2022-11-12T19:10:28.469583 | 2020-07-07T13:44:38 | 2020-07-07T13:44:38 | 266,711,299 | 0 | 0 | null | 2020-05-31T12:44:16 | 2020-05-25T07:20:34 | Java | UTF-8 | Java | false | false | 356 | java | package com.hackday.sns_timeline.searchMember.domain.dto;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class SearchMemberDto {
private long userId;
private String search;
private int page;
}
| [
"qwdbstkd@naver.com"
] | qwdbstkd@naver.com |
55a418db88ae735edb96bdbcbeb020dc9ea7b78f | 7fb21e94e46a24a1b55d66da62c10d74f3a2b84e | /BootMVCMealPlanning/src/test/java/com/skilldistillery/mealplanning/BootMvcMealPlanningApplicationTests.java | 9a6be6e19e058968d237a449706a762b09874b15 | [] | no_license | eclau29/JPACRUDProject | 56347ca789b6763bbbfe87df8151678fc0ccf74d | a76864d7fdd65658a812c7c0ebff11ae95531bb1 | refs/heads/master | 2020-06-14T22:16:27.372985 | 2019-07-15T14:49:51 | 2019-07-15T14:49:51 | 195,137,327 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 362 | java | package com.skilldistillery.mealplanning;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class BootMvcMealPlanningApplicationTests {
@Test
public void contextLoads() {
}
}
| [
"emilylau@Brucebs-MBP-2.hsd1.co.comcast.net"
] | emilylau@Brucebs-MBP-2.hsd1.co.comcast.net |
df448eb23c11467e4022b2eba0b5008bce74ee2a | ac09a467d9981f67d346d1a9035d98f234ce38d5 | /leetcode/src/main/java/org/leetcode/problems/_000125_ValidPalindrome.java | c12a37de60e1112778e7322db53f282fb8aa96ff | [] | no_license | AlexKokoz/leetcode | 03c9749c97c846c4018295008095ac86ae4951ee | 9449593df72d86dadc4c470f1f9698e066632859 | refs/heads/master | 2023-02-23T13:56:38.978851 | 2023-02-12T21:21:54 | 2023-02-12T21:21:54 | 232,152,255 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 670 | java | package org.leetcode.problems;
/**
*
* EASY
*
* @author Alexandros Kokozidis
*
*/
public class _000125_ValidPalindrome {
public boolean isPalindrome(String s) {
int n = s.length();
int lo = 0;
int hi = n - 1;
while (lo < hi) {
while (lo < n && !isAlphanumeric(s.charAt(lo)))
lo++;
while (hi >= 0 && !isAlphanumeric(s.charAt(hi)))
hi--;
if (lo >= hi)
break;
if (Character.toLowerCase(s.charAt(lo)) != Character.toLowerCase(s.charAt(hi)))
return false;
hi--;
lo++;
}
return true;
}
static boolean isAlphanumeric(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
}
}
| [
"alexandros.kokozidis@gmail.com"
] | alexandros.kokozidis@gmail.com |
42210d10a16db0343fa02a1d20dfdecdd0a2f152 | 40edf01e42b1197da27fe270b563398ab01b3d60 | /spring-boot/src/main/java/org/springframework/boot/convert/LenientStringToEnumConverterFactory.java | c5e028e189eb54d6bfe99ff6e22690be099e741c | [] | no_license | hgq0916/spring-sourcecode-study | 7b9551f8df2452013b86e2b190eeb511b531f28c | 0530475ab6c19e12059ec9de13928bc79b499189 | refs/heads/master | 2023-04-10T17:54:07.315336 | 2021-04-17T05:30:24 | 2021-04-17T05:30:24 | 356,565,710 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,145 | java | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.convert;
/**
* Converts from a String to a {@link Enum} with lenient conversion rules.
* Specifically:
* <ul>
* <li>Uses a case insensitive search</li>
* <li>Does not consider {@code '_'}, {@code '$'} or other special characters</li>
* <li>Allows mapping of {@code "false"} and {@code "true"} to enums {@code ON} and
* {@code OFF}</li>
* </ul>
*
* @author Phillip Webb
*/
final class LenientStringToEnumConverterFactory extends LenientObjectToEnumConverterFactory<String> {
}
| [
"hugangquan@ruigushop.com"
] | hugangquan@ruigushop.com |
66784834b07739fe2b804e472d43298314473966 | 44ae1ffbb6e9ec22c65664af0f1ed4a504bb8455 | /trabalho/Heap.java | 5cadb51c53c66c2d0a4d2a09a8069a9848511e36 | [] | no_license | mariaclaraabreu/problema-da-transportadora | 920ec82b036b9660811042b60f36d05a08a56cb1 | 2e90eeeaf58ebc74217cc8aee2a5f9bd04cd58ce | refs/heads/master | 2020-06-26T07:39:23.054398 | 2020-06-18T21:41:10 | 2020-06-18T21:41:10 | 199,573,988 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,290 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package trabalho.pkg1;
/**
*
* @author Maria Clara
*/
public class Heap {
private int[] lista = new int[100];
private int tam;
public void subir(int i) {
int j = i / 2;
if (j >= 0) {
if (lista[i] > lista[j]) {
int aux = lista[i];
lista[i] = lista[j];
lista[j] = aux;
subir(j);
}
}
}
public void descer(int i) {
int j;
if (i == 0) {
j = 1;
} else {
j = 2 * i;
}
if (j <= tam) {
if (j < tam) {
if (lista[j + 1] > lista[j]) {
j = j + 1;
}
}
if (lista[i] < lista[j]) {
int aux = lista[i];
lista[i] = lista[j];
lista[j] = aux;
this.descer(j);
}
}
}
public void inserir(int x) {
if (tam < lista.length) {
lista[tam] = x;
tam++;
this.subir(tam - 1);
} else {
System.out.println("ERRO! Lista cheia.");
}
}
public int remover() {
if (tam == 0) {
System.out.println("ERRO! Lista vazia.");
return -1;
} else {
int x = lista[0];
lista[0] = lista[tam - 1];
tam--;
this.descer(0);
return x;
}
}
}
/*
* 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 trabalho.pkg1;
/**
*
* @author Maria Clara
*/
public class Heap {
private int[] lista = new int[100];
private int tam;
public void subir(int i) {
int j = i / 2;
if (j >= 0) {
if (lista[i] > lista[j]) {
int aux = lista[i];
lista[i] = lista[j];
lista[j] = aux;
subir(j);
}
}
}
public void descer(int i) {
int j;
if (i == 0) {
j = 1;
} else {
j = 2 * i;
}
if (j <= tam) {
if (j < tam) {
if (lista[j + 1] > lista[j]) {
j = j + 1;
}
}
if (lista[i] < lista[j]) {
int aux = lista[i];
lista[i] = lista[j];
lista[j] = aux;
this.descer(j);
}
}
}
public void inserir(int x) {
if (tam < lista.length) {
lista[tam] = x;
tam++;
this.subir(tam - 1);
} else {
System.out.println("ERRO! Lista cheia.");
}
}
public int remover() {
if (tam == 0) {
System.out.println("ERRO! Lista vazia.");
return -1;
} else {
int x = lista[0];
lista[0] = lista[tam - 1];
tam--;
this.descer(0);
return x;
}
}
}
| [
"mclara.engsoftware@gmail.com"
] | mclara.engsoftware@gmail.com |
ce413d70332c15551ab63a4ef7e7bdaef70085e0 | fec4c1754adce762b5c4b1cba85ad057e0e4744a | /jf-base/src/main/java/com/jf/entity/CashTransferExtExample.java | 7c3200dd87c0bec5caf02b5517edd7e917d1123e | [] | no_license | sengeiou/workspace_xg | 140b923bd301ff72ca4ae41bc83820123b2a822e | 540a44d550bb33da9980d491d5c3fd0a26e3107d | refs/heads/master | 2022-11-30T05:28:35.447286 | 2020-08-19T02:30:25 | 2020-08-19T02:30:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,244 | java | package com.jf.entity;
import com.jf.common.ext.query.QueryObject;
import com.jf.common.ext.util.StrKit;
public class CashTransferExtExample extends CashTransferExample{
private QueryObject queryObject;
public QueryObject getQueryObject() {
if(queryObject == null) queryObject = new QueryObject();
return queryObject;
}
public CashTransferExtExample fill(){
if(queryObject == null) return this;
if(StrKit.notBlank(queryObject.getSortString())){
setOrderByClause(queryObject.getSortString());
}
if(queryObject.getLimitSize() > 0){
setLimitStart(0);
setLimitSize(queryObject.getLimitSize());
}
return this;
}
public CashTransferExtExample fillPage(){
if(queryObject == null) queryObject = new QueryObject();
if(StrKit.notBlank(queryObject.getSortString())){
setOrderByClause(queryObject.getSortString());
}
setLimitStart(queryObject.getLimitStart());
setLimitSize(queryObject.getPageSize());
return this;
}
@Override
public CashTransferExtCriteria createCriteria() {
CashTransferExtCriteria criteria = new CashTransferExtCriteria();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
public class CashTransferExtCriteria extends Criteria{
}
}
| [
"397716215@qq.com"
] | 397716215@qq.com |
64bd71fbae82eb5d412bd373d0d470c936f55e83 | 0fc2447d43477f21b1394382d9e822bd55717981 | /Backend/src/main/java/com/niit/models/User.java | 39f5b8e1cd754960c51cc0512bc36e931cbe66fb | [] | no_license | Sab15011994/backend | 282f93851d25720c042ffb651010aec4fa79ee76 | d73cb2bc06b557ee439a561ce70e2d038158a0bf | refs/heads/master | 2020-04-01T23:34:43.879476 | 2018-11-21T13:19:09 | 2018-11-21T13:19:09 | 153,764,457 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,353 | java | package com.niit.models;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
@Entity
public class User {
@Id
private String email;
private String password;
private boolean enabled;
@OneToOne(mappedBy="user",cascade=CascadeType.ALL)
private Authorities authorities;
@OneToOne(mappedBy="user",cascade=CascadeType.ALL)
private Customer customer;
@OneToMany(mappedBy="user")
private List<CartItem> cartItems;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Authorities getAuthorities() {
return authorities;
}
public void setAuthorities(Authorities authorities) {
this.authorities = authorities;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public List<CartItem> getCartItems() {
return cartItems;
}
public void setCartItems(List<CartItem> cartItems) {
this.cartItems = cartItems;
}
}
| [
"shahsaurabh769@gmail.com"
] | shahsaurabh769@gmail.com |
54fa3d0c5e198b11149c9ced1dce750c0265ec7b | 1edc657e20184f041a6bf8539a84f5c477beac52 | /src/test/java/flowctrl/integration/slack/SlackRealTimeMessagingClientTest.java | 0cfa55e5a621a4bfee17125cfccd8d7390992d7f | [
"MIT"
] | permissive | OvertimeNZ/java-slack-api | 52b1719907a1a2b96104cf3eb10d1bf3407ccd6f | cab254446718dd088fd2bcb81d5b13dd2755d4be | refs/heads/master | 2021-01-12T22:10:38.790969 | 2015-12-08T10:36:53 | 2015-12-08T10:36:53 | 47,602,532 | 1 | 0 | MIT | 2018-07-23T06:50:36 | 2015-12-08T06:13:16 | Java | UTF-8 | Java | false | false | 1,674 | java | package flowctrl.integration.slack;
import org.junit.Test;
import com.fasterxml.jackson.databind.JsonNode;
import flowctrl.integration.slack.rtm.Event;
import flowctrl.integration.slack.rtm.EventListener;
import flowctrl.integration.slack.rtm.ProxyServerInfo;
import flowctrl.integration.slack.rtm.SlackRealTimeMessagingClient;
public class SlackRealTimeMessagingClientTest {
private String token = "your slack web api token";
@Test
public void basicTest() {
SlackRealTimeMessagingClient realTimeMessagingClient = SlackClientFactory.createSlackRealTimeMessagingClient(token);
realTimeMessagingClient.addListener("hello", new HelloEventListener());
realTimeMessagingClient.addListener("message", new MessageEventListener());
realTimeMessagingClient.addListener(Event.MESSAGE, new EventListener() {
@Override
public void handleMessage(JsonNode message) {
// todo
}
});
realTimeMessagingClient.connect();
try {
Thread.sleep(60 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void proxyTest() {
String protocol = "https";
String proxyHost = "xxx.xxx.xxx.xxx";
int proxyPort = 1234;
ProxyServerInfo proxyServerInfo = new ProxyServerInfo(protocol, proxyHost, proxyPort);
SlackRealTimeMessagingClient realTimeMessagingClient = SlackClientFactory.createSlackRealTimeMessagingClient(token, proxyServerInfo);
realTimeMessagingClient.addListener("hello", new HelloEventListener());
realTimeMessagingClient.connect();
try {
Thread.sleep(60 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| [
"allbegray@gmail.com"
] | allbegray@gmail.com |
3ddbe5daeeeb22844d9a357c69b7239a5f01cf53 | 926a5cb0be8e8b78601a95fbb7507ba63ce2b745 | /src/Programa_Principal/Main.java | 6fcbdeff1de25a5f3d3c7805ecac2c6e002c1b11 | [] | no_license | facundoam/Greedy_PagoMinimoMoneda | 9bd8e68683734a7dc7541ab504e943c66e399505 | 3618ce0ab477762bf70fdfcf8eadac2d2748582c | refs/heads/master | 2021-01-10T12:09:59.049059 | 2016-03-30T19:48:03 | 2016-03-30T19:48:03 | 55,092,943 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 300 | java | /**
* @author Facundo Arias on 30/3/2016.
*/
package Programa_Principal;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
CambioMoneda a= new CambioMoneda();
a.calcularCambio(0.12f);
System.out.println(a.toString());
}
}
| [
"farias@facunotebook.argentina.ibm.com"
] | farias@facunotebook.argentina.ibm.com |
0161a4c95c7337190fe082fd4aebac214c89d933 | 068785ae51fb6a09d6499a410e16c1be0a9c39ed | /src/planner/heuristics/UnmetGoal.java | 7cd85d364ec381a831d1f37caa64d000deea5feb | [] | no_license | nguyenmv2/Artificial-Intelligence | dde50da45a9c1fdc898f45eb5733ea7f966d4fdf | 2618d5ba0fa9845134e4b31ddc1f8fb03434fa6a | refs/heads/master | 2020-12-30T10:36:48.233816 | 2015-09-10T15:13:38 | 2015-09-10T15:13:38 | 41,463,912 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 394 | java | package planner.heuristics;
import planner.core.PlanStep;
import planner.core.State;
import search.core.BestFirstHeuristic;
/**
* Created by nguye on 9/10/2015.
*/
public class UnmetGoal implements BestFirstHeuristic<PlanStep> {
@Override
public int getDistance(PlanStep node, PlanStep goal) {
return (node.getWorldState().unmetGoals(goal.getWorldState()).size());
}
}
| [
"nguyenm2@hendrix.edu"
] | nguyenm2@hendrix.edu |
b7d26e4f6d110317c22956fb32db8db91697fd5c | cecc84f39cfcd106d40333bfddd4f03afd9f41c7 | /creditGateway-service-api/src/main/java/com/zdmoney/credit/api/waimao3/service/Wm3_2102Service.java | 794c2c669660dcf599f68c2707ee875cb21d857c | [] | no_license | happyjianguo/gateway | e8b6e15f487a72abe6c0f441414ff47eab33a25e | a9936ad58dc40e3697e8c7bf747e17a5347adb41 | refs/heads/master | 2020-07-30T08:09:51.322415 | 2018-11-17T13:58:15 | 2018-11-17T13:58:15 | 210,148,823 | 0 | 1 | null | 2019-09-22T13:05:53 | 2019-09-22T13:05:53 | null | UTF-8 | Java | false | false | 1,240 | java | package com.zdmoney.credit.api.waimao3.service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import com.zdmoney.credit.common.annotate.FuncIdAnnotate;
import com.zdmoney.credit.common.vo.FuncResult;
import com.zdmoney.credit.framework.vo.wm3.input.WM3_2102Vo;
import com.zdmoney.credit.wm3Ws.service.Request;
/**
* 外贸3——放款申请结果查询接口
* @author 10098 2017年3月16日 上午10:46:53
*/
@Service
public class Wm3_2102Service extends Wm3BusinessService {
protected static Log log = LogFactory.getLog(Wm3_2102Service.class);
@FuncIdAnnotate(value = "wm3_2102", desc = "外贸3放款申请结果查询", voCls = WM3_2102Vo.class)
public FuncResult execute(WM3_2102Vo vo){
/** 封装请求参数 **/
Request request = this.getRequestVo();
/** 放款申请结果查询接口的编号 **/
request.setTxCode("2102");
/** 设定业务请求参数 **/
String content = JSONObject.toJSONString(vo);
request.setContent(content);
/** 调用外贸预审批单笔申请接口 **/
return this.search(request);
}
}
| [
"xiegl@asiainfo-sec.com"
] | xiegl@asiainfo-sec.com |
0f458eaa3646f8e04f6332c6a2373ad45235f714 | c3bc4d5842f6ef3b6d09505f202711f99603faf1 | /src/main/java/com/liceu/cars/services/CarServiceImpl.java | ac4722ec50c92750c025734a2eaef02d6cc21532 | [] | no_license | Zerronir/jdbc-servlet | 2067df2f4c155852ac3f9a27a81ba2455a2de1b2 | f1b8f7682093e12803692b63d3caee7b65240068 | refs/heads/master | 2023-01-07T23:50:54.179391 | 2020-11-09T18:39:04 | 2020-11-09T18:39:04 | 310,356,993 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 784 | java | package com.liceu.cars.services;
import com.liceu.cars.daos.Car;
import com.liceu.cars.daos.CarDAO;
import com.liceu.cars.daos.CarServiceAccess;
import java.util.List;
public class CarServiceImpl implements CarSerivce {
@Override
public List<Car> getAll() {
CarDAO cd = new CarServiceAccess();
List<Car> cars = cd.getAll();
return cars;
}
@Override
public boolean addCar(String marca, String modelo, String color, String km, String power) {
try {
Car c = new Car(0, marca, modelo, color, Integer.parseInt(km), Integer.parseInt(power));
CarDAO cd = new CarServiceAccess();
cd.addCar(c);
return true;
}catch (Exception e){
return false;
}
}
}
| [
"pqe0023@gmail.com"
] | pqe0023@gmail.com |
9316873bc550c467c6e26168f10e4dfd76c5e6b1 | 4b15e516d78b05a0ce9f7ba3dd19333eb4313aad | /src/main/java/com/example/demo/service/HystrixClientFallback.java | 2bdc0a3e819bc526502aeb64c70fd4522a151f61 | [] | no_license | ZhangFfeng/SingleDatasource | fc808cc3f7068083ffd5ce364f579db5ea9eff36 | 404ea725e80acca5b52b7d9af634c1a46bbd6960 | refs/heads/master | 2020-05-16T22:46:48.664176 | 2019-04-25T02:51:43 | 2019-04-25T02:51:43 | 183,343,575 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 609 | java | package com.example.demo.service;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.springframework.stereotype.Component;
/**
* feign降级处理
*
* @Author: zhangfeng
* @Date: 2019/4/24 10:04
* @Version 1.0
*/
@Component
public class HystrixClientFallback implements OrganzationService {
Logger logger = LoggerFactory.getLogger(HystrixClientFallback.class);
@Override
public String sayHello(String name) {
logger.info("feign超时配置");
return "请重试";
}
@Override
public String saySorry(String name) {
return null;
}
}
| [
"1547759015@qq.com"
] | 1547759015@qq.com |
e08b474d8c1c4a1e2b29d68fd894d73c09a29530 | 513c6cfa67b73e48dbfdbf8f5e44b01db0278229 | /src/main/java/com/ygznsl/chess/game/position/PositionSupplier.java | 77458cdceb2121e935e16e0aba2a0cdd5d87314a | [] | no_license | YgzNsl/chess | 6f2776a778849ea0963494a82243e94445d1d49a | 2bad63eac033438785aa7825cff3177187e509a3 | refs/heads/master | 2020-07-01T19:29:08.199017 | 2019-10-24T13:26:27 | 2019-10-24T13:26:27 | 201,273,120 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 205 | java | package com.ygznsl.chess.game.position;
import com.ygznsl.chess.game.exception.InvalidPositionException;
public interface PositionSupplier
{
Position getPosition() throws InvalidPositionException;
}
| [
"yagiz.unsal@sahibinden.com"
] | yagiz.unsal@sahibinden.com |
63e08a70c8c478c3bcb56154263d9ca09039afb0 | b279780df79ff2269333ee0dbed046ba02a5aa59 | /IOT-Guide-Custom-Protocol/src/main/java/iot/technology/custom/protocol/PacketCodec.java | 51b3b3024e7ef37e548db63934b688c83bc0ad98 | [
"Apache-2.0"
] | permissive | rogerwangzy/IOT-Technical-Guide | 3093ae7482a6bf1b744f8a2a7d92097b6df53771 | 7e76946a5c4887514707f827308de86d243c8497 | refs/heads/master | 2022-11-24T20:15:54.871068 | 2020-07-28T09:37:29 | 2020-07-28T09:37:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,473 | java | package iot.technology.custom.protocol;
import io.netty.buffer.ByteBuf;
import iot.technology.custom.encryption.Encryption;
import iot.technology.custom.encryption.impl.NotEncryption;
import java.util.HashMap;
import java.util.Map;
/**
* @author james mu
* @date 2020/7/27 13:45
*/
public class PacketCodec {
public static final byte MAGIC_NUMBER1 = (byte) 0x23;
public static final byte MAGIC_NUMBER2 = (byte) 0x23;
public static final byte VER = (byte) 0x01;
public static final PacketCodec INSTANCE = new PacketCodec();
private final Map<Byte, Class<? extends Packet>> packetTypeMap;
private final Map<Byte, Encryption> serializerMap;
private PacketCodec() {
packetTypeMap = new HashMap<>();
serializerMap = new HashMap<>();
Encryption encryption = new NotEncryption();
serializerMap.put(encryption.getEncryptionAlgorithm(), encryption);
}
public void encode(ByteBuf byteBuf, Packet packet) {
byte[] bytes = Encryption.DEFAULT.encrypt(packet);
byteBuf.writeByte(MAGIC_NUMBER1);
byteBuf.writeByte(MAGIC_NUMBER2);
byteBuf.writeByte(packet.getCommand());
byteBuf.writeBytes(packet.getVin());
byteBuf.writeByte(packet.getSwv());
byteBuf.writeByte(Encryption.DEFAULT.getEncryptionAlgorithm());
byteBuf.writeShort(bytes.length);
byteBuf.writeBytes(bytes);
byteBuf.writeByte(VER);
}
public Packet decode(ByteBuf byteBuf) {
byteBuf.skipBytes(2);
byte command = byteBuf.readByte();
byte[] vinByte = new byte[17];
byteBuf.readBytes(vinByte);
byte swv = byteBuf.readByte();
byte enm = byteBuf.readByte();
short length = byteBuf.readShort();
byte[] bytes = new byte[length];
byteBuf.readBytes(bytes);
byte ver = byteBuf.readByte();
Class<? extends Packet> requestType = getRequestType(command);
Encryption encryption = getEncryption(enm);
if (requestType != null && encryption != null) {
Packet packet = encryption.decrypt(requestType, bytes);
packet.setVin(vinByte);
return packet;
}
return null;
}
private Encryption getEncryption(byte encryptionAlgorithm) {
return serializerMap.get(encryptionAlgorithm);
}
private Class<? extends Packet> getRequestType(byte command) {
return packetTypeMap.get(command);
}
}
| [
"lovewsic@gmail.com"
] | lovewsic@gmail.com |
ab95a22719bda44e475d4fb41cc6d38f6d71a19a | abfef0fbdf934ba331bbf042b6ccab39c0682411 | /src/main/java/com/yeahpi/handler/EnumColumnHandler.java | b9defac78440af41b8ae609d27eff50749585b16 | [] | no_license | MicroCountry/excel-util | a562609c0ff1f45b703f3cba533b7e3c996c35b9 | b7d1aa88199323e4a2758f97ff5e588a09c341e0 | refs/heads/master | 2020-03-27T23:07:53.093717 | 2018-10-16T22:34:19 | 2018-10-16T22:34:19 | 147,293,486 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,346 | java | package com.yeahpi.handler;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.poi.ss.usermodel.Cell;
import java.lang.reflect.Method;
/**
* Class
*
* @author wgm
* @date 2018/09/14
*/
public class EnumColumnHandler<E extends Enum> implements ColumnHandler {
private Class<E> type;
@Override
public Cell cell(Cell cell, Object object) {
int code = (int) object;
String desc =getDescByCode(code);
cell.setCellValue(desc);
return cell;
}
public EnumColumnHandler(Class<E> type){
this.type = type;
}
public String getDescByCode(int code){
try {
Method getCode = type.getMethod("getCode");
Method getDesc = type.getMethod("getDesc");
E[] enums = type.getEnumConstants();
if (enums == null) {
throw new IllegalArgumentException(type.getSimpleName() + " does not represent an enum type.");
}
for (E e : enums) {
int eCode = (Integer) getCode.invoke(e);
if(eCode == code){
return (String)getDesc.invoke(e);
}
}
}catch (Exception e){
System.out.println("getDescByCode error " + ExceptionUtils.getStackTrace(e));
}
return "";
}
}
| [
"1570424984@qq.com"
] | 1570424984@qq.com |
41618ba02361dbdeedb0241d980c10c2dd9649e6 | 77bb277d51c72c702dc3fa52718779e3863d1549 | /src/main/java/space/harbour/java/hw13/ResultHandler.java | ae574142be4981c90e5c9eea52d5a1b475ea0910 | [] | no_license | mariusklages/java-hs | 95204f97e5985dde27036e208dd4627e6067a99d | 0270cb7e19b879598e1d053b306cd4dfe0c513ef | refs/heads/master | 2020-04-04T23:05:49.451825 | 2018-11-22T17:32:25 | 2018-11-22T17:32:25 | 156,346,853 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 184 | java | package space.harbour.java.hw13;
import com.mongodb.client.FindIterable;
import org.bson.Document;
public interface ResultHandler<T> {
T handle(FindIterable<Document> result);
}
| [
"mariusaklages@gmail.com"
] | mariusaklages@gmail.com |
c6c31a214db083e29603cb60645725ba14c9ba93 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/22/22_3aa3194dad21034d272a7b9b91142edbc5369adb/OAuthParameters/22_3aa3194dad21034d272a7b9b91142edbc5369adb_OAuthParameters_t.java | d9ed17717e72397278ae09f61b3d9f47ffb2aaaf | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 15,571 | java | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2010 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.jersey.oauth.signature;
import com.sun.jersey.api.uri.UriComponent;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
/**
* A data structure class that represents OAuth protocol parameters.
*
* @author Hubert A. Le Van Gong <hubert.levangong at Sun.COM>
* @author Paul C. Bryan <pbryan@sun.com>
*/
public class OAuthParameters extends HashMap<String, String> {
/** Name of HTTP authorization header. */
public static final String AUTHORIZATION_HEADER = "Authorization";
/** OAuth scheme in Authorization header. */
public static final String SCHEME = "OAuth";
/** Name of parameter containing the protection realm. */
public static final String REALM = "realm";
/** Name of parameter containing the consumer key. */
public static final String CONSUMER_KEY = "oauth_consumer_key";
/** Name of parameter containing the access/request token. */
public static final String TOKEN = "oauth_token";
/** Name of parameter containing the signature method. */
public static final String SIGNATURE_METHOD = "oauth_signature_method";
/** Name of parameter containing the signature. */
public static final String SIGNATURE = "oauth_signature";
/** Name of parameter containing the timestamp. */
public static final String TIMESTAMP = "oauth_timestamp";
/** Name of parameter containing the nonce. */
public static final String NONCE = "oauth_nonce";
/** Name of parameter containing the protocol version. */
public static final String VERSION = "oauth_version";
/** Name of parameter containing the verifier code. */
public static final String VERIFIER = "oauth_verifier";
/** Name of parameter containing the callback URL. */
public static final String CALLBACK = "oauth_callback";
/** Name of parameter containing the token secret.
* This parameter is never used in requests. It is part of a response to the request token and access token requests.
*/
public static final String TOKEN_SECRET = "oauth_token_secret";
/** Name of parameter containing the token secret.
* This parameter is never used in requests. It is part of a response to the request token requests.
*/
public static final String CALLBACK_CONFIRMED = "oauth_callback_confirmed";
/* Authorization scheme and delimiter. */
private static final String SCHEME_SPACE = SCHEME + ' ';
/**
* Returns the protection realm for the request.
*/
public String getRealm() {
return get(REALM);
}
/**
* Sets the protection realm for the request.
*/
public void setRealm(String realm) {
put(REALM, realm);
}
/**
* Builder pattern method to return {@link OAuthParameters} after setting
* protection realm.
*
* @param realm the protection realm for the request.
* @return this parameters object.
*/
public OAuthParameters realm(String realm) {
setRealm(realm);
return this;
}
/**
* Returns the consumer key.
*/
public String getConsumerKey() {
return get(CONSUMER_KEY);
}
/**
* Sets the consumer key.
*/
public void setConsumerKey(String consumerKey) {
put(CONSUMER_KEY, consumerKey);
}
/**
* Builder pattern method to return {@link OAuthParameters} after setting
* consumer key.
*
* @param consumerKey the consumer key.
*/
public OAuthParameters consumerKey(String consumerKey) {
setConsumerKey(consumerKey);
return this;
}
/**
* Returns the request or access token.
*/
public String getToken() {
return get(TOKEN);
}
/**
* Sets the request or access token.
*/
public void setToken(String token) {
put(TOKEN, token);
}
/**
* Builder pattern method to return {@link OAuthParameters} after setting
* token.
*
* @param token the access or request token.
* @return this parameters object.
*/
public OAuthParameters token(String token) {
setToken(token);
return this;
}
/**
* Returns the signature method used to sign the request.
*/
public String getSignatureMethod() {
return get(SIGNATURE_METHOD);
}
/**
* Sets the signature method used to sign the request.
*/
public void setSignatureMethod(String signatureMethod) {
put(SIGNATURE_METHOD, signatureMethod);
}
/**
* Builder pattern method to return {@link OAuthParameters} after setting
* signature method.
*
* @param signatureMethod the signature method used to sign the request.
* @return this parameters object.
*/
public OAuthParameters signatureMethod(String signatureMethod) {
setSignatureMethod(signatureMethod);
return this;
}
/**
* Returns the signature for the request.
*/
public String getSignature() {
return get(SIGNATURE);
}
/**
* Sets the signature for the request.
*/
public void setSignature(String signature) {
put(SIGNATURE, signature);
}
/**
* Builder pattern method to return {@link OAuthParameters} after setting
* signature.
*
* @param signature the signature for the request.
* @return this parameters object.
*/
public OAuthParameters signature(String signature) {
setSignature(signature);
return this;
}
/**
* Returns the timestamp, a value expected to be a positive integer,
* typically containing the number of seconds since January 1, 1970
* 00:00:00 GMT (epoch).
*/
public String getTimestamp() {
return get(TIMESTAMP);
}
/**
* Sets the timestamp. Its value is not validated, but should be a
* positive integer, typically containing the number of seconds since
* January 1, 1970 00:00:00 GMT (epoch).
*/
public void setTimestamp(String timestamp) {
put(TIMESTAMP, timestamp);
}
/**
* Builder pattern method to return {@link OAuthParameters} after setting
* timestamp.
*
* @param timestamp positive integer, typically number of seconds since epoch.
* @return this parameters object.
*/
public OAuthParameters timestamp(String timestamp) {
setTimestamp(timestamp);
return this;
}
/**
* Sets the timestamp to the current time as number of seconds since epoch.
*/
public void setTimestamp() {
setTimestamp(new Long(System.currentTimeMillis() / 1000).toString());
}
/**
* Builder pattern method to return {@link OAuthParameters} after setting
* timestamp to the current time.
*
* @return this parameters object.
*/
public OAuthParameters timestamp() {
setTimestamp();
return this;
}
/**
* Returns the nonce, a value that should be unique for a given
* timestamp.
*/
public String getNonce() {
return get(NONCE);
}
/**
* Sets the nonce, a value that should be unique for a given timestamp.
*/
public void setNonce(String nonce) {
put(NONCE, nonce);
}
/**
* Builder pattern method to return {@link OAuthParameters} after setting
* nonce.
*
* @param nonce a value that should be unique for a given timestamp.
* @return this parameters object.
*/
public OAuthParameters nonce(String nonce) {
setNonce(nonce);
return this;
}
/**
* Sets the nonce to contain a randomly-generated UUID.
*/
public void setNonce() {
setNonce(UUID.randomUUID().toString());
}
/**
* Builder pattern method to return {@link OAuthParameters} after setting
* nonce to a randomly-generated UUID.
*
* @return this parameters object.
*/
public OAuthParameters nonce() {
setNonce();
return this;
}
/**
* Returns the protocol version.
*/
public String getVersion() {
return get(VERSION);
}
/**
* Sets the protocol version.
*/
public void setVersion(String version) {
put(VERSION, version);
}
/**
* Builder pattern method to return {@link OAuthParameters} after setting
* version.
*
* @param version the protocol version.
* @return this parameters object.
*/
public OAuthParameters version(String version) {
setVersion(version);
return this;
}
/**
* Sets the protocol version to the default value of 1.0.
*/
public void setVersion() {
setVersion("1.0");
}
/**
* Builder pattern method to return {@link OAuthParameters} after setting
* version to the default value of 1.0.
*
* @return this parameters object.
*/
public OAuthParameters version() {
setVersion();
return this;
}
/**
* Returns the verifier code.
*/
public String getVerifier() {
return get(VERIFIER);
}
/**
* Sets the verifier code.
*/
public void setVerifier(String verifier) {
put(VERIFIER, verifier);
}
/**
* Builder pattern method to return {@link OAuthParameters} after setting
* verifier code.
*
* @param verifier the verifier code.
* @return this parameters object.
*/
public OAuthParameters verifier(String verifier) {
setVerifier(verifier);
return this;
}
/**
* Returns the callback URL.
*/
public String getCallback() {
return get(CALLBACK);
}
/**
* Sets the callback URL.
*/
public void setCallback(String callback) {
put(CALLBACK, callback);
}
/**
* Builder pattern method to return {@link OAuthParameters} after setting
* callback URL.
*
* @param callback the callback URL.
* @return this parameters object.
*/
public OAuthParameters callback(String callback) {
setCallback(callback);
return this;
}
/**
* Removes (optional) quotation marks encapsulating parameter values in the
* Authorization header and returns the result.
*/
private static String dequote(String value) {
int length = value.length();
return ((length >= 2 && value.charAt(0) == '"' && value.charAt(length - 1) == '"') ?
value.substring(1, length - 1) : value);
}
/**
* Reads a request for OAuth parameters, and populates this object.
*
* @param request the request to read OAuth parameters from.
* @return this parameters object.
*/
public OAuthParameters readRequest(OAuthRequest request) {
// read supported parameters from query string or request body (lowest preference)
for (String param : request.getParameterNames()) {
if (!param.startsWith("oauth_")) {
continue;
}
List values = request.getParameterValues(param);
if (values == null) {
continue;
}
Iterator<String> i = values.iterator();
if (!i.hasNext()) {
continue;
}
put(param, i.next());
}
// read all parameters from authorization header (highest preference)
List<String> headers = request.getHeaderValues(AUTHORIZATION_HEADER);
if (headers == null) { return this; }
for (String header : headers) {
if (!header.regionMatches(true, 0, SCHEME_SPACE, 0, SCHEME_SPACE.length())) {
continue;
}
for (String param : header.substring(SCHEME_SPACE.length()).trim().split(",(?=(?:[^\"]*\"[^\"]*\")+$)")) {
String[] nv = param.split("=", 2);
if (nv.length != 2) {
continue;
}
put(UriComponent.decode(nv[0].trim(), UriComponent.Type.UNRESERVED),
UriComponent.decode(dequote(nv[1].trim()), UriComponent.Type.UNRESERVED));
}
}
return this;
}
/**
* Writes the OAuth parameters to a request, as an Authorization header.
*
* @param request the request to write OAuth parameters to.
* @return this parameters object.
*/
public OAuthParameters writeRequest(OAuthRequest request) {
StringBuffer buf = new StringBuffer(SCHEME);
boolean comma = false;
for (String key : keySet()) {
String value = get(key);
if (value == null) {
continue;
}
buf.append(comma ? ", " : " ").append(UriComponent.encode(key, UriComponent.Type.UNRESERVED));
buf.append("=\"").append(UriComponent.encode(value, UriComponent.Type.UNRESERVED)).append('"');
comma = true;
}
request.addHeaderValue(AUTHORIZATION_HEADER, buf.toString());
return this;
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
e20cf168d7515ebe9ceba46eda82d093fae20cda | 15850dd1a4ec7b1d9bd64a47a3c4d53cc9dc7530 | /app/src/main/java/com/putraaryotama/tugaskuliah/model/DaftarTugas.java | 17f48eaa9b1b54309c79f154f002021f3957b435 | [] | no_license | PutraAryotama/TugasKuliah | d9b21bda363cb3dabf18ce94bbc82f30ce76a4c1 | 5361c08115cc973701da5d94479e32c037692f7c | refs/heads/master | 2021-07-04T13:36:52.930314 | 2017-09-27T03:25:51 | 2017-09-27T03:25:51 | 104,967,413 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 236 | java | package com.putraaryotama.tugaskuliah.model;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Putra Aryotama on 23/09/2017.
*/
public class DaftarTugas {
private List<Tugas> daftarTugas = new ArrayList();
}
| [
"putraaryotama@gmail.com"
] | putraaryotama@gmail.com |
0945ce127951c390c3deba05f58bc81fa2162362 | 8da7da0e0005be8eb0f6a1d4b7083f28122cd603 | /src/com/java/dateUtil/TesteLocalDate.java | 5272060b504ca44369ecb9433bad00317208acdb | [] | no_license | adielmo/POO | 9e76ba275d1d30ac499817d730d2a565d109b475 | 867d4b967769290fa2324da0cc0f68de4c878299 | refs/heads/master | 2022-11-20T19:30:59.263332 | 2022-10-29T12:28:25 | 2022-10-29T12:28:25 | 238,902,730 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,613 | java | package com.java.dateUtil;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class TesteLocalDate {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
LocalDate hoje = LocalDate.now();
LocalDate data = LocalDate.of(2020, 3, 10);
String dt = "2019-05-15";// formato UTC
System.out.println(hoje);
System.out.println(data);
System.out.println(LocalDate.parse(dt));
System.out.println("=======================//==========================");
// Adicionando Ano,Mês ou Dia em uma Data, usando LocalDate.plus
LocalDate maisMes = hoje.plusMonths(2);// Menos 2 mês
System.out.println(maisMes);
System.out.println(maisMes.plusDays(5));// Mais 5 Dias
System.out.println(maisMes.plus(2, ChronoUnit.YEARS));// Mais 2 Anos
System.out.println("=======================//==========================");
// Podemos voltar um Ano,Mês ou Dia em uma Data, usando LocalDate.min
LocalDate menosMes = hoje.minusMonths(3);// Menos 3 Mês
System.out.println(menosMes);
System.out.println(menosMes.plusDays(10));// Menos 10 Dias
System.out.println(menosMes.minus(2, ChronoUnit.MONTHS));// Menos 2 mês
System.out.println("=======================//==========================");
System.out.println(hoje.getDayOfWeek());// Dia da Semana
System.out.println(hoje.getMonth());// Mês do Ano
System.out.println(hoje.getYear());// Ano
System.out.println(hoje.isLeapYear());//VErificar se Ano Bisexto
System.out.println("=======================//==========================");
}
}
| [
"adielmorabelo@gmail.com"
] | adielmorabelo@gmail.com |
20cee2064839bedc79d54ac91c998b3d072004e2 | 8501e286832a36ed033b4220fb5e281f4b57e585 | /Sample9_4_加载obj文件中的纹理坐标/app/src/main/java/com/bn/Sample9_4/MatrixState.java | 8bf22dc44b29bfaaba73ab5c9d9af9eebdb2bf02 | [] | no_license | CatDroid/OpenGLES3xGame | f8b2e88dffdbac67078c04f166f2fc42cf92cc67 | 6e066ceeb238836c623135871674337b4a8b4992 | refs/heads/master | 2021-05-16T15:30:08.674603 | 2020-12-20T09:32:28 | 2020-12-20T09:32:28 | 119,228,042 | 24 | 9 | null | null | null | null | UTF-8 | Java | false | false | 4,126 | java | package com.bn.Sample9_4;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.*;
import android.opengl.Matrix;
//存储系统矩阵状态的类
public class MatrixState
{
private static float[] mProjMatrix = new float[16];//4x4矩阵 投影用
private static float[] mVMatrix = new float[16];//摄像机位置朝向9参数矩阵
private static float[] currMatrix;//当前变换矩阵
public static float[] lightLocation=new float[]{0,0,0};//定位光光源位置
public static FloatBuffer cameraFB;
public static FloatBuffer lightPositionFB;
public static Stack<float[]> mStack=new Stack<float[]>();//保护变换矩阵的栈
public static void setInitStack()//获取不变换初始矩阵
{
currMatrix=new float[16];
Matrix.setRotateM(currMatrix, 0, 0, 1, 0, 0);
}
public static void pushMatrix()//保护变换矩阵
{
mStack.push(currMatrix.clone());
}
public static void popMatrix()//恢复变换矩阵
{
currMatrix=mStack.pop();
}
public static void translate(float x,float y,float z)//设置沿xyz轴移动
{
Matrix.translateM(currMatrix, 0, x, y, z);
}
public static void rotate(float angle,float x,float y,float z)//设置绕xyz轴移动
{
Matrix.rotateM(currMatrix,0,angle,x,y,z);
}
//设置摄像机
public static void setCamera
(
float cx, //摄像机位置x
float cy, //摄像机位置y
float cz, //摄像机位置z
float tx, //摄像机目标点x
float ty, //摄像机目标点y
float tz, //摄像机目标点z
float upx, //摄像机UP向量X分量
float upy, //摄像机UP向量Y分量
float upz //摄像机UP向量Z分量
)
{
Matrix.setLookAtM
(
mVMatrix,
0,
cx,
cy,
cz,
tx,
ty,
tz,
upx,
upy,
upz
);
float[] cameraLocation=new float[3];//摄像机位置
cameraLocation[0]=cx;
cameraLocation[1]=cy;
cameraLocation[2]=cz;
ByteBuffer llbb = ByteBuffer.allocateDirect(3*4);
llbb.order(ByteOrder.nativeOrder());//设置字节顺序
cameraFB=llbb.asFloatBuffer();
cameraFB.put(cameraLocation);
cameraFB.position(0);
}
//设置透视投影参数
public static void setProjectFrustum
(
float left, //near面的left
float right, //near面的right
float bottom, //near面的bottom
float top, //near面的top
float near, //near面距离
float far //far面距离
)
{
Matrix.frustumM(mProjMatrix, 0, left, right, bottom, top, near, far);
}
//设置正交投影参数
public static void setProjectOrtho
(
float left, //near面的left
float right, //near面的right
float bottom, //near面的bottom
float top, //near面的top
float near, //near面距离
float far //far面距离
)
{
Matrix.orthoM(mProjMatrix, 0, left, right, bottom, top, near, far);
}
//获取具体物体的总变换矩阵
public static float[] getFinalMatrix()
{
float[] mMVPMatrix=new float[16];
Matrix.multiplyMM(mMVPMatrix, 0, mVMatrix, 0, currMatrix, 0);
Matrix.multiplyMM(mMVPMatrix, 0, mProjMatrix, 0, mMVPMatrix, 0);
return mMVPMatrix;
}
//获取具体物体的变换矩阵
public static float[] getMMatrix()
{
return currMatrix;
}
//设置灯光位置的方法
public static void setLightLocation(float x,float y,float z)
{
lightLocation[0]=x;
lightLocation[1]=y;
lightLocation[2]=z;
ByteBuffer llbb = ByteBuffer.allocateDirect(3*4);
llbb.order(ByteOrder.nativeOrder());//设置字节顺序
lightPositionFB=llbb.asFloatBuffer();
lightPositionFB.put(lightLocation);
lightPositionFB.position(0);
}
}
| [
"1198432354@qq.com"
] | 1198432354@qq.com |
d9696a2f082d85a77dc78ac2dbe89fb11d7bbdf9 | 0ba4738b6cac011b9e8cf1fd4c5c04adb5ef5d2a | /model/src/designModel/creationtype/prototype/improve/Sheep.java | 354176fb399b262292f8623f1f39f7d630c0959c | [] | no_license | 17551085204/designPattern | b662089fab8ffea6ac7963bcfebb52afb6ff0b98 | 09ee3596fc3c823d0b12ffc45c1560eb976ce718 | refs/heads/main | 2023-01-30T14:03:42.686979 | 2020-12-18T09:52:07 | 2020-12-18T09:52:07 | 317,772,066 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,428 | java | /*
@Author:南柯一梦
@Contact:2890241339@qq.com
@Date:2020/12/10
*/
package designModel.creationtype.prototype.improve;
//import java.util.Scanner;
public class Sheep implements Cloneable {
private String name;
private int age;
private String color;
private String address="蒙古羊";
public Sheep friend;
public Sheep(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
// 克隆该实例,使用默认的克隆方法
@Override
protected Object clone() {
Sheep sheep=null;
try {
sheep=(Sheep)super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return sheep;
}
@Override
public String toString() {
return "Sheep{" +
"name='" + name + '\'' +
", age=" + age +
", color='" + color + '\'' +
", address='" + address + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
| [
"2890241339@qq.com"
] | 2890241339@qq.com |
5f59f6fdfd2f281989348c50482bea39bbb467ed | 8a68cfdd429ae4cb123a254a3a8516eeb8bc92d2 | /src/main/java/com/zetsubou_0/parser/model/DataItemModel.java | 36ab7e9f4dff86f81be1efc7cd45d5df717d7cf3 | [] | no_license | zetsubou-0/site-data-parser | 359f0322787dbe4085bb63dd3d60564b291ac199 | 508d1318c95bc1d98cdb70d9ca1dd96bbeeab9ed | refs/heads/master | 2022-09-25T03:29:55.084013 | 2021-03-23T12:53:27 | 2021-03-23T12:53:27 | 249,950,115 | 0 | 0 | null | 2022-09-01T23:22:07 | 2020-03-25T10:35:20 | Java | UTF-8 | Java | false | false | 298 | java | package com.zetsubou_0.parser.model;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface DataItemModel {
}
| [
"zetsubou.zero.0@gmail.com"
] | zetsubou.zero.0@gmail.com |
4c5ef1cf49659ef6b386602eb8fd16d757740269 | 03e6aba43f138f8d0045c17e6ba7bee34b3ea304 | /cursomc/src/main/java/com/cursomc/domain/ItemPedidoPK.java | 72ec150ce70a25dde7c4b95a75e7a8bc41ec804a | [] | no_license | Walter-Cantori/java-lab | a1fbdc675304a30889d5e294a29de9128267e9ec | 6e095cabf7e7ff05e7c56ee319feebc1d3d556c7 | refs/heads/master | 2020-04-18T23:56:04.679782 | 2019-01-27T17:04:29 | 2019-01-27T17:04:29 | 167,834,271 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,428 | java | package com.cursomc.domain;
import java.io.Serializable;
import javax.persistence.Embeddable;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@Embeddable
public class ItemPedidoPK implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@ManyToOne
@JoinColumn(name="pedido_id")
private Pedido pedido;
@ManyToOne
@JoinColumn(name="produto_id")
private Produto produto;
public Pedido getPedido() {
return pedido;
}
public void setPedido(Pedido pedido) {
this.pedido = pedido;
}
public Produto getProduto() {
return produto;
}
public void setProduto(Produto produto) {
this.produto = produto;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((pedido == null) ? 0 : pedido.hashCode());
result = prime * result + ((produto == null) ? 0 : produto.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;
ItemPedidoPK other = (ItemPedidoPK) obj;
if (pedido == null) {
if (other.pedido != null)
return false;
} else if (!pedido.equals(other.pedido))
return false;
if (produto == null) {
if (other.produto != null)
return false;
} else if (!produto.equals(other.produto))
return false;
return true;
}
}
| [
"walter.cantori@gmail.com"
] | walter.cantori@gmail.com |
c1675dcc39b203add1fa139447f2b6ba500e3e73 | a6c3528dca9c683487dcb85cf437e2cdcf40f913 | /app/src/main/java/fuzhiyan/com/bawie/tablayouttest/adapter/MyListAdapter.java | dc1537d485d67e975bc114d432ceb881471e15c5 | [] | no_license | fuzhiyan/TablayoutTest | 7adb8c9bac459af5000e6da0521f179c5a07ed09 | 50f19102ba961be26ce051daba6381a08de185cb | refs/heads/master | 2021-01-23T06:10:22.677094 | 2017-06-01T03:21:22 | 2017-06-01T03:21:22 | 93,012,146 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,965 | java | package fuzhiyan.com.bawie.tablayouttest.adapter;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.xutils.x;
import java.util.List;
import fuzhiyan.com.bawie.tablayouttest.MyBean;
import fuzhiyan.com.bawie.tablayouttest.R;
/**
* Created by Administrator on 2017/5/31.
* time:
* author:付智焱
*/
public class MyListAdapter extends BaseAdapter {
private Context context;
private List<MyBean.DataBean.ComicsBean> list;
public MyListAdapter(Context context, List<MyBean.DataBean.ComicsBean> list) {
this.context = context;
this.list = list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
class ViewHolder{
private TextView textView1,textView2;
private ImageView imageView;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh;
if(convertView==null){
vh=new ViewHolder();
convertView=View.inflate(context, R.layout.list_item,null);
vh.textView1= (TextView) convertView.findViewById(R.id.itme_text1);
vh.textView2= (TextView) convertView.findViewById(R.id.item_text3);
vh.imageView= (ImageView) convertView.findViewById(R.id.item_image);
convertView.setTag(vh);
}else{
vh= (ViewHolder) convertView.getTag();
}
vh.textView1.setText(list.get(position).getLabel_text());
vh.textView2.setText(list.get(position).getTitle());
x.image().bind(vh.imageView,list.get(position).getTopic().getCover_image_url());
return convertView;
}
}
| [
"fuzhiyan_001@163.com"
] | fuzhiyan_001@163.com |
190c55db4cdc9c9b84c583a6fe4d1ee6907e3227 | 430b7659c2f10c51aa6270e30dd277328d4860eb | /app/src/main/java/com/eddietseng/nytimessearch/activities/ArticleActivity.java | 9bea0221c9efb1916798017ad489ccb77ae98c38 | [] | no_license | eddietseng/NYTimesSearch | 4709a810c729570d196f46e7a3e6b66a9cd4e2f5 | bb7139b4225021e4871409933006ecb3ede1db6a | refs/heads/master | 2021-01-19T05:21:00.352574 | 2016-08-01T01:27:33 | 2016-08-01T01:27:33 | 64,546,763 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,101 | java | package com.eddietseng.nytimessearch.activities;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.eddietseng.nytimessearch.R;
import com.eddietseng.nytimessearch.model.Article;
import org.parceler.Parcels;
public class ArticleActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_article);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
Article article = Parcels.unwrap(getIntent().getParcelableExtra("article"));
WebView webView = (WebView) findViewById(R.id.wvArticle);
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.loadUrl(article.getWebUrl());
}
}
| [
"faizs0831@gmail.com"
] | faizs0831@gmail.com |
a21b727b973d6dd1841dbf1ab3b42c9f02ee7d63 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/12/12_db4c4b9c613fdea9f47e3aaf5ee2c9dfbc8df839/DBWrapper/12_db4c4b9c613fdea9f47e3aaf5ee2c9dfbc8df839_DBWrapper_t.java | 2c03472c58f02b1f233638a3ba9515efade23590 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 90,270 | java | /*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2013 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses. For additional information contact info@OpenLMIS.org.
*/
package org.openlmis.UiUtils;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.lang.String.format;
import static java.lang.System.getProperty;
public class DBWrapper {
public static final int DEFAULT_MAX_MONTH_OF_STOCK = 3;
public static final String DEFAULT_DB_URL = "jdbc:postgresql://localhost:5432/open_lmis";
public static final String DEFAULT_DB_USERNAME = "postgres";
public static final String DEFAULT_DB_PASSWORD = "p@ssw0rd";
Connection connection;
public DBWrapper() throws IOException, SQLException {
String dbUser = getProperty("dbUser", DEFAULT_DB_USERNAME);
String dbPassword = getProperty("dbPassword", DEFAULT_DB_PASSWORD);
String dbUrl = getProperty("dbUrl", DEFAULT_DB_URL);
loadDriver();
connection = DriverManager.getConnection(dbUrl, dbUser, dbPassword);
}
public void closeConnection() throws SQLException {
if (connection != null) connection.close();
}
private void loadDriver() {
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.exit(1);
}
}
private void update(String sql) throws SQLException {
try (Statement statement = connection.createStatement()) {
statement.executeUpdate(sql);
}
}
private void update(String sql, Object... params) throws SQLException {
update(format(sql, params));
}
private ResultSet query(String sql) throws SQLException {
return connection.createStatement().executeQuery(sql);
}
private List<Map<String, String>> select(String sql, Object... params) throws SQLException {
ResultSet rs = query(sql, params);
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
List<Map<String, String>> list = new ArrayList<>();
while (rs.next()) {
Map<String, String> row = new HashMap<>();
for (int i = 1; i <= columns; ++i) {
row.put(md.getColumnName(i), rs.getString(i));
}
list.add(row);
}
return list;
}
private ResultSet query(String sql, Object... params) throws SQLException {
return query(format(sql, params));
}
public void insertUser(String userId, String userName, String password, String facilityCode, String email) throws SQLException, IOException {
update("delete from users where userName like('%s')", userName);
update("INSERT INTO users(id, userName, password, facilityId, firstName, lastName, email, active, verified) " + "VALUES ('%s', '%s', '%s', (SELECT id FROM facilities WHERE code = '%s'), 'Fatima', 'Doe', '%s','true','true')",
userId,
userName,
password,
facilityCode,
email);
}
public void insertPeriodAndAssociateItWithSchedule(String period, String schedule) throws SQLException, IOException {
insertProcessingPeriod(period, period, "2013-09-29", "2020-09-30", 66, schedule);
}
public void deleteProcessingPeriods() throws SQLException, IOException {
update("delete from processing_periods");
}
public List<String> getProductDetailsForProgram(String programCode) throws SQLException {
List<String> prodDetails = new ArrayList<>();
ResultSet rs = query("select programs.code as programCode, programs.name as programName, " +
"products.code as productCode, products.primaryName as productName, products.description as desc, " +
"products.dosesPerDispensingUnit as unit, PG.name as pgName " +
"from products, programs, program_products PP, product_categories PG " +
"where programs.id = PP.programId and PP.productId=products.id and " +
"PG.id = products.categoryId and programs.code='" + programCode + "' " +
"and products.active='true' and PP.active='true'");
while (rs.next()) {
String programName = rs.getString(2);
String productCode = rs.getString(3);
String productName = rs.getString(4);
String desc = rs.getString(5);
String unit = rs.getString(6);
String pcName = rs.getString(7);
prodDetails.add(programName + "," + productCode + "," + productName + "," + desc + "," + unit + "," + pcName);
}
return prodDetails;
}
public List<String> getProductDetailsForProgramAndFacilityType(String programCode, String facilityCode) throws SQLException {
List<String> prodDetails = new ArrayList<>();
ResultSet rs = query("select prog.code as programCode, prog.name as programName, prod.code as productCode, " +
"prod.primaryName as productName, prod.description as desc, prod.dosesPerDispensingUnit as unit, " +
"pg.name as pgName from products prod, programs prog, program_products pp, product_categories pg, " +
"facility_approved_products fap, facility_types ft where prog.id=pp.programId and pp.productId=prod.id and " +
"pg.id = prod.categoryId and fap. programProductId = pp.id and ft.id=fap.facilityTypeId and prog.code='" +
programCode + "' and ft.code='" + facilityCode + "' " + "and prod.active='true' and pp.active='true'");
while (rs.next()) {
String programName = rs.getString(2);
String productCode = rs.getString(3);
String productName = rs.getString(4);
String desc = rs.getString(5);
String unit = rs.getString(6);
String pgName = rs.getString(7);
prodDetails.add(programName + "," + productCode + "," + productName + "," + desc + "," + unit + "," + pgName);
}
return prodDetails;
}
public void updateActiveStatusOfProduct(String productCode, String active) throws SQLException {
update("update products set active='%s' where code='%s'", active, productCode);
}
public void updateActiveStatusOfProgramProduct(String productCode, String programCode, String active) throws SQLException {
update("update program_products set active='%s' WHERE" +
" programId = (select id from programs where code='%s') AND" +
" productId = (select id from products where code='%s')", active, programCode, productCode);
}
public List<String> getFacilityCodeNameForDeliveryZoneAndProgram(String deliveryZoneName, String program, boolean active) throws SQLException {
List<String> codeName = new ArrayList<>();
ResultSet rs = query(
"select f.code, f.name from facilities f, programs p, programs_supported ps, delivery_zone_members dzm, delivery_zones dz where " +
"dzm.DeliveryZoneId=dz.id and " +
"f.active='" + active + "' and " +
"p.id= ps.programId and " +
"p.code='" + program + "' and " +
"dz.id = dzm.DeliveryZoneId and " +
"dz.name='" + deliveryZoneName + "' and " +
"dzm.facilityId = f.id and " +
"ps.facilityId = f.id;");
while (rs.next()) {
String code = rs.getString("code");
String name = rs.getString("name");
codeName.add(code + " - " + name);
}
return codeName;
}
public void updateVirtualPropertyOfFacility(String facilityCode, String flag) throws SQLException, IOException {
update("UPDATE facilities SET virtualFacility='%s' WHERE code='%s'", flag, facilityCode);
}
public void deleteDeliveryZoneMembers(String facilityCode) throws SQLException, IOException {
update("delete from delivery_zone_members where facilityId in (select id from facilities where code ='%s')",
facilityCode);
}
public void updateUser(String password, String email) throws SQLException, IOException {
update("DELETE FROM user_password_reset_tokens");
update("update users set password = '%s', active = TRUE, verified = TRUE where email = '%s'", password, email);
}
public void updateRestrictLogin(String userName, boolean status) throws SQLException, IOException {
update("update users set restrictLogin = '%s' where userName = '%s'", status, userName);
}
public void insertRequisitions(int numberOfRequisitions,
String program,
boolean withSupplyLine) throws SQLException, IOException {
int numberOfRequisitionsAlreadyPresent = 0;
boolean flag = true;
ResultSet rs = query("select count(*) from requisitions");
if (rs.next()) {
numberOfRequisitionsAlreadyPresent = Integer.parseInt(rs.getString(1));
}
for (int i = numberOfRequisitionsAlreadyPresent + 1; i <= numberOfRequisitions + numberOfRequisitionsAlreadyPresent; i++) {
insertProcessingPeriod("PeriodName" + i, "PeriodDesc" + i, "2012-12-01", "2015-12-01", 1, "M");
update("insert into requisitions (facilityId, programId, periodId, status, emergency, " +
"fullSupplyItemsSubmittedCost, nonFullSupplyItemsSubmittedCost, supervisoryNodeId) " +
"values ((Select id from facilities where code='F10'),(Select id from programs where code='" + program + "')," +
"(Select id from processing_periods where name='PeriodName" + i + "'), 'APPROVED', 'false', 50.0000, 0.0000, " +
"(select id from supervisory_nodes where code='N1'))");
update("INSERT INTO requisition_line_items " +
"(rnrId, productCode,product,productDisplayOrder,productCategory,productCategoryDisplayOrder, beginningBalance, quantityReceived, quantityDispensed, stockInHand, " +
"dispensingUnit, maxMonthsOfStock, dosesPerMonth, dosesPerDispensingUnit, packSize,fullSupply,totalLossesAndAdjustments,newPatientCount,stockOutDays,price,roundToZero,packRoundingThreshold) VALUES" +
"((SELECT max(id) FROM requisitions), 'P10','antibiotic Capsule 300/200/600 mg',1,'Antibiotics',1, '0', '11' , '1', '10' ,'Strip','3', '30', '10', '10','t',0,0,0,12.5000,'f',1);");
}
if (withSupplyLine) {
ResultSet rs1 = query("select * from supply_lines where supervisoryNodeId = " +
"(select id from supervisory_nodes where code = 'N1') and programId = " +
"(select id from programs where code='" + program + "') and supplyingFacilityId = " +
"(select id from facilities where code = 'F10')");
if (rs1.next()) {
flag = false;
}
}
if (withSupplyLine) {
if (flag) {
insertSupplyLines("N1", program, "F10", true);
}
}
}
public void insertFulfilmentRoleAssignment(String userName,
String roleName,
String facilityCode) throws SQLException {
update("insert into fulfillment_role_assignments(userId, roleId, facilityId) values " +
"((select id from users where username='" + userName + "')," +
"(select id from roles where name='" + roleName + "'),(select id from facilities where code='" + facilityCode + "'))");
}
public String getDeliveryZoneNameAssignedToUser(String user) throws SQLException, IOException {
String deliveryZoneName = "";
ResultSet rs = query(
"select name from delivery_zones where id in(select deliveryZoneId from role_assignments where " +
"userId=(select id from users where username='" + user + "'))");
if (rs.next()) {
deliveryZoneName = rs.getString("name");
}
return deliveryZoneName;
}
public String getRoleNameAssignedToUser(String user) throws SQLException, IOException {
String userName = "";
ResultSet rs = query("select name from roles where id in(select roleId from role_assignments where " +
"userId=(select id from users where username='" + user + "'))");
if (rs.next()) {
userName = rs.getString("name");
}
return userName;
}
public void insertFacilities(String facility1, String facility2) throws IOException, SQLException {
update("INSERT INTO facilities\n" +
"(code, name, description, gln, mainPhone, fax, address1, address2, geographicZoneId, typeId, catchmentPopulation, latitude, longitude, altitude, operatedById, coldStorageGrossCapacity, coldStorageNetCapacity, suppliesOthers, sdp, hasElectricity, online, hasElectronicSCC, hasElectronicDAR, active, goLiveDate, goDownDate, satellite, comment, enabled, virtualFacility) values\n" +
"('" + facility1 + "','Village Dispensary','IT department','G7645',9876234981,'fax','A','B',5,2,333,22.1,1.2,3.3,2,9.9,6.6,'TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','11/11/12','11/11/1887','TRUE','fc','TRUE', 'FALSE'),\n" +
"('" + facility2 + "','Central Hospital','IT department','G7646',9876234981,'fax','A','B',5,2,333,22.3,1.2,3.3,3,9.9,6.6,'TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','11/11/12','11/11/2012','TRUE','fc','TRUE', 'FALSE');\n");
update("insert into programs_supported(facilityId, programId, startDate, active, modifiedBy) VALUES" +
" ((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 1, '11/11/12', true, 1)," +
" ((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 2, '11/11/12', true, 1)," +
" ((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 5, '11/11/12', true, 1)," +
" ((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 1, '11/11/12', true, 1)," +
" ((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 5, '11/11/12', true, 1)," +
" ((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 2, '11/11/12', true, 1)");
}
public void insertVirtualFacility(String facilityCode, String parentFacilityCode) throws IOException, SQLException {
update("INSERT INTO facilities\n" +
"(code, name, description, gln, mainPhone, fax, address1, address2, geographicZoneId, typeId, catchmentPopulation, latitude, longitude, altitude, operatedById, coldStorageGrossCapacity, coldStorageNetCapacity, suppliesOthers, sdp, hasElectricity, online, hasElectronicSCC, hasElectronicDAR, active, goLiveDate, goDownDate, satellite, comment, enabled, virtualFacility,parentFacilityId) values\n" +
"('" + facilityCode + "','Village Dispensary','IT department','G7645',9876234981,'fax','A','B',5,2,333,22.1,1.2,3.3,2,9.9,6.6,'TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','11/11/12','11/11/2012','TRUE','fc','TRUE', 'TRUE',(SELECT id FROM facilities WHERE code = '" + parentFacilityCode + "'))");
update("insert into programs_supported(facilityId, programId, startDate, active, modifiedBy) VALUES" +
" ((SELECT id FROM facilities WHERE code = '" + facilityCode + "'), 1, '11/11/12', true, 1)," +
" ((SELECT id FROM facilities WHERE code = '" + facilityCode + "'), 2, '11/11/12', true, 1)," +
" ((SELECT id FROM facilities WHERE code = '" + facilityCode + "'), 5, '11/11/12', true, 1)");
update("insert into requisition_group_members (requisitionGroupId, facilityId, createdDate, modifiedDate) values " +
"((select requisitionGroupId from requisition_group_members where facilityId=(SELECT id FROM facilities WHERE code = '" + parentFacilityCode + "'))," +
"(SELECT id FROM facilities WHERE code = '" + facilityCode + "'),NOW(),NOW())");
}
public void deletePeriod(String periodName) throws IOException, SQLException {
update("delete from processing_periods where name='" + periodName + "';");
}
public void insertFacilitiesWithDifferentGeoZones(String facility1, String facility2, String geoZone1, String geoZone2) throws IOException, SQLException {
update("INSERT INTO facilities\n" +
"(code, name, description, gln, mainPhone, fax, address1, address2, geographicZoneId, typeId, catchmentPopulation, latitude, longitude, altitude, operatedById, coldStorageGrossCapacity, coldStorageNetCapacity, suppliesOthers, sdp, hasElectricity, online, hasElectronicSCC, hasElectronicDAR, active, goLiveDate, goDownDate, satellite, comment, enabled, virtualFacility) values\n" +
"('" + facility1 + "','Village Dispensary','IT department','G7645',9876234981,'fax','A','B',(select id from geographic_zones where code='" + geoZone1 + "'),2,333,22.1,1.2,3.3,2,9.9,6.6,'TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','11/11/12','11/11/1887','TRUE','fc','TRUE', 'FALSE'),\n" +
"('" + facility2 + "','Central Hospital','IT department','G7646',9876234981,'fax','A','B',(select id from geographic_zones where code='" + geoZone2 + "'),2,333,22.3,1.2,3.3,3,9.9,6.6,'TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','TRUE','11/11/12','11/11/2012','TRUE','fc','TRUE', 'FALSE');\n");
update("insert into programs_supported(facilityId, programId, startDate, active, modifiedBy) VALUES\n" +
"((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 1, '11/11/12', true, 1),\n" +
"((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 2, '11/11/12', true, 1),\n" +
"((SELECT id FROM facilities WHERE code = '" + facility1 + "'), 5, '11/11/12', true, 1),\n" +
"((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 1, '11/11/12', true, 1),\n" +
"((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 5, '11/11/12', true, 1),\n" +
"((SELECT id FROM facilities WHERE code = '" + facility2 + "'), 2, '11/11/12', true, 1);");
}
public void insertGeographicZone(String code, String name, String parentName) throws IOException, SQLException {
update("insert into geographic_zones (code, name, levelId, parentId) " +
"values ('%s','%s',(select max(levelId) from geographic_zones)," +
"(select id from geographic_zones where code='%s'))", code, name, parentName);
}
public void allocateFacilityToUser(String userId, String facilityCode) throws IOException, SQLException {
update("update users set facilityId = (Select id from facilities where code = '%s') where id = '%s'", facilityCode, userId);
}
public void updateSourceOfAProgramTemplate(String program, String label, String source) throws IOException, SQLException {
update("update program_rnr_columns set source = '%s'" + " where programId = (select id from programs where code = '%s') and label = '%s'", source, program, label);
}
public void deleteData() throws SQLException, IOException {
update("delete from budget_line_items");
update("delete from budget_file_info");
update("delete from role_rights where roleId not in(1)");
update("delete from role_assignments where userId not in (1)");
update("delete from fulfillment_role_assignments");
update("delete from roles where name not in ('Admin')");
update("delete from facility_approved_products");
update("delete from program_product_price_history");
update("delete from pod_line_items");
update("delete from pod");
update("delete from orders");
update("delete from requisition_status_changes");
update("delete from user_password_reset_tokens");
update("delete from comments");
update("delete from facility_visits");
update("delete from epi_use_line_items");
update("delete from epi_use");
update("delete from epi_inventory_line_items");
update("delete from epi_inventory");
update("delete from refrigerator_problems");
update("delete from refrigerator_readings");
update("delete from distribution_refrigerators");
update("delete from vaccination_full_coverages");
update("delete from vaccination_coverages");
update("delete from distributions");
update("delete from refrigerators");
update("delete from users where userName not like('Admin%')");
update("delete from requisition_line_item_losses_adjustments");
update("delete from requisition_line_items");
update("delete from regimen_line_items");
update("delete from requisitions");
update("delete from program_product_isa");
update("delete from facility_approved_products");
update("delete from facility_program_products");
update("delete from program_products");
update("delete from products");
update("delete from product_categories");
update("delete from product_groups");
update("delete from supply_lines");
update("delete from programs_supported");
update("delete from requisition_group_members");
update("delete from program_rnr_columns");
update("delete from requisition_group_program_schedules");
update("delete from requisition_groups");
update("delete from requisition_group_members");
update("delete from delivery_zone_program_schedules");
update("delete from delivery_zone_warehouses");
update("delete from delivery_zone_members");
update("delete from role_assignments where deliveryZoneId in (select id from delivery_zones where code in('DZ1','DZ2'))");
update("delete from delivery_zones");
update("delete from supervisory_nodes");
update("delete from refrigerators");
update("delete from facility_ftp_details");
update("delete from refrigerators");
update("delete from facilities");
update("delete from geographic_zones where code not in ('Root','Arusha','Dodoma', 'Ngorongoro')");
update("delete from processing_periods");
update("delete from processing_schedules");
update("delete from atomfeed.event_records");
update("delete from regimens");
update("delete from program_regimen_columns");
}
public void insertRole(String role, String description) throws SQLException, IOException {
ResultSet rs = query("Select id from roles where name='%s'", role);
if (!rs.next()) {
update("INSERT INTO roles(name, description) VALUES('%s', '%s')", role, description);
}
}
public void insertSupervisoryNode(String facilityCode, String supervisoryNodeCode, String supervisoryNodeName, String supervisoryNodeParentCode) throws SQLException, IOException {
update("delete from supervisory_nodes");
update("INSERT INTO supervisory_nodes (parentId, facilityId, name, code) " + "VALUES (%s, (SELECT id FROM facilities WHERE code = '%s'), '%s', '%s')",
supervisoryNodeParentCode, facilityCode, supervisoryNodeName, supervisoryNodeCode);
}
public void insertSupervisoryNodeSecond(String facilityCode, String supervisoryNodeCode, String supervisoryNodeName, String supervisoryNodeParentCode) throws SQLException, IOException {
update("INSERT INTO supervisory_nodes" +
" (parentId, facilityId, name, code) VALUES" +
" ((select id from supervisory_nodes where code ='%s'), (SELECT id FROM facilities WHERE code = '%s'), '%s', '%s')",
supervisoryNodeParentCode, facilityCode, supervisoryNodeName, supervisoryNodeCode);
}
public void insertRequisitionGroups(String code1, String code2, String supervisoryNodeCode1, String supervisoryNodeCode2) throws SQLException, IOException {
ResultSet rs = query("Select id from requisition_groups;");
if (rs.next()) {
update("delete from requisition_groups;");
}
update("INSERT INTO requisition_groups ( code ,name,description,supervisoryNodeId )values\n" +
"('" + code2 + "','Requistion Group 2','Supports EM(Q1M)',(select id from supervisory_nodes where code ='" + supervisoryNodeCode2 + "')),\n" +
"('" + code1 + "','Requistion Group 1','Supports EM(Q2M)',(select id from supervisory_nodes where code ='" + supervisoryNodeCode1 + "'))");
}
public void insertRequisitionGroupMembers(String RG1facility, String RG2facility) throws SQLException, IOException {
ResultSet rs = query("Select requisitionGroupId from requisition_group_members;");
if (rs.next()) {
update("delete from requisition_group_members;");
}
update("INSERT INTO requisition_group_members ( requisitionGroupId ,facilityId )values\n" +
"((select id from requisition_groups where code ='RG1'),(select id from facilities where code ='" + RG1facility + "')),\n" +
"((select id from requisition_groups where code ='RG2'),(select id from facilities where code ='" + RG2facility + "'));");
}
public void insertRequisitionGroupProgramSchedule() throws SQLException, IOException {
ResultSet rs = query("Select requisitionGroupId from requisition_group_members;");
if (rs.next()) {
update("delete from requisition_group_program_schedules;");
}
update(
"insert into requisition_group_program_schedules ( requisitionGroupId , programId , scheduleId , directDelivery ) values\n" +
"((select id from requisition_groups where code='RG1'),(select id from programs where code='ESS_MEDS'),(select id from processing_schedules where code='Q1stM'),TRUE),\n" +
"((select id from requisition_groups where code='RG1'),(select id from programs where code='MALARIA'),(select id from processing_schedules where code='Q1stM'),TRUE),\n" +
"((select id from requisition_groups where code='RG1'),(select id from programs where code='HIV'),(select id from processing_schedules where code='M'),TRUE),\n" +
"((select id from requisition_groups where code='RG2'),(select id from programs where code='ESS_MEDS'),(select id from processing_schedules where code='Q1stM'),TRUE),\n" +
"((select id from requisition_groups where code='RG2'),(select id from programs where code='MALARIA'),(select id from processing_schedules where code='Q1stM'),TRUE),\n" +
"((select id from requisition_groups where code='RG2'),(select id from programs where code='HIV'),(select id from processing_schedules where code='M'),TRUE);\n");
}
//TODO
public void insertRoleAssignment(String userID, String roleName) throws SQLException, IOException {
update("delete from role_assignments where userId='" + userID + "';");
update(" INSERT INTO role_assignments\n" +
" (userId, roleId, programId, supervisoryNodeId) VALUES \n" +
" ('" + userID + "', (SELECT id FROM roles WHERE name = '" + roleName + "'), 1, null),\n" +
" ('" + userID + "', (SELECT id FROM roles WHERE name = '" + roleName + "'), 1, (SELECT id from supervisory_nodes WHERE code = 'N1'));");
}
//TODO
public void insertRoleAssignmentForSupervisoryNodeForProgramId1(String userID,
String roleName,
String supervisoryNode) throws SQLException, IOException {
update("delete from role_assignments where userId='" + userID + "';");
update(" INSERT INTO role_assignments\n" +
" (userId, roleId, programId, supervisoryNodeId) VALUES \n" +
" ('" + userID + "', (SELECT id FROM roles WHERE name = '" + roleName + "'), 1, null),\n" +
" ('" + userID + "', (SELECT id FROM roles WHERE name = '" + roleName + "'), 1, (SELECT id from supervisory_nodes WHERE code = '" + supervisoryNode + "'));");
}
public void updateRoleGroupMember(String facilityCode) throws SQLException, IOException {
update("update requisition_group_members set facilityId = " +
"(select id from facilities where code ='" + facilityCode + "') where " +
"requisitionGroupId=(select id from requisition_groups where code='RG2');");
update("update requisition_group_members set facilityId = " +
"(select id from facilities where code ='F11') where requisitionGroupId = " +
"(select id from requisition_groups where code='RG1');");
}
public void alterUserID(String userName, String userId) throws SQLException, IOException {
update("delete from user_password_reset_tokens;");
update("delete from users where id='" + userId + "' ;");
update(" update users set id='" + userId + "' where username='" + userName + "'");
}
public void insertProducts(String product1, String product2) throws SQLException, IOException {
update("delete from facility_approved_products;");
update("delete from program_products;");
update("delete from products;");
update("delete from product_categories;");
update("INSERT INTO product_categories (code, name, displayOrder) values ('C1', 'Antibiotics', 1);");
update("INSERT INTO products\n" +
"(code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, type, primaryName, fullName, genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, dosesPerDispensingUnit, packSize, alternatePackSize, storeRefrigerated, storeRoomTemperature, hazardous, flammable, controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, packWidth, packHeight, packWeight, packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, categoryId) values\n" +
"('" + product1 + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, 1, (Select id from product_categories where code='C1')),\n" +
"('" + product2 + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, 5, (Select id from product_categories where code='C1'));\n");
}
public void deleteCategoryFromProducts() throws SQLException, IOException {
update("UPDATE products SET categoryId = null");
}
public void deleteDescriptionFromProducts() throws SQLException, IOException {
update("UPDATE products SET description = null");
}
public void insertProductWithCategory(String product, String productName, String category) throws SQLException, IOException {
update("INSERT INTO product_categories (code, name, displayOrder) values ('" + category + "', '" + productName + "', 1);");
update("INSERT INTO products\n" +
"(code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, type, primaryName, fullName, genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, dosesPerDispensingUnit, packSize, alternatePackSize, storeRefrigerated, storeRoomTemperature, hazardous, flammable, controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, packWidth, packHeight, packWeight, packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, categoryId) values\n" +
"('" + product + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', '" + productName + "', '" + productName + "', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, 1, (Select id from product_categories where code='C1'));\n");
}
public void insertProductGroup(String group) throws SQLException, IOException {
update("INSERT INTO product_groups (code, name) values ('" + group + "', '" + group + "-Name');");
}
public void insertProductWithGroup(String product, String productName, String group, boolean status) throws SQLException, IOException {
update("INSERT INTO products\n" +
"(code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, type, primaryName, fullName," +
" genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, dosesPerDispensingUnit, packSize, alternatePackSize," +
" storeRefrigerated, storeRoomTemperature, hazardous, flammable, controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, " +
"packWidth, packHeight, packWeight, packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, " +
"specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, productGroupId) values" +
"('" + product + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', '" + productName + "', '" + productName +
"', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE," +
" 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', " + status + ",TRUE, TRUE, 1, FALSE, TRUE, 1, (Select id from product_groups where code='" + group + "'));");
}
public void updateProgramToAPushType(String program, boolean flag) throws SQLException {
update("update programs set push='" + flag + "' where code='" + program + "';");
}
public void insertProgramProducts(String product1, String product2, String program) throws SQLException, IOException {
ResultSet rs = query("Select id from program_products;");
if (rs.next()) {
update("delete from facility_approved_products;");
update("delete from program_products;");
}
update("INSERT INTO program_products(programId, productId, dosesPerMonth, currentPrice, active) VALUES\n" +
"((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + product1 + "'), 30, 12.5, true),\n" +
"((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + product2 + "'), 30, 12.5, true);");
}
public void insertProgramProduct(String product, String program, String doses, String active) throws SQLException, IOException {
update("INSERT INTO program_products(programId, productId, dosesPerMonth, currentPrice, active) VALUES\n" +
"((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + product + "'), '" + doses + "', 12.5, '" + active + "');");
}
public void insertProgramProductsWithCategory(String product, String program) throws SQLException, IOException {
update("INSERT INTO program_products(programId, productId, dosesPerMonth, currentPrice, active) VALUES\n" +
"((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + product + "'), 30, 12.5, true);");
}
public void insertProgramProductISA(String program, String product, String whoRatio, String dosesPerYear, String wastageFactor,
String bufferPercentage, String minimumValue, String maximumValue, String adjustmentValue) throws SQLException, IOException {
update(
"INSERT INTO program_product_isa(programProductId, whoRatio, dosesPerYear, wastageFactor, bufferPercentage, minimumValue, maximumValue, adjustmentValue) VALUES\n" +
"((SELECT ID from program_products where programId = " +
"(SELECT ID from programs where code='" + program + "') and productId = " +
"(SELECT id from products WHERE code = '" + product + "'))," + whoRatio + "," + dosesPerYear + "," + wastageFactor + "," + bufferPercentage + "," + minimumValue + "," + maximumValue + "," + adjustmentValue + ");");
}
public void deleteFacilityApprovedProducts() throws SQLException {
update("DELETE FROM facility_approved_products");
}
public void insertFacilityApprovedProduct(String productCode, String programCode, String facilityTypeCode) throws Exception {
String facilityTypeIdQuery = format("(SELECT id FROM facility_types WHERE code = '%s')", facilityTypeCode);
String productIdQuery = format("(SELECT id FROM products WHERE code = '%s')", productCode);
String programIdQuery = format("(SELECT ID from programs where code = '%s' )", programCode);
String programProductIdQuery = format("(SELECT id FROM program_products WHERE programId = %s AND productId = %s)", programIdQuery, productIdQuery);
update(format(
"INSERT INTO facility_approved_products(facilityTypeId, programProductId, maxMonthsOfStock) VALUES (%s,%s,%d)",
facilityTypeIdQuery, programProductIdQuery, DEFAULT_MAX_MONTH_OF_STOCK));
}
public String fetchNonFullSupplyData(String productCode, String facilityTypeID, String programID) throws SQLException, IOException {
ResultSet rs = query("Select p.code, p.displayOrder, p.primaryName, pf.code as ProductForm," +
"p.strength as Strength, du.code as DosageUnit from facility_approved_products fap, " +
"program_products pp, products p, product_forms pf , dosage_units du where fap. facilityTypeId='" + facilityTypeID + "' " +
"and p. fullSupply = false and p.active=true and pp.programId='" + programID + "' and p. code='" + productCode + "' " +
"and pp.productId=p.id and fap. programProductId=pp.id and pp.active=true and pf.id=p.formId " +
"and du.id = p.dosageUnitId order by p. displayOrder asc;");
String nonFullSupplyValues = null;
if (rs.next()) {
nonFullSupplyValues = rs.getString("primaryName") + " " + rs.getString("productForm") + " " + rs.getString("strength") + " " + rs.getString("dosageUnit");
}
return nonFullSupplyValues;
}
public void insertSchedule(String scheduleCode, String scheduleName, String scheduleDesc) throws SQLException, IOException {
update("INSERT INTO processing_schedules(code, name, description) values('" + scheduleCode + "', '" + scheduleName + "', '" + scheduleDesc + "');");
}
public void insertProcessingPeriod(String periodName, String periodDesc, String periodStartDate,
String periodEndDate, Integer numberOfMonths, String scheduleCode) throws SQLException, IOException {
update("INSERT INTO processing_periods\n" +
"(name, description, startDate, endDate, numberOfMonths, scheduleId, modifiedBy) VALUES\n" +
"('" + periodName + "', '" + periodDesc + "', '" + periodStartDate + " 00:00:00', '" + periodEndDate + " 23:59:59', " + numberOfMonths + ", (SELECT id FROM processing_schedules WHERE code = '" + scheduleCode + "'), (SELECT id FROM users LIMIT 1));");
}
public void configureTemplate(String program) throws SQLException, IOException {
update("INSERT INTO program_rnr_columns\n" +
"(masterColumnId, programId, visible, source, formulaValidationRequired, position, label) VALUES\n" +
"(1, (select id from programs where code = '" + program + "'), true, 'U', false,1, 'Skip'),\n" +
"(2, (select id from programs where code = '" + program + "'), true, 'R', false,2, 'Product Code'),\n" +
"(3, (select id from programs where code = '" + program + "'), true, 'R', false,3, 'Product'),\n" +
"(4, (select id from programs where code = '" + program + "'), true, 'R', false,4, 'Unit/Unit of Issue'),\n" +
"(5, (select id from programs where code = '" + program + "'), true, 'U', false,5, 'Beginning Balance'),\n" +
"(6, (select id from programs where code = '" + program + "'), true, 'U', false,6, 'Total Received Quantity'),\n" +
"(7, (select id from programs where code = '" + program + "'), true, 'C', false,7, 'Total'),\n" +
"(8, (select id from programs where code = '" + program + "'), true, 'U', false,8, 'Total Consumed Quantity'),\n" +
"(9, (select id from programs where code = '" + program + "'), true, 'U', false,9, 'Total Losses / Adjustments'),\n" +
"(10, (select id from programs where code = '" + program + "'), true, 'C', true,10, 'Stock on Hand'),\n" +
"(11, (select id from programs where code = '" + program + "'), true, 'U', false,11, 'New Patients'),\n" +
"(12, (select id from programs where code = '" + program + "'), true, 'U', false,12, 'Total StockOut days'),\n" +
"(13, (select id from programs where code = '" + program + "'), true, 'C', false,13, 'Adjusted Total Consumption'),\n" +
"(14, (select id from programs where code = '" + program + "'), true, 'C', false,14, 'Average Monthly Consumption(AMC)'),\n" +
"(15, (select id from programs where code = '" + program + "'), true, 'C', false,15, 'Maximum Stock Quantity'),\n" +
"(16, (select id from programs where code = '" + program + "'), true, 'C', false,16, 'Calculated Order Quantity'),\n" +
"(17, (select id from programs where code = '" + program + "'), true, 'U', false,17, 'Requested quantity'),\n" +
"(18, (select id from programs where code = '" + program + "'), true, 'U', false,18, 'Requested quantity explanation'),\n" +
"(19, (select id from programs where code = '" + program + "'), true, 'U', false,19, 'Approved Quantity'),\n" +
"(20, (select id from programs where code = '" + program + "'), true, 'C', false,20, 'Packs to Ship'),\n" +
"(21, (select id from programs where code = '" + program + "'), true, 'R', false,21, 'Price per pack'),\n" +
"(22, (select id from programs where code = '" + program + "'), true, 'C', false,22, 'Total cost'),\n" +
"(23, (select id from programs where code = '" + program + "'), true, 'U', false,23, 'Expiration Date'),\n" +
"(24, (select id from programs where code = '" + program + "'), true, 'U', false,24, 'Remarks');");
}
public void configureTemplateForCommTrack(String program) throws SQLException, IOException {
update("INSERT INTO program_rnr_columns\n" +
"(masterColumnId, programId, visible, source, position, label) VALUES\n" +
"(2, (select id from programs where code = '" + program + "'), true, 'R', 1, 'Product Code'),\n" +
"(3, (select id from programs where code = '" + program + "'), true, 'R', 2, 'Product'),\n" +
"(4, (select id from programs where code = '" + program + "'), true, 'R', 3, 'Unit/Unit of Issue'),\n" +
"(5, (select id from programs where code = '" + program + "'), true, 'U', 4, 'Beginning Balance'),\n" +
"(6, (select id from programs where code = '" + program + "'), true, 'U', 5, 'Total Received Quantity'),\n" +
"(7, (select id from programs where code = '" + program + "'), true, 'C', 6, 'Total'),\n" +
"(8, (select id from programs where code = '" + program + "'), true, 'C', 7, 'Total Consumed Quantity'),\n" +
"(9, (select id from programs where code = '" + program + "'), true, 'U', 8, 'Total Losses / Adjustments'),\n" +
"(10, (select id from programs where code = '" + program + "'), true, 'U', 9, 'Stock on Hand'),\n" +
"(11, (select id from programs where code = '" + program + "'), true, 'U', 10, 'New Patients'),\n" +
"(12, (select id from programs where code = '" + program + "'), true, 'U', 11, 'Total StockOut days'),\n" +
"(13, (select id from programs where code = '" + program + "'), true, 'C', 12, 'Adjusted Total Consumption'),\n" +
"(14, (select id from programs where code = '" + program + "'), true, 'C', 13, 'Average Monthly Consumption(AMC)'),\n" +
"(15, (select id from programs where code = '" + program + "'), true, 'C', 14, 'Maximum Stock Quantity'),\n" +
"(16, (select id from programs where code = '" + program + "'), true, 'C', 15, 'Calculated Order Quantity'),\n" +
"(17, (select id from programs where code = '" + program + "'), true, 'U', 16, 'Requested quantity'),\n" +
"(18, (select id from programs where code = '" + program + "'), true, 'U', 17, 'Requested quantity explanation'),\n" +
"(19, (select id from programs where code = '" + program + "'), true, 'U', 18, 'Approved Quantity'),\n" +
"(20, (select id from programs where code = '" + program + "'), true, 'C', 19, 'Packs to Ship'),\n" +
"(21, (select id from programs where code = '" + program + "'), true, 'R', 20, 'Price per pack'),\n" +
"(22, (select id from programs where code = '" + program + "'), true, 'C', 21, 'Total cost'),\n" +
"(23, (select id from programs where code = '" + program + "'), true, 'U', 22, 'Expiration Date'),\n" +
"(24, (select id from programs where code = '" + program + "'), true, 'U', 23, 'Remarks');");
}
public Integer getOverriddenIsa(String facilityCode, String program, String product, String period) throws IOException, SQLException {
Integer overriddenIsa = 0;
float numberOfMonths = 0;
ResultSet rs2 = query("SELECT numberOfMonths FROM processing_periods where name ='" + period + "';");
if (rs2.next()) {
numberOfMonths = rs2.getFloat("numberOfMonths");
}
ResultSet rs = query("select overriddenIsa from facility_program_products " +
"where facilityId = '" + getAttributeFromTable("facilities", "id", "code", facilityCode) + "' and programProductId = " +
"(select id from program_products where programId='" + getAttributeFromTable("programs", "id", "code", program) + "' and productId='" + getAttributeFromTable("products", "id", "code", product) + "');");
if (rs.next()) {
overriddenIsa = Math.round(rs.getFloat("overriddenIsa") * numberOfMonths / Integer.parseInt(getAttributeFromTable("products", "packSize", "code", product)));
}
return overriddenIsa;
}
public void InsertOverriddenIsa(String facilityCode, String program, String product, int overriddenIsa) throws IOException, SQLException {
update("INSERT INTO facility_program_products (facilityId, programProductId,overriddenIsa) VALUES (" +
getAttributeFromTable("facilities", "id", "code", facilityCode) + ", (select id from program_products where programId='" +
getAttributeFromTable("programs", "id", "code", program) + "' and productId='" +
getAttributeFromTable("products", "id", "code", product) + "')," + overriddenIsa + ");");
}
public void updateOverriddenIsa(String facilityCode, String program, String product, String overriddenIsa) throws IOException, SQLException {
update("Update facility_program_products set overriddenIsa=" + overriddenIsa + " where facilityId='" +
getAttributeFromTable("facilities", "id", "code", facilityCode) + "' and programProductId = (select id from program_products where programId='" +
getAttributeFromTable("programs", "id", "code", program) + "' and productId='" +
getAttributeFromTable("products", "id", "code", product) + "');");
}
public String[] getProgramProductISA(String program, String product) throws IOException, SQLException {
String isaParams[] = new String[7];
ResultSet rs = query("select * from program_product_Isa where " +
" programProductId = (select id from program_products where programId='" +
getAttributeFromTable("programs", "id", "code", program) + "' and productId='" +
getAttributeFromTable("products", "id", "code", product) + "');");
if (rs.next()) {
isaParams[0] = rs.getString("whoRatio");
isaParams[1] = rs.getString("dosesPerYear");
isaParams[2] = rs.getString("wastageFactor");
isaParams[3] = rs.getString("bufferPercentage");
isaParams[4] = rs.getString("adjustmentValue");
isaParams[5] = rs.getString("minimumValue");
isaParams[6] = rs.getString("maximumValue");
}
return isaParams;
}
public void updateFacilityFieldBYCode(String field, String value, String code) throws IOException, SQLException {
update("update facilities set " + field + "='" + value + "' where code='" + code + "';");
}
public void insertSupplyLines(String supervisoryNode, String programCode, String facilityCode, boolean exportOrders) throws IOException, SQLException {
update("insert into supply_lines (description, supervisoryNodeId, programId, supplyingFacilityId,exportOrders) values" +
"('supplying node for " + programCode + "', " +
"(select id from supervisory_nodes where code = '" + supervisoryNode + "')," +
"(select id from programs where code='" + programCode + "')," +
"(select id from facilities where code = '" + facilityCode + "')," + exportOrders + ");");
}
public void updateSupplyLines(String previousFacilityCode, String newFacilityCode) throws IOException, SQLException {
update("update supply_lines SET supplyingFacilityId=(select id from facilities where code = '" + newFacilityCode + "') " +
"where supplyingFacilityId=(select id from facilities where code = '" + previousFacilityCode + "');");
}
public void insertValuesInRequisition(boolean emergencyRequisitionRequired) throws IOException, SQLException {
update("update requisition_line_items set beginningBalance=1, quantityReceived=1, quantityDispensed = 1, " +
"newPatientCount = 1, stockOutDays = 1, quantityRequested = 10, reasonForRequestedQuantity = 'bad climate', " +
"normalizedConsumption = 10, packsToShip = 1");
update("update requisitions set fullSupplyItemsSubmittedCost = 12.5000, nonFullSupplyItemsSubmittedCost = 0.0000");
if (emergencyRequisitionRequired) {
update("update requisitions set emergency='true'");
}
}
public void insertValuesInRegimenLineItems(String patientsOnTreatment, String patientsToInitiateTreatment, String patientsStoppedTreatment, String remarks) throws IOException, SQLException {
update("update regimen_line_items set patientsOnTreatment='" + patientsOnTreatment + "', patientsToInitiateTreatment='" + patientsToInitiateTreatment +
"', patientsStoppedTreatment='" + patientsStoppedTreatment + "',remarks='" + remarks + "';");
}
public void insertApprovedQuantity(Integer quantity) throws IOException, SQLException {
update("update requisition_line_items set quantityApproved=" + quantity);
}
public void updateRequisitionStatus(String status, String username, String program) throws IOException, SQLException {
update("update requisitions set status='" + status + "';");
ResultSet rs = query("select id from requisitions where programId = (select id from programs where code='" + program + "');");
while (rs.next()) {
update("insert into requisition_status_changes(rnrId, status, createdBy, modifiedBy) values(" + rs.getString("id") + ", '" + status + "', " +
"(select id from users where username = '" + username + "'), (select id from users where username = '" + username + "'));");
}
update("update requisitions set supervisoryNodeId = (select id from supervisory_nodes where code='N1');");
update("update requisitions set createdBy= (select id from users where username = '" + username + "') , modifiedBy= (select id from users where username = '" + username + "');");
}
public void updateRequisitionStatusByRnrId(String status, String username, int rnrId) throws IOException, SQLException {
update("update requisitions set status='" + status + "' where id=" + rnrId + ";");
update("insert into requisition_status_changes(rnrId, status, createdBy, modifiedBy) values(" + rnrId + ", '" + status + "', " +
"(select id from users where username = '" + username + "'), (select id from users where username = '" + username + "'));");
update("update requisitions set supervisoryNodeId = (select id from supervisory_nodes where code='N1');");
update("update requisitions set createdBy= (select id from users where username = '" + username + "') , modifiedBy= (select id from users where username = '" + username + "');");
}
public String getSupplyFacilityName(String supervisoryNode, String programCode) throws IOException, SQLException {
String facilityName = null;
ResultSet rs = query("select name from facilities where id=" +
"(select supplyingFacilityId from supply_lines where supervisoryNodeId=" +
"(select id from supervisory_nodes where code='" + supervisoryNode + "') and programId = " +
"(select id from programs where code='" + programCode + "'));");
if (rs.next()) {
facilityName = rs.getString("name");
}
return facilityName;
}
public int getMaxRnrID() throws IOException, SQLException {
int rnrId = 0;
ResultSet rs = query("select max(id) from requisitions");
if (rs.next()) {
rnrId = Integer.parseInt(rs.getString("max"));
}
return rnrId;
}
public void setupMultipleProducts(String program, String facilityType, int numberOfProductsOfEachType, boolean defaultDisplayOrder) throws SQLException, IOException {
update("delete from facility_approved_products;");
update("delete from program_products;");
update("delete from products;");
update("delete from product_categories;");
String productCodeFullSupply = "F";
String productCodeNonFullSupply = "NF";
update("INSERT INTO product_categories (code, name, displayOrder) values ('C1', 'Antibiotics', 1);");
ResultSet rs = query("Select id from product_categories where code='C1';");
int categoryId = 0;
if (rs.next()) {
categoryId = rs.getInt("id");
}
String insertSql;
insertSql = "INSERT INTO products (code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, type, primaryName, fullName, genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, dosesPerDispensingUnit, packSize, alternatePackSize, storeRefrigerated, storeRoomTemperature, hazardous, flammable, controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, packWidth, packHeight, packWeight, packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, categoryId) values";
for (int i = 0; i < numberOfProductsOfEachType; i++) {
if (defaultDisplayOrder) {
insertSql = insertSql + "('" + productCodeFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, 1, " + categoryId + "),\n";
insertSql = insertSql + "('" + productCodeNonFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, 1, " + categoryId + "),\n";
} else {
insertSql = insertSql + "('" + productCodeFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, " + i + ", " + categoryId + "),\n";
insertSql = insertSql + "('" + productCodeNonFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, " + i + ", " + categoryId + "),\n";
}
}
insertSql = insertSql.substring(0, insertSql.length() - 2) + ";\n";
update(insertSql);
insertSql = "INSERT INTO program_products(programId, productId, dosesPerMonth, currentPrice, active) VALUES\n";
for (int i = 0; i < numberOfProductsOfEachType; i++) {
insertSql = insertSql + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + productCodeFullSupply + i + "'), 30, 12.5, true),\n";
insertSql = insertSql + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + productCodeNonFullSupply + i + "'), 30, 12.5, true),\n";
}
insertSql = insertSql.substring(0, insertSql.length() - 2) + ";";
update(insertSql);
insertSql = "INSERT INTO facility_approved_products(facilityTypeId, programProductId, maxMonthsOfStock) VALUES\n";
for (int i = 0; i < numberOfProductsOfEachType; i++) {
insertSql = insertSql + "((select id from facility_types where name='" + facilityType + "'), (SELECT id FROM program_products WHERE programId=(SELECT ID from programs where code='" + program + "') AND productId=(SELECT id FROM products WHERE code='" + productCodeFullSupply + i + "')), 3),\n";
insertSql = insertSql + "((select id from facility_types where name='" + facilityType + "'), (SELECT id FROM program_products WHERE programId=(SELECT ID from programs where code='" + program + "') AND productId=(SELECT id FROM products WHERE code='" + productCodeNonFullSupply + i + "')), 3),\n";
}
insertSql = insertSql.substring(0, insertSql.length() - 2) + ";";
update(insertSql);
}
public void setupMultipleCategoryProducts(String program, String facilityType, int numberOfCategories, boolean defaultDisplayOrder) throws SQLException, IOException {
update("delete from facility_approved_products;");
update("delete from program_products;");
update("delete from products;");
update("delete from product_categories;");
String productCodeFullSupply = "F";
String productCodeNonFullSupply = "NF";
String insertSql = "INSERT INTO product_categories (code, name, displayOrder) values\n";
for (int i = 0; i < numberOfCategories; i++) {
if (defaultDisplayOrder) {
insertSql = insertSql + "('C" + i + "', 'Antibiotics" + i + "',1),\n";
} else {
insertSql = insertSql + "('C" + i + "', 'Antibiotics" + i + "'," + i + "),\n";
}
}
insertSql = insertSql.substring(0, insertSql.length() - 2) + ";";
update(insertSql);
insertSql = "INSERT INTO products (code, alternateItemCode, manufacturer, manufacturerCode, manufacturerBarcode, mohBarcode, gtin, type, primaryName, fullName, genericName, alternateName, description, strength, formId, dosageUnitId, dispensingUnit, dosesPerDispensingUnit, packSize, alternatePackSize, storeRefrigerated, storeRoomTemperature, hazardous, flammable, controlledSubstance, lightSensitive, approvedByWho, contraceptiveCyp, packLength, packWidth, packHeight, packWeight, packsPerCarton, cartonLength, cartonWidth, cartonHeight, cartonsPerPallet, expectedShelfLife, specialStorageInstructions, specialTransportInstructions, active, fullSupply, tracer, packRoundingThreshold, roundToZero, archived, displayOrder, categoryId) values\n";
for (int i = 0; i < 11; i++) {
insertSql = insertSql + "('" + productCodeFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, TRUE, TRUE, 1, FALSE, TRUE, 1, (select id from product_categories where code='C" + i + "')),\n";
insertSql = insertSql + "('" + productCodeNonFullSupply + i + "', 'a', 'Glaxo and Smith', 'a', 'a', 'a', 'a', 'antibiotic', 'antibiotic', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', 'TDF/FTC/EFV', '300/200/600', 2, 1, 'Strip', 10, 10, 30, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, 1, 2.2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 'a', 'a', TRUE, FALSE, TRUE, 1, FALSE, TRUE, 1, (select id from product_categories where code='C" + i + "')),\n";
}
insertSql = insertSql.substring(0, insertSql.length() - 2) + ";\n";
update(insertSql);
insertSql = "INSERT INTO program_products(programId, productId, dosesPerMonth, currentPrice, active) VALUES\n";
for (int i = 0; i < 11; i++) {
insertSql = insertSql + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + productCodeFullSupply + i + "'), 30, 12.5, true),\n";
insertSql = insertSql + "((SELECT ID from programs where code='" + program + "'), (SELECT id from products WHERE code = '" + productCodeNonFullSupply + i + "'), 30, 12.5, true),\n";
}
insertSql = insertSql.substring(0, insertSql.length() - 2) + ";";
update(insertSql);
insertSql = "INSERT INTO facility_approved_products(facilityTypeId, programProductId, maxMonthsOfStock) VALUES\n";
for (int i = 0; i < 11; i++) {
insertSql = insertSql + "((select id from facility_types where name='" + facilityType + "'), (SELECT id FROM program_products WHERE programId=(SELECT ID from programs where code='" + program + "') AND productId=(SELECT id FROM products WHERE code='" + productCodeFullSupply + i + "')), 3),\n";
insertSql = insertSql + "((select id from facility_types where name='" + facilityType + "'), (SELECT id FROM program_products WHERE programId=(SELECT ID from programs where code='" + program + "') AND productId=(SELECT id FROM products WHERE code='" + productCodeNonFullSupply + i + "')), 3),\n";
}
insertSql = insertSql.substring(0, insertSql.length() - 2) + ";";
update(insertSql);
}
public void assignRight(String roleName, String roleRight) throws SQLException, IOException {
update("INSERT INTO role_rights (roleId, rightName) VALUES" +
" ((select id from roles where name='" + roleName + "'), '" + roleRight + "');");
}
public void updatePacksToShip(String packsToShip) throws SQLException {
update("update requisition_line_items set packsToShip='" + packsToShip + "';");
}
public void insertPastPeriodRequisitionAndLineItems(String facilityCode, String program, String periodName, String product) throws IOException, SQLException {
update("DELETE FROM requisition_line_item_losses_adjustments;");
update("DELETE FROM requisition_line_items;");
update("DELETE FROM requisitions;");
update("INSERT INTO requisitions " +
"(facilityId, programId, periodId, status) VALUES " +
"((SELECT id FROM facilities WHERE code = '" + facilityCode + "'), (SELECT ID from programs where code='" + program + "'), (select id from processing_periods where name='" + periodName + "'), 'RELEASED');");
update("INSERT INTO requisition_line_items " +
"(rnrId, productCode, beginningBalance, quantityReceived, quantityDispensed, stockInHand, normalizedConsumption, " +
"dispensingUnit, maxMonthsOfStock, dosesPerMonth, dosesPerDispensingUnit, packSize,fullSupply) VALUES" +
"((SELECT id FROM requisitions), '" + product + "', '0', '11' , '1', '10', '1' ,'Strip','0', '0', '0', '10','t');");
}
public void insertRoleAssignmentForDistribution(String userName, String roleName, String deliveryZoneCode) throws SQLException, IOException {
update("INSERT INTO role_assignments\n" +
" (userId, roleId, deliveryZoneId) VALUES\n" +
" ((SELECT id FROM USERS WHERE username='" + userName + "'), (SELECT id FROM roles WHERE name = '" + roleName + "'),\n" +
" (SELECT id FROM delivery_zones WHERE code='" + deliveryZoneCode + "'));");
}
public void deleteDeliveryZoneToFacilityMapping(String deliveryZoneName) throws SQLException, IOException {
update("delete from delivery_zone_members where deliveryZoneId in (select id from delivery_zones where name='" + deliveryZoneName + "');");
}
public void deleteProgramToFacilityMapping(String programCode) throws SQLException, IOException {
update("delete from programs_supported where programId in (select id from programs where code='" + programCode + "');");
}
public void updateActiveStatusOfFacility(String facilityCode, String active) throws SQLException, IOException {
update("update facilities set active='" + active + "' where code='" + facilityCode + "';");
}
public void updatePopulationOfFacility(String facility, String population) throws SQLException, IOException {
update("update facilities set catchmentPopulation=" + population + " where code='" + facility + "';");
}
public void insertDeliveryZone(String code, String name) throws SQLException {
update("INSERT INTO delivery_zones ( code ,name)values\n" +
"('" + code + "','" + name + "');");
}
public void insertWarehouseIntoSupplyLinesTable(String facilityCodeFirst, String programFirst, String supervisoryNode, boolean exportOrders) throws SQLException {
update("INSERT INTO supply_lines (supplyingFacilityId, programId, supervisoryNodeId, description, exportOrders, createdBy, modifiedBy) values " +
"(" + "(select id from facilities where code = '" + facilityCodeFirst + "')," + "(select id from programs where name ='" + programFirst + "')," + "(select id from supervisory_nodes where code='" + supervisoryNode + "'),'warehouse', " + exportOrders + ", '1', '1');");
}
public void insertDeliveryZoneMembers(String code, String facility) throws SQLException {
update("INSERT INTO delivery_zone_members ( deliveryZoneId ,facilityId )values\n" +
"((select id from delivery_zones where code ='" + code + "'),(select id from facilities where code ='" + facility + "'));");
}
public void insertDeliveryZoneProgramSchedule(String code, String program, String scheduleCode) throws SQLException {
update("INSERT INTO delivery_zone_program_schedules\n" +
"(deliveryZoneId, programId, scheduleId ) values(\n" +
"(select id from delivery_zones where code='" + code + "'),\n" +
"(select id from programs where code='" + program + "'),\n" +
"(select id from processing_schedules where code='" + scheduleCode + "')\n" +
");");
}
public void insertProcessingPeriodForDistribution(int numberOfPeriodsRequired, String schedule) throws IOException, SQLException {
for (int counter = 1; counter <= numberOfPeriodsRequired; counter++) {
String startDate = "2013-01-0" + counter;
String endDate = "2013-01-0" + counter;
insertProcessingPeriod("Period" + counter, "PeriodDecs" + counter, startDate, endDate, 1, schedule);
}
}
public void updateActiveStatusOfProgram(String programCode, boolean status) throws SQLException {
update("update programs SET active=" + status + " where code='" + programCode + "';");
}
public void insertRegimenTemplateColumnsForProgram(String programName) throws SQLException {
update("INSERT INTO program_regimen_columns(name, programId, label, visible, dataType) values\n" +
"('code',(SELECT id FROM programs WHERE name='" + programName + "'), 'header.code',true,'regimen.reporting.dataType.text'),\n" +
"('name',(SELECT id FROM programs WHERE name='" + programName + "'),'header.name',true,'regimen.reporting.dataType.text'),\n" +
"('patientsOnTreatment',(SELECT id FROM programs WHERE name='" + programName + "'),'Number of patients on treatment',true,'regimen.reporting.dataType.numeric'),\n" +
"('patientsToInitiateTreatment',(SELECT id FROM programs WHERE name='" + programName + "'),'Number of patients to be initiated treatment',true,'regimen.reporting.dataType.numeric'),\n" +
"('patientsStoppedTreatment',(SELECT id FROM programs WHERE name='" + programName + "'),'Number of patients stopped treatment',true,'regimen.reporting.dataType.numeric'),\n" +
"('remarks',(SELECT id FROM programs WHERE name='" + programName + "'),'Remarks',true,'regimen.reporting.dataType.text');");
}
public void insertRegimenTemplateConfiguredForProgram(String programName, String categoryCode, String code, String name, boolean active) throws SQLException {
update("update programs set regimenTemplateConfigured='true' where name='" + programName + "';");
update("INSERT INTO regimens\n" +
" (programId, categoryId, code, name, active,displayOrder) VALUES\n" +
" ((SELECT id FROM programs WHERE name='" + programName + "'), (SELECT id FROM regimen_categories WHERE code = '" + categoryCode + "'),\n" +
" '" + code + "','" + name + "','" + active + "',1);");
}
public void setRegimenTemplateConfiguredForAllPrograms(boolean flag) throws SQLException {
update("update programs set regimenTemplateConfigured='" + flag + "';");
}
public String getAllActivePrograms() throws SQLException {
String programsString = "";
ResultSet rs = query("select * from programs where active=true;");
while (rs.next()) {
programsString = programsString + rs.getString("name");
}
return programsString;
}
public void updateProgramRegimenColumns(String programName, String regimenColumnName, boolean visible) throws SQLException {
update("update program_regimen_columns set visible=" + visible + " where name ='" + regimenColumnName +
"'and programId=(SELECT id FROM programs WHERE name='" + programName + "');");
}
public void setupOrderFileConfiguration(String filePrefix, String headerInFile) throws IOException, SQLException {
update("DELETE FROM order_configuration;");
update("INSERT INTO order_configuration \n" +
" (filePrefix, headerInFile) VALUES\n" +
" ('" + filePrefix + "', '" + headerInFile + "');");
}
public void setupShipmentFileConfiguration(String headerInFile) throws IOException, SQLException {
update("DELETE FROM shipment_configuration;");
update("INSERT INTO shipment_configuration(headerInFile) VALUES('" + headerInFile + "')");
}
public void setupOrderFileOpenLMISColumns(String dataFieldLabel, String includeInOrderFile, String columnLabel, int position, String Format) throws IOException, SQLException {
update("UPDATE order_file_columns SET " +
"includeInOrderFile='" + includeInOrderFile + "', columnLabel='" + columnLabel + "', position=" + position + ", format='" + Format + "' where dataFieldLabel='" + dataFieldLabel + "'");
}
public void deleteOrderFileNonOpenLMISColumns() throws SQLException {
update("DELETE FROM order_file_columns where openLMISField = FALSE");
}
public void setupOrderFileNonOpenLMISColumns(String dataFieldLabel, String includeInOrderFile, String columnLabel, int position) throws IOException, SQLException {
update("INSERT INTO order_file_columns (dataFieldLabel, includeInOrderFile, columnLabel, position, openLMISField) " +
"VALUES ('" + dataFieldLabel + "','" + includeInOrderFile + "','" + columnLabel + "'," + position + ", FALSE)");
}
public void updateProductToHaveGroup(String product, String productGroup) throws SQLException {
update("UPDATE products set productGroupId = (SELECT id from product_groups where code = '" + productGroup + "') where code = '" + product + "'");
}
public void deleteReport(String reportName) throws SQLException {
update("DELETE FROM report_templates where name = '" + reportName + "'");
}
public void insertOrders(String status, String username, String program) throws IOException, SQLException {
ResultSet rs = query("select id from requisitions where programId=(select id from programs where code='" + program + "');");
while (rs.next()) {
update("update requisitions set status='RELEASED' where id =" + rs.getString("id"));
update("insert into orders(Id, status,supplyLineId, createdBy, modifiedBy) values(" + rs.getString("id") + ", '" + status + "', (select id from supply_lines where supplyingFacilityId = " +
"(select facilityId from fulfillment_role_assignments where userId = " +
"(select id from users where username = '" + username + "')) limit 1) ," +
"(select id from users where username = '" + username + "'), (select id from users where username = '" + username + "'));");
}
}
public void setupUserForFulfillmentRole(String username, String roleName, String facilityCode) throws IOException, SQLException {
update("insert into fulfillment_role_assignments(userId, roleId,facilityId) values((select id from users where userName = '" + username +
"'),(select id from roles where name = '" + roleName + "')," +
"(select id from facilities where code = '" + facilityCode + "'));");
}
public Map<String, String> getFacilityVisitDetails(String facilityCode) throws SQLException {
Map<String, String> facilityVisitsDetails = new HashMap<>();
try (ResultSet rs = query("SELECT observations,confirmedByName,confirmedByTitle,verifiedByName,verifiedByTitle from facility_visits" +
" WHERE facilityId = (SELECT id FROM facilities WHERE code = '" + facilityCode + "');")) {
while (rs.next()) {
facilityVisitsDetails.put("observations", rs.getString("observations"));
facilityVisitsDetails.put("confirmedByName", rs.getString("confirmedByName"));
facilityVisitsDetails.put("confirmedByTitle", rs.getString("confirmedByTitle"));
facilityVisitsDetails.put("verifiedByName", rs.getString("verifiedByName"));
facilityVisitsDetails.put("verifiedByTitle", rs.getString("verifiedByTitle"));
}
return facilityVisitsDetails;
}
}
public void disableFacility(String warehouseName) throws SQLException {
update("UPDATE facilities SET enabled='false' WHERE name='" + warehouseName + "';");
}
public void enableFacility(String warehouseName) throws SQLException {
update("UPDATE facilities SET enabled='true' WHERE name='" + warehouseName + "';");
}
public int getPODLineItemQuantityReceived(long orderId, String productCode) throws Exception {
try (ResultSet rs1 = query("SELECT id FROM pod WHERE OrderId = %d", orderId)) {
if (rs1.next()) {
int podId = rs1.getInt("id");
ResultSet rs2 = query("SELECT quantityReceived FROM pod_line_items WHERE podId = %d and productCode='%s'", podId, productCode);
if (rs2.next()) {
return rs2.getInt("quantityReceived");
}
}
}
return -1;
}
public void setExportOrdersFlagInSupplyLinesTable(boolean flag, String facilityCode) throws SQLException {
update("UPDATE supply_lines SET exportOrders='" + flag + "' WHERE supplyingFacilityId=(select id from facilities where code='" + facilityCode + "');");
}
public void enterValidDetailsInFacilityFtpDetailsTable(String facilityCode) throws SQLException {
update(
"INSERT INTO facility_ftp_details(facilityId, serverHost, serverPort, username, password, localFolderPath) VALUES" + "((SELECT id FROM facilities WHERE code = '%s' ), '192.168.34.1', 21, 'openlmis', 'openlmis', '/ftp');",
facilityCode);
}
public List<Integer> getAllProgramsOfFacility(String facilityCode) throws SQLException {
List<Integer> l1 = new ArrayList<>();
ResultSet rs = query(
"SELECT programId FROM programs_supported WHERE facilityId = (SELECT id FROM facilities WHERE code ='%s')",
facilityCode);
while (rs.next()) {
l1.add(rs.getInt(1));
}
return l1;
}
public String getProgramFieldForProgramIdAndFacilityCode(int programId, String facilityCode, String field) throws SQLException {
String res = null;
ResultSet rs = query(
"SELECT %s FROM programs_supported WHERE programId = %d AND facilityId = (SELECT id FROM facilities WHERE code = '%s')",
field,
programId,
facilityCode);
if (rs.next()) {
res = rs.getString(1);
}
return res;
}
public Date getProgramStartDateForProgramIdAndFacilityCode(int programId, String facilityCode) throws SQLException {
Date date = null;
ResultSet rs = query(
"SELECT startDate FROM programs_supported WHERE programId = %d AND facilityId = (SELECT id FROM facilities WHERE code ='%s')",
programId,
facilityCode);
if (rs.next()) {
date = rs.getDate(1);
}
return date;
}
public void changeVirtualFacilityTypeId(String facilityCode, int facilityTypeId) throws SQLException {
update("UPDATE facilities SET typeid=" + facilityTypeId + "WHERE code='" + facilityCode + "';");
}
public void deleteCurrentPeriod() throws SQLException {
update("delete from processing_periods where endDate>=NOW()");
}
public void updateProgramsSupportedByField(String field, String newValue, String facilityCode) throws SQLException {
update("Update programs_supported set " + field + "='" + newValue + "' where facilityId=(Select id from facilities where code ='" + facilityCode + "');");
}
public void deleteSupervisoryRoleFromRoleAssignment() throws SQLException {
update("delete from role_assignments where supervisoryNodeId is not null;");
}
public void deleteRnrTemplate() throws SQLException {
update("delete from program_rnr_columns");
}
public void deleteProductAvailableAtFacility(String productCode, String programCode, String facilityCode) throws SQLException {
update("delete from facility_approved_products where facilityTypeId=(select typeId from facilities where code='" + facilityCode + "') " +
"and programproductid=(select id from program_products where programId=(select id from programs where code='" + programCode + "')" +
"and productid=(select id from products where code='" + productCode + "'));");
}
public void updateProductFullSupplyStatus(String productCode, boolean fullSupply) throws SQLException {
update("UPDATE products SET fullSupply=" + fullSupply + " WHERE code='" + productCode + "';");
}
public void updateConfigureTemplateValidationFlag(String programCode, String flag) throws SQLException {
update("UPDATE program_rnr_columns set formulaValidationRequired ='" + flag + "' WHERE programId=" +
"(SELECT id from programs where code='" + programCode + "');");
}
public void updateConfigureTemplate(String programCode, String fieldName, String fieldValue, String visibilityFlag, String rnrColumnName) throws SQLException {
update("UPDATE program_rnr_columns SET visible ='" + visibilityFlag + "', " + fieldName + "='" + fieldValue + "' WHERE programId=" +
"(SELECT id from programs where code='" + programCode + "')" +
"AND masterColumnId =(SELECT id from master_rnr_columns WHERE name = '" + rnrColumnName + "') ;");
}
public void deleteConfigureTemplate(String program) throws SQLException {
update("DELETE FROM program_rnr_columns where programId=(select id from programs where code = '" + program + "');");
}
public String getRequisitionLineItemFieldValue(Long requisitionId, String field, String productCode) throws SQLException {
String value = null;
ResultSet rs = query("SELECT %s FROM requisition_line_items WHERE rnrId = %d AND productCode = '%s'", field, requisitionId, productCode);
if (rs.next()) {
value = rs.getString(field);
}
return value;
}
public void updateProductFullSupplyFlag(boolean isFullSupply, String productCode) throws SQLException {
update("UPDATE products SET fullSupply = %b WHERE code = '%s'", isFullSupply, productCode);
}
public void insertRoleAssignmentForSupervisoryNode(String userID, String roleName, String supervisoryNode, String programCode) throws SQLException {
update(" INSERT INTO role_assignments\n" +
" (userId, roleId, programId, supervisoryNodeId) VALUES \n" +
" ('" + userID + "', (SELECT id FROM roles WHERE name = '" + roleName + "')," +
" (SELECT id from programs WHERE code='" + programCode + "'), " +
"(SELECT id from supervisory_nodes WHERE code = '" + supervisoryNode + "'));");
}
public void insertRequisitionGroupProgramScheduleForProgram(String requisitionGroupCode, String programCode, String scheduleCode) throws SQLException {
update("delete from requisition_group_program_schedules where programId=(select id from programs where code='" + programCode + "');");
update(
"insert into requisition_group_program_schedules ( requisitionGroupId , programId , scheduleId , directDelivery ) values\n" +
"((select id from requisition_groups where code='" + requisitionGroupCode + "'),(select id from programs where code='" + programCode + "')," +
"(select id from processing_schedules where code='" + scheduleCode + "'),TRUE);");
}
public void updateCreatedDateInRequisitionStatusChanges(String newDate, Long rnrId) throws SQLException {
update("update requisition_status_changes SET createdDate= '" + newDate + "' WHERE rnrId=" + rnrId + ";");
}
public void updateCreatedDateInPODLineItems(String newDate, Long rnrId) throws SQLException {
update("update pod SET createdDate= '" + newDate + "' WHERE orderId=" + rnrId + ";");
}
public void updatePeriodIdInRequisitions(Long rnrId) throws SQLException {
Integer reqId = 0;
ResultSet rs = query("select " + "periodId" + " from requisitions where id= " + rnrId + ";");
if (rs.next()) {
reqId = Integer.parseInt(rs.getString(1));
}
reqId = reqId - 1;
update("update requisitions SET periodId= '" + reqId + "' WHERE id=" + rnrId + ";");
}
public void updateProductsByField(String field, String fieldValue, String productCode) throws SQLException {
update("update products set " + field + "=" + fieldValue + " where code='" + productCode + "';");
}
public void updateSupervisoryNodeForRequisitionGroup(String requisitionGroup,
String supervisoryNodeCode) throws SQLException {
update("update requisition_groups set supervisoryNodeId=(select id from supervisory_nodes where code='" + supervisoryNodeCode +
"') where code='" + requisitionGroup + "';");
}
public void updateOrderStatus() throws IOException, SQLException {
update("update orders set status='RECEIVED'");
}
public void updateRequisitionToEmergency() throws IOException, SQLException {
update("update requisitions set Emergency=true");
}
public void deleteSupplyLine() throws IOException, SQLException {
update("delete from supply_lines where description='supplying node for MALARIA'");
}
public Map<String, String> getEpiUseDetails(String productGroupCode, String facilityCode) throws SQLException {
return select("SELECT * FROM epi_use_line_items WHERE productGroupName = " +
"(SELECT name FROM product_groups where code = '%s') AND epiUseId=(Select id from epi_use where facilityId=" +
"(Select id from facilities where code ='%s'));", productGroupCode, facilityCode).get(0);
}
public void updateBudgetFlag(String ProgramName, Boolean Flag) throws IOException, SQLException {
update("update programs set budgetingApplies ='" + Flag + "' where name ='" + ProgramName + "';");
}
public void insertBudgetData() throws IOException, SQLException {
update("INSERT INTO budget_file_info VALUES (1,'abc.csv','f',200,'12/12/13',200,'12/12/13');");
update(
"INSERT INTO budget_line_items VALUES (1,(select id from processing_periods where name='current Period'),1,'01/01/2013',200,'hjhj',200,'12/12/2013',200,'12/12/2013',(select id from facilities where code='F10'),1);");
}
public void updateBudgetLineItemsByField(String field, String newValue) throws SQLException {
update("UPDATE budget_line_items SET " + field + " ='" + newValue + "';");
}
public void addRefrigeratorToFacility(String brand, String model, String serialNumber, String facilityCode) throws SQLException {
update("INSERT INTO refrigerators(brand, model, serialNumber, facilityId, createdBy , modifiedBy) VALUES" +
"('" + brand + "','" + model + "','" + serialNumber + "',(SELECT id FROM facilities WHERE code = '" + facilityCode + "'),1,1);");
}
public ResultSet getRefrigeratorReadings(String refrigeratorSerialNumber, String facilityCode) throws SQLException {
ResultSet resultSet = query("SELECT * FROM refrigerator_readings WHERE refrigeratorId = " +
"(SELECT id FROM refrigerators WHERE serialNumber = '%s' AND facilityId = " +
"(SELECT id FROM facilities WHERE code = '%s'));", refrigeratorSerialNumber, facilityCode);
resultSet.next();
return resultSet;
}
public ResultSet getRefrigeratorProblems(Long readingId) throws SQLException {
return query("SELECT * FROM refrigerator_problems WHERE readingId = %d", readingId);
}
public void updateProcessingPeriodByField(String field, String fieldValue, String periodName, String scheduleCode) throws SQLException {
update("update processing_periods set " + field + "=" + fieldValue +
" where name='" + periodName + "'" +
" and scheduleId =" +
"(Select id from processing_schedules where code = '" + scheduleCode + "');");
}
public ResultSet getRefrigeratorsData(String refrigeratorSerialNumber, String facilityCode) throws SQLException {
ResultSet resultSet = query("SELECT * FROM refrigerators WHERE serialNumber = " + refrigeratorSerialNumber
+ " AND facilityId = " + getAttributeFromTable("facilities", "id", "code", facilityCode));
resultSet.next();
return resultSet;
}
public String getAttributeFromTable(String tableName, String attribute, String queryColumn, String queryParam) throws SQLException {
String returnValue = null;
ResultSet resultSet = query("select * from %s where %s in ('%s');", tableName, queryColumn, queryParam);
if (resultSet.next()) {
returnValue = resultSet.getString(attribute);
}
return returnValue;
}
public String getRowsCountFromDB(String tableName) throws IOException, SQLException {
String rowCount = null;
ResultSet rs = query("SELECT count(*) as count from " + tableName + "");
if (rs.next()) {
rowCount = rs.getString("count");
}
return rowCount;
}
public String getCreatedDate(String tableName, String dateFormat) throws SQLException {
String createdDate = null;
ResultSet rs = query("SELECT to_char(createdDate, '" + dateFormat + "' ) from " + tableName);
if (rs.next()) {
createdDate = rs.getString(1);
}
return createdDate;
}
public Integer getRequisitionGroupId(String facilityCode) throws SQLException {
return Integer.parseInt(getAttributeFromTable("requisition_group_members", "requisitionGroupId", "facilityId", getAttributeFromTable("facilities", "id", "code", facilityCode)));
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
ae6fe5a3b8f4e5edb37d522074d9c7816214c5b4 | 8361c48221ae1b5627a22ba04b313b447feb933f | /src/MatrixRotationMXN.java | c18e34807ad78f69c12e33aae2aa0644301b101e | [] | no_license | YesVen/CrackingTheCodingWithHackerRankAndLeetCode | 07f92da263ef1930d80efbcabb84fc7976324bd0 | 113c57bb34e43dabb7bf8ccab27e11646faae611 | refs/heads/master | 2020-03-21T11:11:28.339119 | 2016-12-08T23:07:16 | 2016-12-08T23:07:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,962 | java | import java.util.Scanner;
public class MatrixRotationMXN {
public static void main(String[] args){
int[][] matrix, matrix90Right, matrix90Left;
Scanner in = new Scanner(System.in);
int numberOfRows = in.nextInt();
int numberOfColumns = in.nextInt();
matrix = new int[numberOfRows][numberOfColumns];
for(int i =0; i<numberOfRows;i++){
for(int j=0; j<numberOfColumns;j++){
matrix[i][j]=in.nextInt();
}
}
System.out.println("\nOriginal Matrix:\n");
for(int i =0; i<numberOfRows;i++){
for(int j=0; j<numberOfColumns;j++){
System.out.print(matrix[i][j]+ " ");
}
System.out.println();
}
MatrixRotationMXN obj = new MatrixRotationMXN();
matrix90Right = obj.matrixRotation90Right(matrix, numberOfRows, numberOfColumns);
matrix90Left = obj.matrixRotation90Left(matrix, numberOfRows, numberOfColumns);
System.out.println("\n90 degree Right Rotated Matrix:\n");
for(int i =0; i<numberOfColumns;i++){
for(int j=0; j<numberOfRows;j++){
System.out.print(matrix90Right[i][j]+ " ");
}
System.out.println();
}
System.out.println("\n90 degree Left Rotated Matrix:\n");
for(int i =0; i<numberOfColumns;i++){
for(int j=0; j<numberOfRows;j++){
System.out.print(matrix90Left[i][j]+ " ");
}
System.out.println();
}
}
int[][] matrixRotation90Right(int[][] matrix, int row, int column){
int resRow = column;
int resColumn = row;
int[][] resMatrix = new int[resRow][resColumn];
for(int i = 0; i < row; i++){
for(int j = 0; j < column; j++){
resMatrix[j][resColumn - 1 - i] = matrix[i][j];
}
}
return resMatrix;
}
int[][] matrixRotation90Left(int[][] matrix, int row, int column){
int resRow = column;
int resColumn = row;
int[][] resMatrix = new int[resRow][resColumn];
for(int i = 0; i < row; i++){
for(int j = 0; j < column; j++){
resMatrix[resRow - 1 - j][i] = matrix[i][j];
}
}
return resMatrix;
}
} | [
"bharatbhavsar007@gmail.com"
] | bharatbhavsar007@gmail.com |
4206b0de0c69279df15a8f2c24f0d8d03f8a1933 | ce2beb45ca8dedcdeb8b781995161fce7ad13a8d | /src/main/java/com/thinkxfactor/zomatoplus/controller/RestuarentController.java | e8cd6a12cd510a409e991e2a43073555bdb419a9 | [] | no_license | LordKostoo/zomatoplus | ed6b5dc872e74bcc22f1b477489db0d19c6d9f13 | 15a39f3dd4a4c67aa102b6100d41e6267630e423 | refs/heads/master | 2020-03-21T13:28:04.835408 | 2018-06-28T19:39:26 | 2018-06-28T19:39:26 | 138,607,263 | 0 | 0 | null | 2018-06-25T14:36:19 | 2018-06-25T14:36:18 | null | UTF-8 | Java | false | false | 2,068 | java | package com.thinkxfactor.zomatoplus.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.thinkxfactor.zomatoplus.models.Item;
import com.thinkxfactor.zomatoplus.models.Restuarent;
import com.thinkxfactor.zomatoplus.models.User;
import com.thinkxfactor.zomatoplus.repository.ItemRepository;
import com.thinkxfactor.zomatoplus.repository.RestaurantRepository;
import com.thinkxfactor.zomatoplus.repository.UserRepository;
@RestController
@RequestMapping("/restuarent")
public class RestuarentController {
@Autowired
private RestaurantRepository restaurantRepository;
@Autowired
private ItemRepository itemRepository;
@PostMapping("/create")
public Restuarent createRestuarent(@RequestBody Restuarent res) {
Restuarent persistedRest = restaurantRepository.save(res);
return persistedRest;
}
@GetMapping("/getall")
public List<Restuarent> ListAllRestuarent() {
List<Restuarent> listofrests = restaurantRepository.findAll();
return listofrests;
}
@PostMapping("/additem")
public Item AddItem(@RequestBody Item items) {
Item persisteditem=itemRepository.save(items);
return persisteditem;}
@PostMapping("/findrest")
public Restuarent restfind(@RequestBody Restuarent rest) {
Restuarent persistRest=restaurantRepository.findByNameAndAddress(rest.getName(),rest.getAddress());
return persistRest;
}
@PostMapping("/finditem")
public Item finditem(@RequestBody Item items) {
Item persistItem= itemRepository.findByRestaurantIdAndName(items.getRestaurantId(), items.getName());
return persistItem;
}
@GetMapping("/getallitem")
public List<Item> ListAllItem() {
List<Item> listofitem = itemRepository.findAll();
return listofitem;
}
} | [
"kaustuvsaha36@gmail.com"
] | kaustuvsaha36@gmail.com |
218a661b91961f4c95113d3ef5c2603fd833f78e | 0aa49746d7476aca477f0e56e164e8e4741a5051 | /src/main/java/org/primefaces/component/api/Widget.java | 0d49fe9e8fb73aba8c2c5c5e4a15624809ffc532 | [] | no_license | loictalbot/Primefaces | e492c2f3388058777a9341d1994a19350e8aaa6d | 523a17f3bd7da0adfa69ef7c625366ac58d3612f | refs/heads/master | 2020-05-18T22:19:07.942761 | 2013-09-16T20:20:32 | 2013-09-16T20:20:32 | 12,877,720 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 700 | java | /*
* Copyright 2009-2013 PrimeTek.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.primefaces.component.api;
public interface Widget {
public String resolveWidgetVar();
}
| [
"loic@mixandplay.com"
] | loic@mixandplay.com |
66e8a8fe98529b60f7b2a6181e3f032da3426fd5 | a42f1f343b4282cfd42fbfa41a3923333dc1cb5e | /generator/src/main/java/org/jsonx/ObjectModel.java | 0f79da4d903c1e71da942d5106be0cc314219914 | [
"MIT"
] | permissive | iskorn/jsonx | 82f12638ad6a017cc42b1c90963ce9aab0cedd5f | 87f610c3082d1474fc87e0d4c56204c71b5c34cc | refs/heads/master | 2020-05-23T17:34:41.949057 | 2019-05-15T14:01:19 | 2019-05-15T14:01:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 21,555 | java | /* Copyright (c) 2017 JSONx
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* You should have received a copy of The MIT License (MIT) along with this
* program. If not, see <http://opensource.org/licenses/MIT/>.
*/
package org.jsonx;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.jsonx.www.schema_0_2_2.xL0gluGCXYYJc;
import org.libj.lang.IllegalAnnotationException;
import org.libj.util.Classes;
import org.libj.util.Iterators;
import org.libj.util.Strings;
import org.openjax.xml.api.XmlElement;
final class ObjectModel extends Referrer<ObjectModel> {
private static xL0gluGCXYYJc.Schema.Object type(final schema.ObjectType jsonx, final String name) {
final xL0gluGCXYYJc.Schema.Object xsb = new xL0gluGCXYYJc.Schema.Object();
if (name != null)
xsb.setName$(new xL0gluGCXYYJc.Schema.Object.Name$(name));
if (jsonx.getJsd_3aAbstract() != null)
xsb.setAbstract$(new xL0gluGCXYYJc.Schema.Object.Abstract$(jsonx.getJsd_3aAbstract()));
return xsb;
}
private static xL0gluGCXYYJc.$Object property(final schema.ObjectProperty jsonx, final String name) {
final xL0gluGCXYYJc.$Object xsb = new xL0gluGCXYYJc.$Object() {
private static final long serialVersionUID = 5201562440101597524L;
@Override
protected xL0gluGCXYYJc.$Member inherits() {
return new xL0gluGCXYYJc.$ObjectMember.Property();
}
};
if (name != null)
xsb.setName$(new xL0gluGCXYYJc.$Object.Name$(name));
if (jsonx.getJsd_3aNullable() != null)
xsb.setNullable$(new xL0gluGCXYYJc.$Object.Nullable$(jsonx.getJsd_3aNullable()));
if (jsonx.getJsd_3aUse() != null)
xsb.setUse$(new xL0gluGCXYYJc.$Object.Use$(xL0gluGCXYYJc.$Object.Use$.Enum.valueOf(jsonx.getJsd_3aUse())));
if (jsonx.getJsd_3aExtends() != null)
xsb.setExtends$(new xL0gluGCXYYJc.$ObjectMember.Extends$(jsonx.getJsd_3aExtends()));
return xsb;
}
static xL0gluGCXYYJc.$ObjectMember jsdToXsb(final schema.Object jsd, final String name) {
final xL0gluGCXYYJc.$ObjectMember xsb;
if (jsd instanceof schema.ObjectType)
xsb = type((schema.ObjectType)jsd, name);
else if (jsd instanceof schema.ObjectProperty)
xsb = property((schema.ObjectProperty)jsd, name);
else
throw new UnsupportedOperationException("Unsupported type: " + jsd.getClass().getName());
if (jsd.getJsd_3aExtends() != null)
xsb.setExtends$(new xL0gluGCXYYJc.$ObjectMember.Extends$(jsd.getJsd_3aExtends()));
if (jsd.getJsd_3aProperties() != null) {
for (final Map.Entry<String,Object> property : jsd.getJsd_3aProperties()._2e_2a.entrySet()) {
if (property.getValue() instanceof schema.AnyProperty)
xsb.addProperty(AnyModel.jsdToXsb((schema.AnyProperty)property.getValue(), property.getKey()));
else if (property.getValue() instanceof schema.ArrayProperty)
xsb.addProperty(ArrayModel.jsdToXsb((schema.ArrayProperty)property.getValue(), property.getKey()));
else if (property.getValue() instanceof schema.BooleanProperty)
xsb.addProperty(BooleanModel.jsdToXsb((schema.BooleanProperty)property.getValue(), property.getKey()));
else if (property.getValue() instanceof schema.NumberProperty)
xsb.addProperty(NumberModel.jsdToXsb((schema.NumberProperty)property.getValue(), property.getKey()));
else if (property.getValue() instanceof schema.ReferenceProperty)
xsb.addProperty(Reference.jsdToXsb((schema.ReferenceProperty)property.getValue(), property.getKey()));
else if (property.getValue() instanceof schema.StringProperty)
xsb.addProperty(StringModel.jsdToXsb((schema.StringProperty)property.getValue(), property.getKey()));
else if (property.getValue() instanceof schema.ObjectProperty)
xsb.addProperty(ObjectModel.jsdToXsb((schema.ObjectProperty)property.getValue(), property.getKey()));
else
throw new UnsupportedOperationException("Unsupported JSONx type: " + property.getValue().getClass().getName());
}
}
return xsb;
}
static ObjectModel declare(final Registry registry, final xL0gluGCXYYJc.Schema.Object binding) {
return registry.declare(binding).value(new ObjectModel(registry, binding), null);
}
static ObjectModel declare(final Registry registry, final ObjectModel referrer, final xL0gluGCXYYJc.$Object binding) {
return registry.declare(binding).value(new ObjectModel(registry, binding), referrer);
}
static Member referenceOrDeclare(final Registry registry, final Referrer<?> referrer, final ObjectProperty property, final Field field) {
if (!isAssignable(field, JxObject.class, false, property.nullable(), property.use()))
throw new IllegalAnnotationException(property, field.getDeclaringClass().getName() + "." + field.getName() + ": @" + ObjectProperty.class.getSimpleName() + " can only be applied to required or not-nullable fields of JxObject type, or optional and nullable fields of Optional<? extends JxObject> type");
final Id id = Id.named(getRealType(field));
if (registry.isPending(id))
return Reference.defer(registry, JsdUtil.getName(property.name(), field), property.nullable(), property.use(), () -> registry.reference(registry.getModel(id), referrer));
final ObjectModel model = (ObjectModel)registry.getModel(id);
return new Reference(registry, JsdUtil.getName(property.name(), field), property.nullable(), property.use(), model == null ? registry.declare(id).value(new ObjectModel(registry, field, property), referrer) : registry.reference(model, referrer));
}
static Member referenceOrDeclare(final Registry registry, final Element referrer, final ObjectElement element) {
final Id id = Id.named(element.type());
if (registry.isPending(id))
return Reference.defer(registry, element.nullable(), element.minOccurs(), element.maxOccurs(), () -> registry.reference(registry.getModel(id), referrer instanceof Referrer ? (Referrer<?>)referrer : null));
final ObjectModel model = (ObjectModel)registry.getModel(id);
return new Reference(registry, element.nullable(), element.minOccurs(), element.maxOccurs(), model == null ? registry.declare(id).value(new ObjectModel(registry, element), referrer instanceof Referrer ? (Referrer<?>)referrer : null) : registry.reference(model, referrer instanceof Referrer ? (Referrer<?>)referrer : null));
}
static Member referenceOrDeclare(final Registry registry, final Class<?> cls) {
checkJSObject(cls);
final Id id = Id.named(cls);
if (registry.isPending(id))
return new Deferred<>(null, () -> registry.reference(registry.getModel(id), null));
final ObjectModel model = (ObjectModel)registry.getModel(id);
return model != null ? registry.reference(model, null) : registry.declare(id).value(new ObjectModel(registry, cls, null, null), null);
}
static String getFullyQualifiedName(final xL0gluGCXYYJc.$Object binding) {
final StringBuilder builder = new StringBuilder();
xL0gluGCXYYJc.$Object owner = binding;
do
builder.insert(0, '$').insert(1, JsdUtil.toIdentifier(Strings.flipFirstCap(owner.getName$().text())));
while (owner.owner() instanceof xL0gluGCXYYJc.$Object && (owner = (xL0gluGCXYYJc.$Object)owner.owner()) != null);
return builder.insert(0, JsdUtil.toIdentifier(JsdUtil.flipName(((xL0gluGCXYYJc.Schema.Object)owner.owner()).getName$().text()))).toString();
}
private static Member getReference(final Registry registry, final Referrer<?> referrer, final Field field) {
Member reference = null;
for (final Annotation annotation : field.getAnnotations()) {
Member next = null;
if (AnyProperty.class.equals(annotation.annotationType()))
next = AnyModel.referenceOrDeclare(registry, referrer, (AnyProperty)annotation, field);
else if (ArrayProperty.class.equals(annotation.annotationType()))
next = ArrayModel.referenceOrDeclare(registry, referrer, (ArrayProperty)annotation, field);
else if (BooleanProperty.class.equals(annotation.annotationType()))
next = BooleanModel.referenceOrDeclare(registry, referrer, (BooleanProperty)annotation, field);
else if (NumberProperty.class.equals(annotation.annotationType()))
next = NumberModel.referenceOrDeclare(registry, referrer, (NumberProperty)annotation, field);
else if (ObjectProperty.class.equals(annotation.annotationType()))
next = ObjectModel.referenceOrDeclare(registry, referrer, (ObjectProperty)annotation, field);
else if (StringProperty.class.equals(annotation.annotationType()))
next = StringModel.referenceOrDeclare(registry, referrer, (StringProperty)annotation, field);
if (reference == null)
reference = next;
else if (next != null)
throw new ValidationException(field.getDeclaringClass().getName() + "." + field.getName() + " specifies multiple parameter annotations: [" + reference.elementName() + ", " + next.elementName() + "]");
}
return reference;
}
private static void checkJSObject(final Class<?> cls) {
if (!JxObject.class.isAssignableFrom(cls))
throw new IllegalArgumentException("Class " + cls.getName() + " does not implement " + JxObject.class.getName());
}
private static void recurseInnerClasses(final Registry registry, final Class<?> cls) {
for (final Class<?> innerClass : cls.getClasses()) {
if (!JxObject.class.isAssignableFrom(innerClass))
recurseInnerClasses(registry, innerClass);
else
referenceOrDeclare(registry, innerClass);
}
}
private Map<String,Member> parseMembers(final xL0gluGCXYYJc.$ObjectMember binding, final ObjectModel objectModel) {
final LinkedHashMap<String,Member> members = new LinkedHashMap<>();
final Iterator<? super xL0gluGCXYYJc.$Member> iterator = Iterators.filter(binding.elementIterator(), m -> m instanceof xL0gluGCXYYJc.$Member);
while (iterator.hasNext()) {
final xL0gluGCXYYJc.$Member member = (xL0gluGCXYYJc.$Member)iterator.next();
if (member instanceof xL0gluGCXYYJc.$Any) {
final xL0gluGCXYYJc.$Any any = (xL0gluGCXYYJc.$Any)member;
members.put(any.getNames$().text(), AnyModel.reference(registry, objectModel, any));
}
else if (member instanceof xL0gluGCXYYJc.$Array) {
final xL0gluGCXYYJc.$Array array = (xL0gluGCXYYJc.$Array)member;
final ArrayModel child = ArrayModel.reference(registry, objectModel, array);
members.put(array.getName$().text(), child);
}
else if (member instanceof xL0gluGCXYYJc.$Boolean) {
final xL0gluGCXYYJc.$Boolean bool = (xL0gluGCXYYJc.$Boolean)member;
members.put(bool.getName$().text(), BooleanModel.reference(registry, objectModel, bool));
}
else if (member instanceof xL0gluGCXYYJc.$Number) {
final xL0gluGCXYYJc.$Number number = (xL0gluGCXYYJc.$Number)member;
members.put(number.getName$().text(), NumberModel.reference(registry, objectModel, number));
}
else if (member instanceof xL0gluGCXYYJc.$Object) {
final xL0gluGCXYYJc.$Object object = (xL0gluGCXYYJc.$Object)member;
final ObjectModel child = declare(registry, objectModel, object);
members.put(object.getName$().text(), child);
}
else if (member instanceof xL0gluGCXYYJc.$Reference) {
final xL0gluGCXYYJc.$Reference reference = (xL0gluGCXYYJc.$Reference)member;
final Id id = Id.named(reference.getType$());
final Member model = registry.getModel(id);
if (model == null)
throw new IllegalStateException("Reference \"" + reference.getName$().text() + "\" -> type=\"" + reference.getType$().text() + "\" not found");
members.put(reference.getName$().text(), model instanceof Reference ? model : Reference.defer(registry, reference, () -> registry.reference((Model)model, objectModel)));
}
else if (member instanceof xL0gluGCXYYJc.$String) {
final xL0gluGCXYYJc.$String string = (xL0gluGCXYYJc.$String)member;
members.put(string.getName$().text(), StringModel.reference(registry, objectModel, string));
}
else {
throw new UnsupportedOperationException("Unsupported " + member.getClass().getSimpleName() + " member type: " + member.getClass().getName());
}
}
return members;
}
private static Class<?> getRealType(final Field field) {
return Optional.class.isAssignableFrom(field.getType()) ? Classes.getGenericClasses(field)[0] : field.getType();
}
final Map<String,Member> members;
private Member superObject;
final boolean isAbstract;
private ObjectModel(final Registry registry, final xL0gluGCXYYJc.Schema.Object binding) {
super(registry, registry.getType(registry.packageName, registry.classPrefix + JsdUtil.flipName(binding.getName$().text()), binding.getExtends$() != null ? registry.classPrefix + JsdUtil.flipName(binding.getExtends$().text()) : null));
this.isAbstract = binding.getAbstract$().text();
this.superObject = getReference(binding.getExtends$());
this.members = parseMembers(binding, this);
}
private ObjectModel(final Registry registry, final Field field, final ObjectProperty property) {
this(registry, getRealType(field), property.nullable(), property.use());
}
private ObjectModel(final Registry registry, final ObjectElement element) {
this(registry, element.type(), element.nullable(), null);
}
private ObjectModel(final Registry registry, final xL0gluGCXYYJc.$Object binding) {
super(registry, binding.getName$(), binding.getNullable$(), binding.getUse$(), registry.getType(registry.packageName, registry.classPrefix + getFullyQualifiedName(binding), binding.getExtends$() != null ? registry.classPrefix + JsdUtil.flipName(binding.getExtends$().text()) : null));
this.superObject = getReference(binding.getExtends$());
this.isAbstract = false;
this.members = parseMembers(binding, this);
}
private ObjectModel(final Registry registry, final Class<?> cls, final Boolean nullable, final Use use) {
super(registry, nullable, use, registry.getType(cls));
final Class<?> superClass = cls.getSuperclass();
this.isAbstract = Modifier.isAbstract(cls.getModifiers());
this.superObject = superClass == null || !JxObject.class.isAssignableFrom(superClass) ? null : referenceOrDeclare(registry, superClass);
final LinkedHashMap<String,Member> members = new LinkedHashMap<>();
for (final Field field : cls.getDeclaredFields()) {
final Member reference = getReference(registry, this, field);
if (reference != null)
members.put(reference.name, reference);
}
this.members = members;
recurseInnerClasses(registry, cls);
}
@Override
Registry.Type type() {
return classType();
}
@Override
String elementName() {
return "object";
}
@Override
String sortKey() {
return "z" + type().getName();
}
@Override
Class<? extends Annotation> propertyAnnotation() {
return ObjectProperty.class;
}
@Override
Class<? extends Annotation> elementAnnotation() {
return ObjectElement.class;
}
private boolean referencesResolved = false;
@Override
void resolveReferences() {
if (referencesResolved)
return;
if (superObject instanceof Deferred)
superObject = ((Deferred<Model>)superObject).resolve();
for (final Map.Entry<String,Member> member : members.entrySet())
if (member.getValue() instanceof Deferred)
member.setValue(((Deferred<?>)member.getValue()).resolve());
referencesResolved = true;
}
@Override
void getDeclaredTypes(final Set<Registry.Type> types) {
types.add(type());
if (superObject != null)
superObject.getDeclaredTypes(types);
if (members != null)
for (final Member member : members.values())
member.getDeclaredTypes(types);
}
@Override
Map<String,Object> toAttributes(final Element owner, final String prefix, final String packageName) {
final Map<String,Object> attributes = super.toAttributes(owner, prefix, packageName);
attributes.put(owner instanceof ArrayModel ? "type" : "name", name != null ? name : JsdUtil.flipName(owner instanceof ObjectModel ? classType().getSubName(((ObjectModel)owner).type().getName()) : classType().getSubName(packageName)));
if (superObject != null)
attributes.put(prefix + "extends", JsdUtil.flipName(superObject.type().getRelativeName(packageName)));
if (isAbstract)
attributes.put(prefix + "abstract", isAbstract);
return attributes;
}
@Override
XmlElement toXml(final Settings settings, final Element owner, final String prefix, final String packageName) {
final XmlElement element = super.toXml(settings, owner, prefix, packageName);
if (members == null || members.size() == 0)
return element;
final List<XmlElement> elements = new ArrayList<>();
for (final Member member : members.values())
elements.add(member.toXml(settings, this, prefix, packageName));
element.setElements(elements);
return element;
}
@Override
Map<String,Object> toJson(final Settings settings, final Element owner, final String packageName) {
final Map<String,Object> element = super.toJson(settings, owner, packageName);
if (members == null || members.size() == 0)
return element;
final Map<String,Object> properties = new LinkedHashMap<>();
for (final Member member : members.values())
properties.put(member.name, member.toJson(settings, this, packageName));
element.put("jsd:properties", properties);
return element;
}
@Override
void toAnnotationAttributes(final AttributeMap attributes, final Member owner) {
super.toAnnotationAttributes(attributes, owner);
if (owner instanceof ArrayModel)
attributes.put("type", classType().getCanonicalName() + ".class");
}
@Override
List<AnnotationSpec> getClassAnnotation() {
return null;
}
@Override
String toSource(final Settings settings) {
final StringBuilder builder = new StringBuilder();
if (members != null && members.size() > 0) {
final Iterator<Member> iterator = members.values().iterator();
for (int i = 0; iterator.hasNext(); ++i) {
if (i > 0)
builder.append("\n\n");
builder.append(iterator.next().toField());
}
}
final Registry.Type type = classType();
if (members.size() > 0)
builder.append("\n\n");
builder.append('@').append(Override.class.getName());
builder.append("\npublic boolean equals(final ").append(Object.class.getName()).append(" obj) {");
builder.append("\n if (obj == this)");
builder.append("\n return true;");
builder.append("\n\n if (!(obj instanceof ").append(type.getCanonicalName()).append(')').append((type.getSuperType() != null ? " || !super.equals(obj)" : "")).append(')');
builder.append("\n return false;\n");
if (members != null && members.size() > 0) {
builder.append("\n final ").append(type.getCanonicalName()).append(" that = (").append(type.getCanonicalName()).append(")obj;");
for (final Member member : members.values()) {
final String instanceName = JsdUtil.toInstanceName(member.name);
builder.append("\n if (that.").append(instanceName).append(" != null ? !that.").append(instanceName).append(".equals(").append(instanceName).append(") : ").append(instanceName).append(" != null)");
builder.append("\n return false;\n");
}
}
builder.append("\n return true;");
builder.append("\n}");
builder.append("\n\n@").append(Override.class.getName());
builder.append("\npublic int hashCode() {");
if (members != null && members.size() > 0) {
builder.append("\n int hashCode = ").append(type.getName().hashCode()).append((type.getSuperType() != null ? " * 31 + super.hashCode()" : "")).append(';');
for (final Member member : members.values()) {
final String instanceName = JsdUtil.toInstanceName(member.name);
builder.append("\n hashCode = 31 * hashCode + (").append(instanceName).append(" == null ? 0 : ").append(instanceName).append(".hashCode());");
}
builder.append("\n return hashCode;");
}
else {
builder.append("\n return ").append(type.getName().hashCode()).append((type.getSuperType() != null ? " * 31 + super.hashCode()" : "")).append(';');
}
builder.append("\n}");
builder.append("\n\n@").append(Override.class.getName());
builder.append("\npublic ").append(String.class.getName()).append(" toString() {");
builder.append("\n return ").append(JxEncoder.class.getName()).append(".get().marshal(this);");
builder.append("\n}");
return builder.toString();
}
} | [
"seva@safris.org"
] | seva@safris.org |
fe393246939d200241033bac2540930c332351ed | 0d7994cd38e076e05fda289a267f1ade353a7418 | /DizajnerskiObrasci/src/drawing/mvc/Frame.java | 8e45a6744a18a241210f723f300a84eeebfe23cd | [] | no_license | danielmocko/Dizajnerski-Obrasci | de348f6cf9232ca3b65cee836298236c3b09b5b1 | 76bba2238b06e6dae5176f5fc38ec5fe90f86663 | refs/heads/master | 2020-03-23T21:39:45.311960 | 2018-09-04T11:54:09 | 2018-09-04T11:54:09 | 142,123,378 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 25,381 | java | package drawing.mvc;
import javax.swing.JFrame;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.LayoutStyle.ComponentPlacement;
import com.sun.jmx.mbeanserver.SunJmxMBeanServer;
import drawing.observer.Observer;
import javax.swing.JToggleButton;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import javax.swing.JScrollPane;
import javax.swing.JList;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.imageio.ImageIO;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.JLabel;
public class Frame extends JFrame implements Observer{
private View view = new View();
private Controller controller ;
private JButton btnOpen;
private JButton btnSave;
private JButton btnLoad;
private JButton btnUndo;
private JButton btnRedo;
private JToggleButton tglbtnSelect;
private JButton btnToBack;
private JButton btnToFront;
private JButton btnBringToBack;
private JButton btnBringToFront;
private JToggleButton tglbtnPoint;
private JToggleButton tglbtnLine;
private JToggleButton tglbtnSquare;
private JToggleButton tglbtnRectangle;
private JToggleButton tglbtnCircle;
private JToggleButton tglbtnHexagon;
private JButton btnEdgeColor;
private JButton btnInsideColor;
private JPanel panelNort;
private JPanel panelView;
private final ButtonGroup buttonGroup = new ButtonGroup();
private JButton btnDelete;
private JButton btnModify;
private String color = "#f0f0f0";
private DefaultListModel<String> dlmList = new DefaultListModel<String>();
private int numberSelectedObjects=0;
private JScrollPane scrollPane;
private JList<String> logList;
private JLabel lblAreaColor;
private JPanel panel;
public Frame() {
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{1034, 0};
gridBagLayout.rowHeights = new int[]{55, 448, 0, 0};
gridBagLayout.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, 1.0, 0.0, Double.MIN_VALUE};
getContentPane().setLayout(gridBagLayout);
JPanel panelNorth = new JPanel();
GridBagConstraints gbc_panelNorth = new GridBagConstraints();
gbc_panelNorth.fill = GridBagConstraints.HORIZONTAL;
gbc_panelNorth.insets = new Insets(0, 0, 5, 0);
gbc_panelNorth.anchor = GridBagConstraints.NORTH;
gbc_panelNorth.gridx = 0;
gbc_panelNorth.gridy = 0;
getContentPane().add(panelNorth, gbc_panelNorth);
Icon open = new ImageIcon("res/Icons/open.png");
Icon save = new ImageIcon("res/Icons/save.png");
Icon load = new ImageIcon("res/Icons/load.png");
Icon undo = new ImageIcon("res/Icons/undo.png");
Icon redo = new ImageIcon("res/Icons/redo.png");
Icon select = new ImageIcon("res/Icons/select.png");
Icon toBack= new ImageIcon("res/Icons/goToBack.png");
Icon toFront = new ImageIcon("res/Icons/goToFront.png");
Icon bringToBack = new ImageIcon("res/Icons/bringToBack.png");
Icon bringToFront = new ImageIcon("res/Icons/bringToFront.png");
Icon modify = new ImageIcon("res/Icons/modify.png");
Icon delete = new ImageIcon("res/Icons/delete.png");
Icon point = new ImageIcon("res/Icons/point.png");
Icon line = new ImageIcon("res/Icons/line.png");
Icon square = new ImageIcon("res/Icons/square.png");
Icon rectangle = new ImageIcon("res/Icons/rectangle.png");
Icon circle = new ImageIcon("res/Icons/circle.png");
Icon hexagon = new ImageIcon("res/Icons/Hexagon.png");
panelView = new JPanel();
view.setBackground(Color.WHITE);//panelView
view.addMouseListener(new MouseAdapter() {//panelView
public void mousePressed(MouseEvent e) {
controller.panelClick(e);
}
});
GridBagConstraints gbc_panelView = new GridBagConstraints();
gbc_panelView.insets = new Insets(0, 0, 5, 0);
gbc_panelView.fill = GridBagConstraints.BOTH;
gbc_panelView.gridx = 0;
gbc_panelView.gridy = 1;
getContentPane().add(view, gbc_panelView);//panelView
scrollPane = new JScrollPane();
logList = new JList<String>(dlmList);
logList.disable();
//panelNort = new JPanel();
//panelNort.setBackground(Color.WHITE);
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 2;
getContentPane().add(scrollPane, gbc_scrollPane);
scrollPane.setViewportView(logList);
GridBagLayout gbl_panelNorth = new GridBagLayout();
gbl_panelNorth.columnWidths = new int[]{0, 31, 31, 31, 33, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 19, 26, 25, 57, 62, 0};
gbl_panelNorth.rowHeights = new int[]{20, 24, 0, 0};
gbl_panelNorth.columnWeights = new double[]{0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, Double.MIN_VALUE};
gbl_panelNorth.rowWeights = new double[]{1.0, 0.0, 1.0, Double.MIN_VALUE};
panelNorth.setLayout(gbl_panelNorth);
btnUndo = new JButton(undo);
btnUndo.setBorder(null);
btnUndo.setEnabled(false);
btnUndo.setBackground(Color.decode(color));
btnUndo.setBorderPainted(false);
btnUndo.setToolTipText("Undo");
btnUndo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
controller.undo();
}
});
btnSave = new JButton(save);
btnSave.setBorder(null);
btnSave.setBackground(Color.decode(color));
btnSave.setBorderPainted(false);
btnSave.setToolTipText("Save file");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
controller.saving(e);
}
});
panel = new JPanel();
GridBagConstraints gbc_panel = new GridBagConstraints();
gbc_panel.gridheight = 2;
gbc_panel.insets = new Insets(0, 0, 5, 0);
gbc_panel.fill = GridBagConstraints.BOTH;
gbc_panel.gridx = 19;
gbc_panel.gridy = 0;
panelNorth.add(panel, gbc_panel);
JLabel lblBorderColor = new JLabel("Border color:");
btnInsideColor = new JButton();
btnInsideColor.setBackground(Color.WHITE);
btnInsideColor.setToolTipText("Area color");
btnInsideColor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
controller.insideColor(e);
}
});
lblAreaColor = new JLabel("Area color:");
btnEdgeColor = new JButton();
btnEdgeColor.setBackground(Color.BLACK);
btnEdgeColor.setToolTipText("Broder color");
GroupLayout gl_panel = new GroupLayout(panel);
gl_panel.setHorizontalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addContainerGap()
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addComponent(lblAreaColor, GroupLayout.DEFAULT_SIZE, 66, Short.MAX_VALUE)
.addGap(3))
.addComponent(lblBorderColor, GroupLayout.DEFAULT_SIZE, 66, Short.MAX_VALUE))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
.addComponent(btnInsideColor, GroupLayout.DEFAULT_SIZE, 72, Short.MAX_VALUE)
.addComponent(btnEdgeColor, GroupLayout.DEFAULT_SIZE, 70, Short.MAX_VALUE))
.addContainerGap())
);
gl_panel.setVerticalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addContainerGap()
.addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
.addComponent(lblBorderColor, GroupLayout.DEFAULT_SIZE, 22, Short.MAX_VALUE)
.addComponent(btnEdgeColor, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING)
.addComponent(btnInsideColor, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblAreaColor, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
panel.setLayout(gl_panel);
btnEdgeColor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
controller.edgeColor(e);
}
});
btnOpen = new JButton(open);
btnOpen.setBorder(null);
btnOpen.setBackground(Color.decode(color));
btnOpen.setBorderPainted(false);
btnOpen.setToolTipText("Open file");
btnOpen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
controller.openFiles();
} catch (FileNotFoundException | ClassNotFoundException e1) {
e1.printStackTrace();
}
}
});
GridBagConstraints gbc_btnOpen = new GridBagConstraints();
gbc_btnOpen.gridheight = 2;
gbc_btnOpen.fill = GridBagConstraints.BOTH;
gbc_btnOpen.insets = new Insets(0, 0, 5, 5);
gbc_btnOpen.gridx = 1;
gbc_btnOpen.gridy = 0;
panelNorth.add(btnOpen, gbc_btnOpen);
GridBagConstraints gbc_btnSave = new GridBagConstraints();
gbc_btnSave.gridheight = 2;
gbc_btnSave.fill = GridBagConstraints.BOTH;
gbc_btnSave.insets = new Insets(0, 0, 5, 5);
gbc_btnSave.gridx = 2;
gbc_btnSave.gridy = 0;
panelNorth.add(btnSave, gbc_btnSave);
btnLoad = new JButton(load);
btnLoad.setBorder(null);
btnLoad.setBackground(Color.decode(color));
btnLoad.setBorderPainted(false);
btnLoad.setEnabled(false);
btnLoad.setToolTipText("Load log file");
btnLoad.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
controller.loadData();
}
});
GridBagConstraints gbc_btnLoad = new GridBagConstraints();
gbc_btnLoad.gridheight = 2;
gbc_btnLoad.fill = GridBagConstraints.BOTH;
gbc_btnLoad.insets = new Insets(0, 0, 5, 5);
gbc_btnLoad.gridx = 3;
gbc_btnLoad.gridy = 0;
panelNorth.add(btnLoad, gbc_btnLoad);
GridBagConstraints gbc_btnUndo = new GridBagConstraints();
gbc_btnUndo.gridheight = 2;
gbc_btnUndo.fill = GridBagConstraints.BOTH;
gbc_btnUndo.insets = new Insets(0, 0, 5, 5);
gbc_btnUndo.gridx = 4;
gbc_btnUndo.gridy = 0;
panelNorth.add(btnUndo, gbc_btnUndo);
btnBringToBack = new JButton(bringToBack);
btnBringToBack.setBorder(null);
btnBringToBack.setBackground(Color.decode(color));
btnBringToBack.setBorderPainted(false);
btnBringToBack.setToolTipText("Bring to back");
btnBringToBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
controller.bringToBack(e);
}
});
btnToBack = new JButton(toBack);
btnToBack.setBorder(null);
btnToBack.setBackground(Color.decode(color));
btnToBack.setBorderPainted(false);
btnToBack.setToolTipText("Go to back");
btnToBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
controller.toBack(e);
}
});
btnModify = new JButton(modify);
btnModify.setBorder(null);
btnModify.setBackground(Color.decode(color));
btnModify.setBorderPainted(false);
btnModify.setToolTipText("Modify");
btnModify.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
controller.modify(e);
}
});
btnRedo = new JButton(redo);
btnRedo.setBorder(null);
btnRedo.setEnabled(false);
btnRedo.setBackground(Color.decode(color));
btnRedo.setBorderPainted(false);
btnRedo.setToolTipText("Redo");
btnRedo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
controller.redo();
}
});
GridBagConstraints gbc_btnRedo = new GridBagConstraints();
gbc_btnRedo.gridheight = 2;
gbc_btnRedo.fill = GridBagConstraints.BOTH;
gbc_btnRedo.insets = new Insets(0, 0, 5, 5);
gbc_btnRedo.gridx = 5;
gbc_btnRedo.gridy = 0;
panelNorth.add(btnRedo, gbc_btnRedo);
tglbtnSelect = new JToggleButton(select);
tglbtnSelect.setBorder(null);
tglbtnSelect.setBackground(Color.decode(color));
tglbtnSelect.setBorderPainted(false);
buttonGroup.add(getTglbtnSelect());
tglbtnSelect.setToolTipText("Select");
GridBagConstraints gbc_tglbtnSelect = new GridBagConstraints();
gbc_tglbtnSelect.gridheight = 2;
gbc_tglbtnSelect.fill = GridBagConstraints.BOTH;
gbc_tglbtnSelect.insets = new Insets(0, 0, 5, 5);
gbc_tglbtnSelect.gridx = 6;
gbc_tglbtnSelect.gridy = 0;
panelNorth.add(tglbtnSelect, gbc_tglbtnSelect);
GridBagConstraints gbc_btnModify = new GridBagConstraints();
gbc_btnModify.gridheight = 2;
gbc_btnModify.fill = GridBagConstraints.BOTH;
gbc_btnModify.insets = new Insets(0, 0, 5, 5);
gbc_btnModify.gridx = 7;
gbc_btnModify.gridy = 0;
panelNorth.add(btnModify, gbc_btnModify);
btnDelete = new JButton(delete);
btnDelete.setBorder(null);
btnDelete.setBackground(Color.decode(color));
btnDelete.setBorderPainted(false);
btnDelete.setToolTipText("Delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
controller.delete(e);
}
});
GridBagConstraints gbc_btnDelete = new GridBagConstraints();
gbc_btnDelete.gridheight = 2;
gbc_btnDelete.fill = GridBagConstraints.BOTH;
gbc_btnDelete.insets = new Insets(0, 0, 5, 5);
gbc_btnDelete.gridx = 8;
gbc_btnDelete.gridy = 0;
panelNorth.add(btnDelete, gbc_btnDelete);
GridBagConstraints gbc_btnToBack = new GridBagConstraints();
gbc_btnToBack.gridheight = 2;
gbc_btnToBack.fill = GridBagConstraints.BOTH;
gbc_btnToBack.insets = new Insets(0, 0, 5, 5);
gbc_btnToBack.gridx = 9;
gbc_btnToBack.gridy = 0;
panelNorth.add(btnToBack, gbc_btnToBack);
btnToFront = new JButton(toFront);
btnToFront.setBorder(null);
btnToFront.setBackground(Color.decode(color));
btnToFront.setBorderPainted(false);
btnToFront.setToolTipText("Go to front");
btnToFront.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
controller.toFront();
}
});
GridBagConstraints gbc_btnToFront = new GridBagConstraints();
gbc_btnToFront.gridheight = 2;
gbc_btnToFront.fill = GridBagConstraints.BOTH;
gbc_btnToFront.insets = new Insets(0, 0, 5, 5);
gbc_btnToFront.gridx = 10;
gbc_btnToFront.gridy = 0;
panelNorth.add(btnToFront, gbc_btnToFront);
GridBagConstraints gbc_btnBringToBack = new GridBagConstraints();
gbc_btnBringToBack.gridheight = 2;
gbc_btnBringToBack.fill = GridBagConstraints.BOTH;
gbc_btnBringToBack.insets = new Insets(0, 0, 5, 5);
gbc_btnBringToBack.gridx = 11;
gbc_btnBringToBack.gridy = 0;
panelNorth.add(btnBringToBack, gbc_btnBringToBack);
btnBringToFront = new JButton(bringToFront);
btnBringToFront.setBorder(null);
btnBringToFront.setBackground(Color.decode(color));
btnBringToFront.setBorderPainted(false);
btnBringToFront.setToolTipText("Bring to front");
btnBringToFront.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
controller.bringToFront(e);
}
});
GridBagConstraints gbc_btnBringToFront = new GridBagConstraints();
gbc_btnBringToFront.gridheight = 2;
gbc_btnBringToFront.fill = GridBagConstraints.BOTH;
gbc_btnBringToFront.insets = new Insets(0, 0, 5, 5);
gbc_btnBringToFront.gridx = 12;
gbc_btnBringToFront.gridy = 0;
panelNorth.add(btnBringToFront, gbc_btnBringToFront);
tglbtnPoint = new JToggleButton(point);
tglbtnPoint.setBorder(null);
buttonGroup.add(tglbtnPoint);
tglbtnPoint.setBackground(Color.decode(color));
tglbtnPoint.setBorderPainted(false);
buttonGroup.add(getTglbtnPoint());
tglbtnPoint.setToolTipText("Point");
GridBagConstraints gbc_tglbtnPoint = new GridBagConstraints();
gbc_tglbtnPoint.gridheight = 2;
gbc_tglbtnPoint.fill = GridBagConstraints.BOTH;
gbc_tglbtnPoint.insets = new Insets(0, 0, 5, 5);
gbc_tglbtnPoint.gridx = 13;
gbc_tglbtnPoint.gridy = 0;
panelNorth.add(tglbtnPoint, gbc_tglbtnPoint);
tglbtnLine = new JToggleButton(line);
tglbtnLine.setBorder(null);
buttonGroup.add(tglbtnLine);
tglbtnLine.setBackground(Color.decode(color));
tglbtnLine.setBorderPainted(false);
tglbtnLine.setToolTipText("Line");
buttonGroup.add(getTglbtnLine());
GridBagConstraints gbc_tglbtnLine = new GridBagConstraints();
gbc_tglbtnLine.gridheight = 2;
gbc_tglbtnLine.fill = GridBagConstraints.BOTH;
gbc_tglbtnLine.insets = new Insets(0, 0, 5, 5);
gbc_tglbtnLine.gridx = 14;
gbc_tglbtnLine.gridy = 0;
panelNorth.add(tglbtnLine, gbc_tglbtnLine);
tglbtnSquare = new JToggleButton(square);
tglbtnSquare.setBorder(null);
buttonGroup.add(tglbtnSquare);
tglbtnSquare.setBackground(Color.decode(color));
tglbtnSquare.setBorderPainted(false);
tglbtnSquare.setToolTipText("Square");
buttonGroup.add(getTglbtnSquare());
GridBagConstraints gbc_tglbtnSquare = new GridBagConstraints();
gbc_tglbtnSquare.gridheight = 2;
gbc_tglbtnSquare.fill = GridBagConstraints.BOTH;
gbc_tglbtnSquare.insets = new Insets(0, 0, 5, 5);
gbc_tglbtnSquare.gridx = 15;
gbc_tglbtnSquare.gridy = 0;
panelNorth.add(tglbtnSquare, gbc_tglbtnSquare);
tglbtnRectangle = new JToggleButton(rectangle);
tglbtnRectangle.setBorder(null);
buttonGroup.add(tglbtnRectangle);
tglbtnRectangle.setBackground(Color.decode(color));
tglbtnRectangle.setBorderPainted(false);
tglbtnRectangle.setToolTipText("Rectangle");
buttonGroup.add(getTglbtnRectangle());
GridBagConstraints gbc_tglbtnRectangle = new GridBagConstraints();
gbc_tglbtnRectangle.gridheight = 2;
gbc_tglbtnRectangle.fill = GridBagConstraints.BOTH;
gbc_tglbtnRectangle.insets = new Insets(0, 0, 5, 5);
gbc_tglbtnRectangle.gridx = 16;
gbc_tglbtnRectangle.gridy = 0;
panelNorth.add(tglbtnRectangle, gbc_tglbtnRectangle);
tglbtnCircle = new JToggleButton(circle);
tglbtnCircle.setBorder(null);
buttonGroup.add(tglbtnCircle);
tglbtnCircle.setBackground(Color.decode(color));
tglbtnCircle.setBorderPainted(false);
tglbtnCircle.setToolTipText("Circle");
buttonGroup.add(getTglbtnCircle());
GridBagConstraints gbc_tglbtnCircle = new GridBagConstraints();
gbc_tglbtnCircle.gridheight = 2;
gbc_tglbtnCircle.fill = GridBagConstraints.BOTH;
gbc_tglbtnCircle.insets = new Insets(0, 0, 5, 5);
gbc_tglbtnCircle.gridx = 17;
gbc_tglbtnCircle.gridy = 0;
panelNorth.add(tglbtnCircle, gbc_tglbtnCircle);
tglbtnHexagon = new JToggleButton(hexagon);
tglbtnHexagon.setBorder(null);
buttonGroup.add(tglbtnHexagon);
tglbtnHexagon.setBackground(Color.decode(color));
tglbtnHexagon.setBorderPainted(false);
tglbtnHexagon.setToolTipText("Hexagon");
buttonGroup.add(getTglbtnHexagon());
GridBagConstraints gbc_tglbtnHexagon = new GridBagConstraints();
gbc_tglbtnHexagon.fill = GridBagConstraints.BOTH;
gbc_tglbtnHexagon.insets = new Insets(0, 0, 0, 5);
gbc_tglbtnHexagon.gridheight = 2;
gbc_tglbtnHexagon.gridx = 18;
gbc_tglbtnHexagon.gridy = 0;
panelNorth.add(tglbtnHexagon, gbc_tglbtnHexagon);
updateView(0, 0, 0);
}
public void updateView(int numberSelectedObjects, int flag,int size) {
this.numberSelectedObjects=numberSelectedObjects;
if(size==0) {
this.btnSave.setEnabled(false);
}
else if(size>0) {
this.btnSave.setEnabled(true);
}
if(this.numberSelectedObjects==0) {
this.btnModify.setEnabled(false);
this.btnDelete.setEnabled(false);
this.btnBringToBack.setEnabled(false);
this.btnBringToFront.setEnabled(false);
this.btnToFront.setEnabled(false);
this.btnToBack.setEnabled(false);
}
else if(this.numberSelectedObjects==1 ) {
this.btnModify.setEnabled(true);
this.btnDelete.setEnabled(true);
if(size==1 ) {
this.btnBringToBack.setEnabled(false);
this.btnToBack.setEnabled(false);
this.btnBringToFront.setEnabled(false);
this.btnToFront.setEnabled(false);
}
else if(size>1 && flag==2) {
this.btnBringToBack.setEnabled(true);
this.btnToBack.setEnabled(true);
this.btnBringToFront.setEnabled(false);
this.btnToFront.setEnabled(false);
}
else if(size>1 && flag==1) {
this.btnBringToBack.setEnabled(false);
this.btnToBack.setEnabled(false);
this.btnBringToFront.setEnabled(true);
this.btnToFront.setEnabled(true);
}
else {
this.btnBringToBack.setEnabled(true);
this.btnToBack.setEnabled(true);
this.btnBringToFront.setEnabled(true);
this.btnToFront.setEnabled(true);
}
}
else {
this.btnModify.setEnabled(false);
this.btnDelete.setEnabled(true);
this.btnBringToBack.setEnabled(false);
this.btnBringToFront.setEnabled(false);
this.btnToFront.setEnabled(false);
this.btnToBack.setEnabled(false);
}
}
public void updateLog(String logList) {
getDlmList().add(0, logList);
}
public View getView() {
return view;
}
public void setView(View view) {
this.view = view;
}
public Controller getController() {
return controller;
}
public void setController(Controller controller) {
this.controller = controller;
}
public JButton getBtnSave() {
return btnOpen;
}
public void setBtnSave(JButton btnSave) {
this.btnOpen = btnSave;
}
public JButton getBtnOpen() {
return btnSave;
}
public void setBtnOpen(JButton btnOpen) {
this.btnSave = btnOpen;
}
public JButton getBtnLoad() {
return btnLoad;
}
public void setBtnLoad(JButton btnLoad) {
this.btnLoad = btnLoad;
}
public JButton getBtnUndo() {
return btnUndo;
}
public void setBtnUndo(JButton btnUndo) {
this.btnUndo = btnUndo;
}
public JButton getBtnRedo() {
return btnRedo;
}
public void setBtnRedo(JButton btnRedo) {
this.btnRedo = btnRedo;
}
public JToggleButton getTglbtnSelect() {
return tglbtnSelect;
}
public void setTglbtnSelect(JToggleButton tglbtnSelect) {
this.tglbtnSelect = tglbtnSelect;
}
public JButton getBtnGoToBack() {
return btnToBack;
}
public void setBtnGoToBack(JButton btnGoToBack) {
this.btnToBack = btnGoToBack;
}
public JButton getBtnGoToFront() {
return btnToFront;
}
public void setBtnGoToFront(JButton btnGoToFront) {
this.btnToFront = btnGoToFront;
}
public JButton getBtnBringToBack() {
return btnBringToBack;
}
public void setBtnBringToBack(JButton btnBringToBack) {
this.btnBringToBack = btnBringToBack;
}
public JButton getBtnBringToFront() {
return btnBringToFront;
}
public void setBtnBringToFront(JButton btnBringToFront) {
this.btnBringToFront = btnBringToFront;
}
public JToggleButton getTglbtnPoint() {
return tglbtnPoint;
}
public void setTglbtnPoint(JToggleButton tglbtnPoint) {
this.tglbtnPoint = tglbtnPoint;
}
public JToggleButton getTglbtnLine() {
return tglbtnLine;
}
public void setTglbtnLine(JToggleButton tglbtnLine) {
this.tglbtnLine = tglbtnLine;
}
public JToggleButton getTglbtnSquare() {
return tglbtnSquare;
}
public void setTglbtnSquare(JToggleButton tglbtnSquare) {
this.tglbtnSquare = tglbtnSquare;
}
public JToggleButton getTglbtnRectangle() {
return tglbtnRectangle;
}
public void setTglbtnRectangle(JToggleButton tglbtnRectangle) {
this.tglbtnRectangle = tglbtnRectangle;
}
public JToggleButton getTglbtnCircle() {
return tglbtnCircle;
}
public void setTglbtnCircle(JToggleButton tglbtnCircle) {
this.tglbtnCircle = tglbtnCircle;
}
public JToggleButton getTglbtnHexagon() {
return tglbtnHexagon;
}
public void setTglbtnHexagon(JToggleButton tglbtnHexagon) {
this.tglbtnHexagon = tglbtnHexagon;
}
public JButton getBtnEdgeColor() {
return btnEdgeColor;
}
public void setBtnEdgeColor(JButton btnEdgeColor) {
this.btnEdgeColor = btnEdgeColor;
}
public JButton getBtnInsideColor() {
return btnInsideColor;
}
public void setBtnInsideColor(JButton btnInsideColor) {
this.btnInsideColor = btnInsideColor;
}
public JPanel getPanelView() {
return panelView;
}
public void setPanelView(JPanel panelView) {
this.panelView = panelView;
}
public JButton getBtnDelete() {
return btnDelete;
}
public void setBtnDelete(JButton btnDelete) {
this.btnDelete = btnDelete;
}
public JButton getBtnModify() {
return btnModify;
}
public void setBtnModify(JButton btnModify) {
this.btnModify = btnModify;
}
public DefaultListModel<String> getDlmList() {
return dlmList;
}
public void setDlmList(DefaultListModel<String> dlmList) {
this.dlmList = dlmList;
}
public JList<String> getLogList() {
return logList;
}
public void setLogList(JList<String> logList) {
this.logList = logList;
}
}
| [
"danielmocko50@gmail.com"
] | danielmocko50@gmail.com |
08ec2a0e9d3ef39ea98727ebbaaab37af065494f | 1f19aec2ecfd756934898cf0ad2758ee18d9eca2 | /u-1/u-11/u-11-111/u-11-111-1112/u-11-111-1112-11113-111111/u-11-111-1112-11113-111111-f5528.java | b58ef4d653322e23311458aa83533bf146e02498 | [] | no_license | apertureatf/perftest | f6c6e69efad59265197f43af5072aa7af8393a34 | 584257a0c1ada22e5486052c11395858a87b20d5 | refs/heads/master | 2020-06-07T17:52:51.172890 | 2019-06-21T18:53:01 | 2019-06-21T18:53:01 | 193,039,805 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 106 | java | mastercard 5555555555554444 4012888888881881 4222222222222 378282246310005 6011111111111117
2368311293972 | [
"jenkins@khan.paloaltonetworks.local"
] | jenkins@khan.paloaltonetworks.local |
54b605ce321fbfa385d24289c93bd0dd11ce9184 | 8e7e4144a30aa3ef60e0bc156ac264607b90ffd5 | /nanshanguanli/src/org/itst/service/UserService.java | 5d65ebcd8f9f02004b216ea4c3405c1f9f1b9f73 | [] | no_license | ZTFrom1994/nanshanmanage | 487df4d9341095c8149c89bb39cfeb7ecef0740d | 33a171e4616b373d5960566cbe14cd0da7192786 | refs/heads/master | 2021-01-20T00:21:40.899849 | 2017-04-23T05:13:19 | 2017-04-23T05:13:19 | 89,118,982 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,312 | java | package org.itst.service;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.itst.domain.User;
public interface UserService {
/**
* 在这里注解后,方法的实现不用我们自己写,mybatis会自动帮我们实现,只需在conf.xml中配置后,直接调用就行
* @param u
* @return
*/
// @Insert("insert into users(username, password) values(#{username}, #{password})")
// public int addUser(User u);
// @Delete("delete from users where id=#{id}")
// public int deleteUserById(int id);
// @Update("update users set username=#{username},password=#{password} where id=#{id}")
// public int updateUser(User u);
// @Select("select * from users where id=#{id}")
// public User getUserById(int id);
// @Select("select * from users")
// public List<User> getAllUsers();
public void addUser(User u);
public void deleteUserById(String id);
public int updateUser(User u);
public User getUserById(String id);
public User getUserByName(String username);
public List<User> getAllUsers();
public String getUsersJsonByPage(int pageSize,int pageNow);
public String getUsersJsonByKeyWord(String key,int pageSize,int pageNow);
}
| [
"605288028@qq.com"
] | 605288028@qq.com |
49b6264b4e2f01f7e0d54dfa0483e900fa2d723a | e6868aaf103dd862e599f05a87502ce1ad66eae0 | /新建文件夹/.svn/pristine/4f/4f115f02529e994132e7d1de3ddcd760679f1d72.svn-base | 1d0fea8bb4e025dcdfaa6e0afcdde5238952caf0 | [] | no_license | griftt/about-shop | f5b76162a0e61f3777061feea6242c7306af73b9 | 01615afae85c73eca1cb1a4ef322f60a5183787e | refs/heads/master | 2020-03-24T00:22:27.590985 | 2018-07-27T10:43:32 | 2018-07-27T10:43:32 | 142,288,052 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 896 | package com.hc.shop.mapper;
import com.hc.shop.pojo.TbOrderItem;
import com.hc.shop.pojo.TbOrderItemExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface TbOrderItemMapper {
long countByExample(TbOrderItemExample example);
int deleteByExample(TbOrderItemExample example);
int deleteByPrimaryKey(String id);
int insert(TbOrderItem record);
int insertSelective(TbOrderItem record);
List<TbOrderItem> selectByExample(TbOrderItemExample example);
TbOrderItem selectByPrimaryKey(String id);
int updateByExampleSelective(@Param("record") TbOrderItem record, @Param("example") TbOrderItemExample example);
int updateByExample(@Param("record") TbOrderItem record, @Param("example") TbOrderItemExample example);
int updateByPrimaryKeySelective(TbOrderItem record);
int updateByPrimaryKey(TbOrderItem record);
} | [
"1361255790.@qq.com"
] | 1361255790.@qq.com | |
89cb4dbc23ce724911b8432f6cf3c48adb2a4353 | 50c0f060674aaea51c154d12ea585f5c1b2e129d | /Microservices5112019/.metadata/.plugins/org.eclipse.core.resources/.history/7f/80f81ecd1102001a1b259d41d1ebbbe9 | fecfc794e728a41bf070e814ea5abf7975b493aa | [] | no_license | badhekomal17/MyProject | 3645695c968e4ef4aa27fa710ed9b7c3a9498eca | 9abb12040699be6ddb8d7f3a6eb4273c37a86c49 | refs/heads/master | 2020-09-06T15:08:11.500244 | 2019-11-08T12:30:02 | 2019-11-08T12:30:02 | 220,461,210 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 700 | package com.zensar.goodByeservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class GoodByeServiceApplication {
public static void main(String[] args) {
SpringApplication.run(GoodByeServiceApplication.class, args);
}
@GetMapping
public String sayGoodBye() {
//return "<h1> Welcome to Microservices </h1>";
return "<h1> Good Bye !!</h1>";
}
}
| [
"ahirrao.rohini.29@gmail.com"
] | ahirrao.rohini.29@gmail.com | |
51f126ca60c08a22b0be926fa0e09081ef928012 | b0296d820c0400440232152485a0b3dff3e943be | /GTAS/GridTalk/src/Client/com/gridnode/gtas/client/web/download/EditGridDocumentAction.java | ada3122d9398f2f859bcd4b42edd751f9821dae9 | [] | no_license | andytanoko/4.2.x_integration | 74536c8933a98373b0118eeac66678b72b00aa8e | 984842d92abaa797a19bd0f002ec45c9c37da288 | refs/heads/master | 2021-01-10T13:46:58.824451 | 2015-09-23T10:41:25 | 2015-09-23T10:41:25 | 46,325,977 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 7,818 | java | /**
* This software is the proprietary information of GridNode Pte Ltd.
* Use is subjected to license terms.
*
* Copyright 2001-2002 (C) GridNode Pte Ltd. All Rights Reserved.
*
* File: EditGridDocumentAction.java
*
****************************************************************************
* Date Author Changes
****************************************************************************
* 2003-07-23 Daniel D'Cotta Created (GridForm 2.0 intergration)
* Nov 24 2005 Neo Sok Lay Specify use of Xerces parser implementation to parse doc
* Feb 12 2007 Neo Sok Lay Remove attempt to connect to GAIA.
*/
package com.gridnode.gtas.client.web.download;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.gridnode.gtas.client.GTClientException;
import com.gridnode.gtas.client.utils.StaticUtils;
import com.gridnode.gtas.client.web.IRequestKeys;
import com.gridnode.gtas.client.web.StaticWebUtils;
import com.gridnode.gtas.client.web.strutsbase.ActionContext;
import com.gridnode.gtas.client.web.strutsbase.GTActionBase;
import com.gridnode.pdip.framework.file.access.FileAccess;
public class EditGridDocumentAction extends GTActionBase
{
protected static final Log _log = LogFactory.getLog(EditGridDocumentAction.class); // 20031209 DDJ
protected static final String DOWNLOAD_MAPPING = "download";
protected static final String SAVE_GRID_DOCUMENT_MAPPING = "saveGridDocument";
public ActionForward execute( ActionMapping mapping,
ActionForm actionForm,
HttpServletRequest request,
HttpServletResponse response)
throws Exception
{
try
{
ActionContext actionContext = new ActionContext(mapping,actionForm,request,response);
actionContext.setLog(_log);
EditGridDocumentAForm form = (EditGridDocumentAForm)actionForm;
validateFormState(form);
/*NSL20070212
String domain = form.getDomain();
String filePath = form.getFilePath();
String gridDocId = form.getGridDocId();
File file = getFile(domain, filePath);
String root = getRoot(file); */
ActionForward actionForward = null;
/*
try
{
// check if managed to obtain GAIA project name
if(StaticUtils.stringEmpty(root))
{
throw new GTClientException("Unable to retrieve GridForm project of document"); // 20040108 DDJ
}
// check if GAIA can handle the document
GAIAClient gaiaClient = new GAIAClient();
boolean isProjectAvailable = gaiaClient.isProjectAvailable(root);
if(!isProjectAvailable)
{
throw new UnsupportedOperationException("GridForm does not support root: " + root);
}
// upload the file to GAIA
String filename = StaticUtils.extractFilename(filePath);
String desc = filename + " (GTAS GridDocument Id: " + gridDocId + ")";
int gaiaDocId = gaiaClient.uploadDocument(file, desc);
// construct the return URL
// note: currently GAIA appends "http://" to the url
String saveGridDocumentUrl = request.getServerName() + ":" +
request.getServerPort() +
response.encodeURL(request.getContextPath() + mapping.findForward(SAVE_GRID_DOCUMENT_MAPPING).getPath());
saveGridDocumentUrl = StaticWebUtils.addParameterToURL(saveGridDocumentUrl, IRequestKeys.GRID_DOC_ID, gridDocId);
saveGridDocumentUrl = StaticWebUtils.addParameterToURL(saveGridDocumentUrl, IRequestKeys.GAIA_DOC_ID, gaiaDocId + "");
if(_log.isDebugEnabled())
{
_log.debug("saveGridDocumentUrl=" + saveGridDocumentUrl);
}
// redirect to the URL given by GAIA
String gaiaDocUrl = gaiaClient.getUrl(gaiaDocId, saveGridDocumentUrl);
actionForward = new ActionForward(gaiaDocUrl, true);
}
catch(Throwable t)
{
if(_log.isErrorEnabled())
{
_log.error("Caught error trying to view using GridForm, using default viewer", t);
}*/
actionForward = mapping.findForward(DOWNLOAD_MAPPING);
/*}*/
return actionForward;
}
catch(Throwable t)
{
throw new GTClientException("Error executing EditGridDocumentAction",t);
}
}
protected void validateFormState(EditGridDocumentAForm form)
throws IllegalStateException
{
if(StaticUtils.stringEmpty(form.getDomain()))
throw new IllegalStateException("domain is undefined");
if(StaticUtils.stringEmpty(form.getFilePath()))
throw new IllegalStateException("filePath is undefined");
if(StaticUtils.stringEmpty(form.getGridDocId()))
throw new IllegalStateException("gridDocId is undefined");
if(StaticUtils.primitiveLongValue(form.getGridDocId()) <= 0)
throw new IllegalStateException("gridDocId is not a valid value");
}
// return the file specified
protected File getFile(String domain, String filePath)
{
FileAccess fileAccess = new FileAccess(domain);
File file = fileAccess.getFile(filePath);
if(file == null)
{
throw new NullPointerException("FileAccess.getFile(" + filePath + ") returned null");
}
return file;
}
// return the root element
protected String getRoot(File file)
{
String root = null;
try
{
Document document = null;
//DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//NSL20051124
DocumentBuilderFactory dbf = new org.apache.xerces.jaxp.DocumentBuilderFactoryImpl();
/*
DocumentBuilderFactory dbf;
ClassLoader oldLoader = null;
String oldFactory = System.getProperty("javax.xml.parsers.DocumentBuilderFactory");
try
{
System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
oldLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
dbf = DocumentBuilderFactory.newInstance();
}
finally
{
if (oldLoader != null)
Thread.currentThread().setContextClassLoader(oldLoader);
System.setProperty("javax.xml.parsers.DocumentBuilderFactory", oldFactory);
}*/
DocumentBuilder db = dbf.newDocumentBuilder();
db.setEntityResolver(new DummyResolver());
document = db.parse(file);
Node rootNode = document.getDocumentElement();
root = rootNode.getNodeName();
}
catch(Exception ex)
{
if(_log.isErrorEnabled())
{
_log.error("Error extracting root element", ex);
}
}
return root;
}
protected class DummyResolver implements EntityResolver
{
public DummyResolver()
{
}
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException, IOException
{
if(_log.isDebugEnabled())
{
_log.debug("Returning 'null' for resolveEntity(" + publicId + ", " + systemId + ")");
}
return new InputSource(new StringReader(""));
}
}
}
| [
"muhamadnazir@gmail.com"
] | muhamadnazir@gmail.com |
20a503cd86ba1e4394badf0be6e76029f1cf336b | 38d145558f4d11bcfbbfd4e403327d5f9be4a810 | /app/src/main/java/com/makan/app/web/pojo/FilterSearchRequest.java | 7fa1cc610dc619e1a79a6da703606c32329fc3bc | [] | no_license | greeniit/MakanProject | 17108cd62c94ff85d4214783ef6b27d6a508daef | e98460c3c478a8fc74c1a921ae1e207ad19c75ad | refs/heads/master | 2020-12-30T04:47:09.913345 | 2020-02-07T07:20:51 | 2020-02-07T07:20:51 | 238,864,088 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,715 | java | package com.makan.app.web.pojo;
import android.os.Parcel;
import android.os.Parcelable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class FilterSearchRequest implements Parcelable {
@SerializedName("user_id")
@Expose
private int userId;
@SerializedName("selectedType")
@Expose
private Integer selectedType;
@SerializedName("sub_category_id")
@Expose
private List<Integer> subCategoryId = null;
@SerializedName("location")
@Expose
private String location;
@SerializedName("property_name")
@Expose
private String propertyName;
@SerializedName("lat")
@Expose
private String lat;
@SerializedName("long")
@Expose
private String _long;
@SerializedName("minarea")
@Expose
private Integer minarea;
@SerializedName("maxarea")
@Expose
private Integer maxarea;
@SerializedName("minprice")
@Expose
private Integer minprice;
@SerializedName("maxprice")
@Expose
private Integer maxprice;
public Integer getSelectedType() {
return selectedType;
}
public void setSelectedType(Integer selectedType) {
this.selectedType = selectedType;
}
public List<Integer> getSubCategoryId() {
return subCategoryId;
}
public void setSubCategoryId(List<Integer> subCategoryId) {
this.subCategoryId = subCategoryId;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getPropertyName() {
return propertyName;
}
public void setPropertyName(String propertyName) {
this.propertyName = propertyName;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLong() {
return _long;
}
public void setLong(String _long) {
this._long = _long;
}
public Integer getMinarea() {
return minarea;
}
public void setMinarea(Integer minarea) {
this.minarea = minarea;
}
public Integer getMaxarea() {
return maxarea;
}
public void setMaxarea(Integer maxarea) {
this.maxarea = maxarea;
}
public Integer getMinprice() {
return minprice;
}
public void setMinprice(Integer minprice) {
this.minprice = minprice;
}
public Integer getMaxprice() {
return maxprice;
}
public void setMaxprice(Integer maxprice) {
this.maxprice = maxprice;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(this.userId);
dest.writeValue(this.selectedType);
dest.writeList(this.subCategoryId);
dest.writeString(this.location);
dest.writeString(this.propertyName);
dest.writeString(this.lat);
dest.writeString(this._long);
dest.writeValue(this.minarea);
dest.writeValue(this.maxarea);
dest.writeValue(this.minprice);
dest.writeValue(this.maxprice);
}
public FilterSearchRequest() {
}
protected FilterSearchRequest(Parcel in) {
this.userId = (Integer) in.readValue(Integer.class.getClassLoader());
this.selectedType = (Integer) in.readValue(Integer.class.getClassLoader());
this.subCategoryId = new ArrayList<Integer>();
in.readList(this.subCategoryId, Integer.class.getClassLoader());
this.location = in.readString();
this.propertyName = in.readString();
this.lat = in.readString();
this._long = in.readString();
this.minarea = (Integer) in.readValue(Integer.class.getClassLoader());
this.maxarea = (Integer) in.readValue(Integer.class.getClassLoader());
this.minprice = (Integer) in.readValue(Integer.class.getClassLoader());
this.maxprice = (Integer) in.readValue(Integer.class.getClassLoader());
}
public static final Parcelable.Creator<FilterSearchRequest> CREATOR = new Parcelable.Creator<FilterSearchRequest>() {
@Override
public FilterSearchRequest createFromParcel(Parcel source) {
return new FilterSearchRequest(source);
}
@Override
public FilterSearchRequest[] newArray(int size) {
return new FilterSearchRequest[size];
}
};
}
| [
"roym5252@gmail.com"
] | roym5252@gmail.com |
b876ebb9f64c77636eded7330668e8cfe8f895d9 | 65abae2f0221d0ee542f51d935f6f429ac519bb8 | /src/main/java/com.abc/dao/entity/Dept.java | 08b15254c83e09808a548bba5d8bc5a85e3fae84 | [] | no_license | langugu-art/spring | ef71eb6533c29d3062d0c901138243ec37ff0cda | bd7c732086f94887f0859131f99434cf1f5274fe | refs/heads/master | 2023-01-30T23:19:15.715823 | 2020-12-16T15:11:59 | 2020-12-16T15:11:59 | 322,011,763 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 953 | java | package com.abc.dao.entity;
public class Dept {
//部门编号,名称,地址
private int deptno;
private String dname;
private String loc;
@Override
public String toString() {
return "Dept{" +
"deptno=" + deptno +
", dname='" + dname + '\'' +
", loc='" + loc + '\'' +
'}';
}
public Dept(int deptno, String dname, String loc) {
this.deptno = deptno;
this.dname = dname;
this.loc = loc;
}
public Dept( ) {
}
public int getDeptno() {
return deptno;
}
public String getDname() {
return dname;
}
public String getLoc() {
return loc;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
public void setDname(String dname) {
this.dname = dname;
}
public void setLoc(String loc) {
this.loc = loc;
}
}
| [
"gcbslyx@126.com"
] | gcbslyx@126.com |
3ad2b762a67400edfb5e7ec701141cb1bc01186e | 8d9061310311c9dd84d0e091ea6400d404b8ad12 | /pmd-jerry/test/test/net/sourceforge/pmd/jerry/ast/xpath/TokenMgrErrorTest.java | 8dac5cfd283529c791a6c34fd1b9123e7b380adb | [] | no_license | mishin/pmd | dc06c35f11715acfef7ae6695072e625585a9e10 | 44e7bb6354a5d673c575d379a1a9d9ad6ba4e9af | refs/heads/master | 2020-12-14T00:22:08.875811 | 2013-05-17T14:21:37 | 2013-05-17T14:21:37 | 55,873,341 | 1 | 0 | null | 2016-04-10T00:23:50 | 2016-04-10T00:23:50 | null | UTF-8 | Java | false | false | 1,128 | java | /**
*
*/
package test.net.sourceforge.pmd.jerry.ast.xpath;
import static org.junit.Assert.assertEquals;
import net.sourceforge.pmd.jerry.ast.xpath.TokenMgrError;
import org.junit.Before;
import org.junit.Test;
/**
* @author rpelisse
*
*/
public class TokenMgrErrorTest {
private static final String MESSAGE = "Message";
private static final int REASON = 0;
private TokenMgrError tokenMgr;
@Before
public void buildTestTarget() {
tokenMgr = new TokenMgrError(MESSAGE, REASON);
}
@Test
public void getMessage() {
assertEquals(MESSAGE,tokenMgr.getMessage());
}
@Test
public void addEscapes() {
TokenMgrErrorDummy dummy = new TokenMgrErrorDummy();
assertEquals(dummy.escapes("\b"),"\\b");
assertEquals(dummy.escapes("\t"),"\\t");
assertEquals(dummy.escapes("\n"),"\\n");
assertEquals(dummy.escapes("\f"),"\\f");
assertEquals(dummy.escapes("\r"),"\\r");
assertEquals(dummy.escapes("\\"),"\\\\");
}
private class TokenMgrErrorDummy extends TokenMgrError {
private static final long serialVersionUID = 1L;
public String escapes(String str) {
return super.addEscapes(str);
}
}
}
| [
"rpelisse@users.sourceforge.net"
] | rpelisse@users.sourceforge.net |
eee2acebdf34403aabc03fe8a42cb9c91b3cb51d | d9776413fd11ae416548f533d33edaebc684f6a8 | /server/src/main/java/com/course/server/dto/PageDto.java | 27fb1fe3f259be00ccb19f8424cf76198cbe9333 | [] | no_license | mangmangxiyu/course | 13094beb68229c3be0be21b6914a455cff6a75fa | 76f7195fbd1d07a8c72e449ae51a586331d1eff9 | refs/heads/master | 2023-03-26T06:54:24.328931 | 2021-03-28T06:13:30 | 2021-03-28T06:19:31 | 347,658,694 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,686 | java | /**
* Copyright (C), 2015-2021, XXX有限公司
* FileName: PageDto
* Author: 111
* Date: 2021/3/9 23:14
* Description: 接收前端分页请求数据的Dto,再传递给后端
* History:
* <author> <time> <version> <desc>
* 作者姓名 修改时间 版本号 描述
*/
package com.course.server.dto;
import java.util.List;
/**
* 〈一句话功能简述〉<br>
* 〈接收前端分页请求数据的Dto,再传递给后端〉
*
* @author 111
* @create 2021/3/9
* @since 1.0.0
*/
public class PageDto<T> {
/*
前端传递过来的当前页码,页面大小
*/
protected int page;
protected int size;
/*
后端处理请求查询数据库后的结果
*/
protected long total;
protected List<T> list;
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("PageDto{");
sb.append("page=").append(page);
sb.append(", size=").append(size);
sb.append(", total=").append(total);
sb.append(", list=").append(list);
sb.append('}');
return sb.toString();
}
}
| [
"goodMoring_glb@qq.com"
] | goodMoring_glb@qq.com |
11c5543a4b428ed1ae644c88940fa29c6390aa9d | ce056c2531a2ea73e3f6a820c225a3e9c1cd082b | /ssm-xml-second/src/main/java/com/dao/UsersDao.java | 7e5326d558fabdf6e24b7f60a56c86d6174b58d2 | [] | no_license | Rivenerdawqrq/spring-parent | b6d26670825f7ea36c0e0ddd549f98b3d313c114 | 9b65c22c1fdb2fe8274a66484127321f02f39f83 | refs/heads/master | 2022-12-22T20:29:55.980397 | 2019-11-27T12:08:46 | 2019-11-27T12:08:46 | 224,417,384 | 0 | 0 | null | 2022-12-16T14:51:13 | 2019-11-27T11:41:18 | Java | UTF-8 | Java | false | false | 273 | java | package com.dao;
import com.entity.UserInfos;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UsersDao {
List<UserInfos> getAll(@Param("pageNum")int pageNum,@Param("pageSize")int pageSize);
void insert(UserInfos userInfos);
}
| [
"1595606639@qq.com"
] | 1595606639@qq.com |
e8171e8aae3c3b39eb2350f369b0d651f08aa543 | 3419c5dd022c1c76d1029614135f1d92993ca6d3 | /src/main/java/com/rpc/test/Main.java | d45ad5005d0e477543c0d5fa313ab553159d75d4 | [] | no_license | ys-d/simpleRpcServer | 5f926c7956294c4d3375ffb4380341d481452fc9 | 9f20e95f56864009a299bbd3869d01d2039d00b0 | refs/heads/master | 2020-03-21T10:41:42.003369 | 2016-08-14T15:12:32 | 2016-08-14T15:12:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 993 | java | package com.rpc.test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// int hash ="aasa1aa".hashCode();
// System.out.println(hash%16);
// int segmentShift =28 ;
// int segmentMask = 15;
// System.out.println((hash >>> segmentShift));
// System.out.println((hash >>> segmentShift) & segmentMask);
ExecutorService service =new ThreadPoolExecutor(2, 2,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(4));
for (int k =0 ; k<100;k++){
service.submit(new Runnable() {
@Override
public void run() {
try {
System.out.println("启动");
Thread.sleep(100L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
service.shutdown();
}
}
| [
"shocklee@vip.qq.com"
] | shocklee@vip.qq.com |
dec8ff3a10597b34427bc97a21681aae2ebefd71 | 84103269d0322ad778085bab554a64c266abb09c | /Interview Preparation Kit/Graphs/DFS Connected Cell in a Grid/Solution.java | 50bd9ba5fe1440178a817c784b99868e0ebe9544 | [
"MIT"
] | permissive | PawarAditi/HackerRank | 40e55eb02f5e3c4b1aba6aca63f3a99076bda006 | fcd9d1450ee293372ce5f1d4a3b7284ecf472657 | refs/heads/master | 2023-01-08T12:50:53.540537 | 2020-10-17T13:33:19 | 2020-10-17T13:33:19 | 300,532,220 | 0 | 0 | MIT | 2020-10-17T13:33:20 | 2020-10-02T07:12:51 | null | UTF-8 | Java | false | false | 1,439 | java | import java.io.*;
import java.util.*;
public class Solution {
public static int largestRegion(int[][] grid) {
int max = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
max = Math.max(max, countCells(grid, i, j));
}
}
return max;
}
private static int countCells(int[][] grid, int i, int j) {
if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length)
return 0;
if (grid[i][j] == 0)
return 0;
int count = grid[i][j]--; //it works as a flag to stop the recursion
count += countCells(grid, i + 1, j);
count += countCells(grid, i - 1, j);
count += countCells(grid, i, j + 1);
count += countCells(grid, i, j - 1);
count += countCells(grid, i + 1, j + 1);
count += countCells(grid, i - 1, j - 1);
count += countCells(grid, i - 1, j + 1);
count += countCells(grid, i + 1, j - 1);
return count;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int grid[][] = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
grid[i][j] = in.nextInt();
}
}
System.out.println(largestRegion(grid));
}
}
| [
"sofiakinsht@gmail.com"
] | sofiakinsht@gmail.com |
0f887279d89838e684bac5f36f58e565d89247d1 | 2f0b8c3bf0856e8535bd58b164b3b543f4337d31 | /CourseSchedule.java | ca28d1044cf6e11c3bd01c4fc60813f55bff7fb1 | [] | no_license | habina/lintcode_run | 5322587a0426b6105ff1fed767aeb33e95477ff2 | 61a712d811a5eeb75ecf0f508614b7b49cf4293b | refs/heads/master | 2021-03-30T16:57:51.878395 | 2018-01-11T22:02:43 | 2018-01-11T22:02:43 | 64,609,831 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,891 | java | import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
public class CourseSchedule {
public static boolean canFinish(int numCourses, int[][] prerequisites) {
Map<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
Map<Integer, Integer> inbound = new HashMap<Integer, Integer>();
for (int[] edge : prerequisites) {
if (map.containsKey(edge[0])) {
map.get(edge[0]).add(edge[1]);
} else {
List<Integer> t = new ArrayList<Integer>();
t.add(edge[1]);
map.put(edge[0], t);
}
if (inbound.containsKey(edge[1])) {
inbound.put(edge[1], inbound.get(edge[1]) + 1);
} else {
inbound.put(edge[1], 1);
}
}
Set<Integer> visited = new HashSet<Integer>();
Queue<Integer> q = new LinkedList<Integer>();
for (int i = 0; i < numCourses; i++) {
if (!inbound.containsKey(i)) {
q.offer(i);
visited.add(i);
}
}
while (!q.isEmpty()) {
int cur = q.poll();
if (map.containsKey(cur)) {
for (Integer neighbor : map.get(cur)) {
inbound.put(neighbor, inbound.get(neighbor) - 1);
if (inbound.get(neighbor) == 0) {
visited.add(neighbor);
q.offer(neighbor);
}
}
}
}
return visited.size() == numCourses;
}
public static void main(String[] args) {
int a = 2;
int[][] b = { { 1, 0 } };
System.out.println(canFinish(a, b));
}
}
| [
"habinacds@gmail.com"
] | habinacds@gmail.com |
c72b9dfe9cda36e76009d33f42760ae4a59222a1 | 8fa4ce9795a7a0500283407aef31fe9d8d519989 | /webt-simple/web-template-simple/src/main/java/com/teamsun/web_template_simple/App.java | 71cbb1411e54a518bec55291a09231af881179ff | [] | no_license | simplty/web-template | babc43b084e75d6f0e0e90d00ce4c0461e80a42c | 95f4e2e29a31697db5432b92df72b0b73771e4b1 | refs/heads/master | 2021-01-10T23:56:45.354737 | 2016-10-13T07:39:02 | 2016-10-13T07:39:02 | 70,780,439 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 194 | java | package com.teamsun.web_template_simple;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
| [
"simplty@gmail.com"
] | simplty@gmail.com |
d2e0211dc975e6ca91aa94adb8ecc22eb8a742d3 | 29872f4a68f697cbea58f68162285f33e219fd07 | /src/main/java/com/imooc/test/TestString.java | 13e619c9ddf802ade0141ae81d1d891728b1f321 | [] | no_license | jll410206801/person-girl | 49f4a9efb6b6618f7ee247c6551d6f38a61554a4 | dcc3f5c31cac52b68254ba77ff1949c6e50592a2 | refs/heads/master | 2021-09-05T10:38:01.893445 | 2018-01-26T13:41:43 | 2018-01-26T13:41:43 | 112,473,782 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 183 | java | package com.imooc.test;
public class TestString {
public static void main(String[] args) {
String s = "q";
StringBuilder sb = new StringBuilder();
}
}
| [
"498394266@qq.com"
] | 498394266@qq.com |
ef9f5527d6312d0713283db8bb1504b20061ac16 | 85e8dd9329d18b80147d87ad11fbc50105e732cf | /src/main/java/com/google/devtools/build/lib/dynamic/LegacyDynamicSpawnStrategy.java | f22c120f13956f87cdd1d5f9a6583f790b35fa18 | [
"Apache-2.0"
] | permissive | bobhu2010/bazel | 3ae15df0bfd1ba700ade263a7cb52f86eaa3ad22 | 2c8639f15d898e1559074185a493300dcd06f8cb | refs/heads/master | 2022-11-07T23:09:29.497252 | 2020-06-30T01:48:51 | 2020-06-30T01:50:24 | 276,035,590 | 1 | 0 | Apache-2.0 | 2020-06-30T08:00:44 | 2020-06-30T08:00:44 | null | UTF-8 | Java | false | false | 20,689 | java | // Copyright 2018 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.dynamic;
import com.google.auto.value.AutoValue;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.flogger.GoogleLogger;
import com.google.common.io.Files;
import com.google.devtools.build.lib.actions.ActionContext;
import com.google.devtools.build.lib.actions.ActionExecutionContext;
import com.google.devtools.build.lib.actions.DynamicStrategyRegistry;
import com.google.devtools.build.lib.actions.EnvironmentalExecException;
import com.google.devtools.build.lib.actions.ExecException;
import com.google.devtools.build.lib.actions.ExecutionRequirements;
import com.google.devtools.build.lib.actions.SandboxedSpawnStrategy;
import com.google.devtools.build.lib.actions.Spawn;
import com.google.devtools.build.lib.actions.SpawnResult;
import com.google.devtools.build.lib.actions.SpawnStrategy;
import com.google.devtools.build.lib.actions.Spawns;
import com.google.devtools.build.lib.actions.UserExecException;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.exec.ExecutionPolicy;
import com.google.devtools.build.lib.server.FailureDetails.DynamicExecution;
import com.google.devtools.build.lib.server.FailureDetails.DynamicExecution.Code;
import com.google.devtools.build.lib.server.FailureDetails.FailureDetail;
import com.google.devtools.build.lib.util.io.FileOutErr;
import com.google.devtools.build.lib.vfs.Path;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Phaser;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import javax.annotation.Nullable;
/**
* A spawn strategy that speeds up incremental builds while not slowing down full builds.
*
* <p>This strategy tries to run spawn actions on the local and remote machine at the same time, and
* picks the spawn action that completes first. This gives the benefits of remote execution on full
* builds, and local execution on incremental builds.
*
* <p>One might ask, why we don't run spawns on the workstation all the time and just "spill over"
* actions to remote execution when there are no local resources available. This would work, except
* that the cost of transferring action inputs and outputs from the local machine to and from remote
* executors over the network is way too high - there is no point in executing an action locally and
* save 0.5s of time, when it then takes us 5 seconds to upload the results to remote executors for
* another action that's scheduled to run there.
*/
public class LegacyDynamicSpawnStrategy implements SpawnStrategy {
private static final GoogleLogger logger = GoogleLogger.forEnclosingClass();
enum StrategyIdentifier {
NONE("unknown"),
LOCAL("locally"),
REMOTE("remotely");
private final String prettyName;
StrategyIdentifier(String prettyName) {
this.prettyName = prettyName;
}
String prettyName() {
return prettyName;
}
}
@AutoValue
abstract static class DynamicExecutionResult {
static DynamicExecutionResult create(
StrategyIdentifier strategyIdentifier,
@Nullable FileOutErr fileOutErr,
@Nullable ExecException execException,
List<SpawnResult> spawnResults) {
return new AutoValue_LegacyDynamicSpawnStrategy_DynamicExecutionResult(
strategyIdentifier, fileOutErr, execException, ImmutableList.copyOf(spawnResults));
}
abstract StrategyIdentifier strategyIdentifier();
@Nullable
abstract FileOutErr fileOutErr();
@Nullable
abstract ExecException execException();
/**
* Returns a list of SpawnResults associated with executing a Spawn.
*
* <p>The list will typically contain one element, but could contain zero elements if spawn
* execution did not complete, or multiple elements if multiple sub-spawns were executed.
*/
abstract ImmutableList<SpawnResult> spawnResults();
}
private static final ImmutableSet<String> DISABLED_MNEMONICS_FOR_WORKERS =
ImmutableSet.of("JavaDeployJar");
private final ExecutorService executorService;
private final DynamicExecutionOptions options;
private final Function<Spawn, ExecutionPolicy> getExecutionPolicy;
private final AtomicBoolean delayLocalExecution = new AtomicBoolean(false);
// TODO(steinman): This field is never assigned and canExec() would throw if trying to access it.
@Nullable private SandboxedSpawnStrategy workerStrategy;
/**
* Constructs a {@code DynamicSpawnStrategy}.
*
* @param executorService an {@link ExecutorService} that will be used to run Spawn actions.
*/
public LegacyDynamicSpawnStrategy(
ExecutorService executorService,
DynamicExecutionOptions options,
Function<Spawn, ExecutionPolicy> getExecutionPolicy) {
this.executorService = executorService;
this.options = options;
this.getExecutionPolicy = getExecutionPolicy;
}
@Override
public ImmutableList<SpawnResult> exec(
final Spawn spawn, final ActionExecutionContext actionExecutionContext)
throws ExecException, InterruptedException {
if (options.requireAvailabilityInfo
&& !options.availabilityInfoExempt.contains(spawn.getMnemonic())) {
if (spawn.getExecutionInfo().containsKey(ExecutionRequirements.REQUIRES_DARWIN)
&& !spawn.getExecutionInfo().containsKey(ExecutionRequirements.REQUIREMENTS_SET)) {
String message =
String.format(
"The following spawn was missing Xcode-related execution requirements. Please"
+ " let the Bazel team know if you encounter this issue. You can work around"
+ " this error by passing --experimental_require_availability_info=false --"
+ " at your own risk! This may cause some actions to be executed on the"
+ " wrong platform, which can result in build failures.\n"
+ "Failing spawn: mnemonic = %s\n"
+ "tool files = %s\n"
+ "execution platform = %s\n"
+ "execution info = %s\n",
spawn.getMnemonic(),
spawn.getToolFiles(),
spawn.getExecutionPlatform(),
spawn.getExecutionInfo());
throw new EnvironmentalExecException(
createFailureDetail(message, Code.XCODE_RELATED_PREREQ_UNMET));
}
}
ExecutionPolicy executionPolicy = getExecutionPolicy.apply(spawn);
// If a Spawn cannot run remotely, we must always execute it locally. Resources will already
// have been acquired by Skyframe for us.
if (executionPolicy.canRunLocallyOnly()) {
return runLocally(spawn, actionExecutionContext, null);
}
// If a Spawn cannot run locally, we must always execute it remotely. For remote execution,
// local resources should not be acquired.
if (executionPolicy.canRunRemotelyOnly()) {
return runRemotely(spawn, actionExecutionContext, null);
}
// At this point we have a Spawn that can run locally and can run remotely. Run it in parallel
// using both the remote and the local strategy.
ExecException exceptionDuringExecution = null;
DynamicExecutionResult dynamicExecutionResult =
DynamicExecutionResult.create(
StrategyIdentifier.NONE, null, null, /*spawnResults=*/ ImmutableList.of());
// As an invariant in Bazel, all actions must terminate before the build ends. We use a
// synchronizer here, in the main thread, to wait for the termination of both local and remote
// spawns. Termination implies successful completion, failure, or, if one spawn wins,
// cancellation by the executor.
//
// In the case where one task completes successfully before the other starts, Bazel must
// proceed and return, skipping the other spawn. To achieve this, we use Phaser for its ability
// to register a variable number of tasks.
//
// TODO(b/118451841): Note that this may incur a performance issue where a remote spawn is
// faster than a worker spawn, because the worker spawn cannot be cancelled once it starts. This
// nullifies the gains from the faster spawn.
Phaser bothTasksFinished = new Phaser(/*parties=*/ 1);
try {
final AtomicReference<SpawnStrategy> outputsHaveBeenWritten = new AtomicReference<>(null);
dynamicExecutionResult =
executorService.invokeAny(
ImmutableList.of(
new DynamicExecutionCallable(
bothTasksFinished,
StrategyIdentifier.LOCAL,
actionExecutionContext.getFileOutErr()) {
@Override
List<SpawnResult> callImpl() throws InterruptedException, ExecException {
// This is a rather simple approach to make it possible to score a cache hit
// on remote execution before even trying to start the action locally. This
// saves resources that would otherwise be wasted by continuously starting and
// immediately killing local processes. One possibility for improvement would
// be to establish a reporting mechanism from strategies back to here, where
// we delay starting locally until the remote strategy tells us that the
// action isn't a cache hit.
if (delayLocalExecution.get()) {
Thread.sleep(options.localExecutionDelay);
}
return runLocally(
spawn,
actionExecutionContext.withFileOutErr(fileOutErr),
outputsHaveBeenWritten);
}
},
new DynamicExecutionCallable(
bothTasksFinished,
StrategyIdentifier.REMOTE,
actionExecutionContext.getFileOutErr()) {
@Override
public List<SpawnResult> callImpl() throws InterruptedException, ExecException {
List<SpawnResult> spawnResults =
runRemotely(
spawn,
actionExecutionContext.withFileOutErr(fileOutErr),
outputsHaveBeenWritten);
delayLocalExecution.set(true);
return spawnResults;
}
}));
} catch (ExecutionException e) {
Throwables.propagateIfPossible(e.getCause(), InterruptedException.class);
// DynamicExecutionCallable.call only declares InterruptedException, so this should never
// happen.
exceptionDuringExecution =
new UserExecException(
e.getCause(),
createFailureDetail(
Strings.nullToEmpty(e.getCause().getMessage()), Code.RUN_FAILURE));
} finally {
bothTasksFinished.arriveAndAwaitAdvance();
if (dynamicExecutionResult.execException() != null) {
exceptionDuringExecution = dynamicExecutionResult.execException();
}
if (Thread.currentThread().isInterrupted()) {
// Warn but don't throw, in case we're crashing.
logger.atWarning().log("Interrupted waiting for dynamic execution tasks to finish");
}
}
// Check for interruption outside of finally block, so we don't mask any other exceptions.
// Clear the interrupt bit if it's set.
if (exceptionDuringExecution == null && Thread.interrupted()) {
throw new InterruptedException("Interrupted waiting for dynamic execution tasks to finish");
}
StrategyIdentifier winningStrategy = dynamicExecutionResult.strategyIdentifier();
FileOutErr fileOutErr = dynamicExecutionResult.fileOutErr();
if (StrategyIdentifier.NONE.equals(winningStrategy) || fileOutErr == null) {
throw new IllegalStateException("Neither local or remote execution has started.");
}
try {
moveFileOutErr(actionExecutionContext, fileOutErr);
} catch (IOException e) {
String strategyName = winningStrategy.name().toLowerCase();
if (exceptionDuringExecution == null) {
throw new UserExecException(
e,
createFailureDetail(
String.format("Could not move action logs from %s execution", strategyName),
Code.ACTION_LOG_MOVE_FAILURE));
} else {
actionExecutionContext
.getEventHandler()
.handle(
Event.warn(
String.format(
"Could not move action logs from %s execution: %s",
strategyName, e.toString())));
}
}
if (exceptionDuringExecution != null) {
throw exceptionDuringExecution;
}
if (options.debugSpawnScheduler) {
actionExecutionContext
.getEventHandler()
.handle(
Event.info(
String.format(
"%s action %s %s",
spawn.getMnemonic(),
dynamicExecutionResult.execException() == null ? "finished" : "failed",
winningStrategy.prettyName())));
}
// TODO(b/62588075) If a second list of spawnResults was generated (before execution was
// cancelled), then we might want to save it as well (e.g. for metrics purposes).
return dynamicExecutionResult.spawnResults();
}
@Override
public boolean canExec(Spawn spawn, ActionContext.ActionContextRegistry actionContextRegistry) {
DynamicStrategyRegistry dynamicStrategyRegistry =
actionContextRegistry.getContext(DynamicStrategyRegistry.class);
for (SandboxedSpawnStrategy strategy :
dynamicStrategyRegistry.getDynamicSpawnActionContexts(
spawn, DynamicStrategyRegistry.DynamicMode.LOCAL)) {
if (strategy.canExec(spawn, actionContextRegistry)) {
return true;
}
}
for (SandboxedSpawnStrategy strategy :
dynamicStrategyRegistry.getDynamicSpawnActionContexts(
spawn, DynamicStrategyRegistry.DynamicMode.REMOTE)) {
if (strategy.canExec(spawn, actionContextRegistry)) {
return true;
}
}
return workerStrategy.canExec(spawn, actionContextRegistry);
}
private void moveFileOutErr(ActionExecutionContext actionExecutionContext, FileOutErr outErr)
throws IOException {
if (outErr.getOutputPath().exists()) {
Files.move(
outErr.getOutputPath().getPathFile(),
actionExecutionContext.getFileOutErr().getOutputPath().getPathFile());
}
if (outErr.getErrorPath().exists()) {
Files.move(
outErr.getErrorPath().getPathFile(),
actionExecutionContext.getFileOutErr().getErrorPath().getPathFile());
}
}
private static FileOutErr getSuffixedFileOutErr(FileOutErr fileOutErr, String suffix) {
Path outDir = Preconditions.checkNotNull(fileOutErr.getOutputPath().getParentDirectory());
String outBaseName = fileOutErr.getOutputPath().getBaseName();
Path errDir = Preconditions.checkNotNull(fileOutErr.getErrorPath().getParentDirectory());
String errBaseName = fileOutErr.getErrorPath().getBaseName();
return new FileOutErr(
outDir.getChild(outBaseName + suffix), errDir.getChild(errBaseName + suffix));
}
private static boolean supportsWorkers(Spawn spawn) {
return (!DISABLED_MNEMONICS_FOR_WORKERS.contains(spawn.getMnemonic())
&& Spawns.supportsWorkers(spawn));
}
private static SandboxedSpawnStrategy.StopConcurrentSpawns lockOutputFiles(
SandboxedSpawnStrategy token, @Nullable AtomicReference<SpawnStrategy> outputWriteBarrier) {
if (outputWriteBarrier == null) {
return null;
} else {
return () -> {
if (outputWriteBarrier.get() != token && !outputWriteBarrier.compareAndSet(null, token)) {
throw new DynamicInterruptedException(
"Execution stopped because other strategy finished first");
}
};
}
}
private static ImmutableList<SpawnResult> runLocally(
Spawn spawn,
ActionExecutionContext actionExecutionContext,
@Nullable AtomicReference<SpawnStrategy> outputWriteBarrier)
throws ExecException, InterruptedException {
DynamicStrategyRegistry dynamicStrategyRegistry =
actionExecutionContext.getContext(DynamicStrategyRegistry.class);
for (SandboxedSpawnStrategy strategy :
dynamicStrategyRegistry.getDynamicSpawnActionContexts(
spawn, DynamicStrategyRegistry.DynamicMode.LOCAL)) {
if (!strategy.toString().contains("worker") || supportsWorkers(spawn)) {
return strategy.exec(
spawn, actionExecutionContext, lockOutputFiles(strategy, outputWriteBarrier));
}
}
throw new RuntimeException(
"executorCreated not yet called or no default dynamic_local_strategy set");
}
private static ImmutableList<SpawnResult> runRemotely(
Spawn spawn,
ActionExecutionContext actionExecutionContext,
@Nullable AtomicReference<SpawnStrategy> outputWriteBarrier)
throws ExecException, InterruptedException {
DynamicStrategyRegistry dynamicStrategyRegistry =
actionExecutionContext.getContext(DynamicStrategyRegistry.class);
for (SandboxedSpawnStrategy strategy :
dynamicStrategyRegistry.getDynamicSpawnActionContexts(
spawn, DynamicStrategyRegistry.DynamicMode.REMOTE)) {
return strategy.exec(
spawn, actionExecutionContext, lockOutputFiles(strategy, outputWriteBarrier));
}
throw new RuntimeException(
"executorCreated not yet called or no default dynamic_remote_strategy set");
}
private static FailureDetail createFailureDetail(String message, Code detailedCode) {
return FailureDetail.newBuilder()
.setMessage(message)
.setDynamicExecution(DynamicExecution.newBuilder().setCode(detailedCode))
.build();
}
private abstract static class DynamicExecutionCallable
implements Callable<DynamicExecutionResult> {
private final Phaser taskFinished;
private final StrategyIdentifier strategyIdentifier;
protected final FileOutErr fileOutErr;
DynamicExecutionCallable(
Phaser taskFinished,
StrategyIdentifier strategyIdentifier,
FileOutErr fileOutErr) {
this.taskFinished = taskFinished;
this.strategyIdentifier = strategyIdentifier;
this.fileOutErr = getSuffixedFileOutErr(fileOutErr, "." + strategyIdentifier.name());
}
abstract List<SpawnResult> callImpl() throws InterruptedException, ExecException;
@Override
public final DynamicExecutionResult call() throws InterruptedException {
taskFinished.register();
try {
List<SpawnResult> spawnResults = callImpl();
return DynamicExecutionResult.create(strategyIdentifier, fileOutErr, null, spawnResults);
} catch (Exception e) {
Throwables.throwIfInstanceOf(e, InterruptedException.class);
return DynamicExecutionResult.create(
strategyIdentifier,
fileOutErr,
e instanceof ExecException
? (ExecException) e
: new UserExecException(
e, createFailureDetail(Strings.nullToEmpty(e.getMessage()), Code.RUN_FAILURE)),
/*spawnResults=*/ ImmutableList.of());
} finally {
try {
fileOutErr.close();
} catch (IOException ignored) {
// Nothing we can do here.
}
taskFinished.arriveAndDeregister();
}
}
}
}
| [
"copybara-worker@google.com"
] | copybara-worker@google.com |
a4b900d0d543e69d4646f07457ce5b85ca838b45 | 589c715e5a64aa9928ae2144b7e616fe9afd997c | /src/main/java/com/dendreon/intellivenge/dataservice/config/JDBCDataServiceModule.java | 71d638f9afde8f88c8bd0b658faad919b0a563ee | [] | no_license | tracyhires/intv-dataservice | 3812712966861e0b223f6a0ddb1c2252ff6f526e | d152c05bd63c2c7a3c7be78d9aa43af260988683 | refs/heads/master | 2016-09-06T17:07:01.822750 | 2015-01-06T22:13:03 | 2015-01-06T22:13:03 | 27,829,309 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 877 | java | package com.dendreon.intellivenge.dataservice.config;
import static com.google.inject.jndi.JndiIntegration.fromJndi;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import com.dendreon.intellivenge.dataservice.DataService;
import com.dendreon.intellivenge.dataservice.OracleDataService;
import com.google.inject.PrivateModule;
import com.google.inject.name.Names;
public class JDBCDataServiceModule extends PrivateModule {
@Override
protected void configure() {
bind(Context.class).to(InitialContext.class);
bind(DataSource.class).annotatedWith(Names.named("XxsapJndi"))
.toProvider(
fromJndi(DataSource.class,
"java:/comp/env/jdbc/xxsap"));
expose(DataSource.class).annotatedWith(Names.named("XxsapJndi"));
bind(DataService.class).to(OracleDataService.class);
expose(DataService.class);
}
}
| [
"crennie@teknovare.com"
] | crennie@teknovare.com |
49629b0b5be47da4703c6d651b321b8113b4da21 | 64ee8136635860ac9d0c7cdd2262b9e9430b58bd | /src/minecraft/poop/command/Command.java | 0d0c969735c87f418a583813466889d8bb4c24b1 | [] | no_license | NovaDevUK/sexclient | e21a6fc977a40047e90f13af8190bbc7373a3fc8 | 7f61b1e64b8569a91f1fb997c3add1f5190abeeb | refs/heads/master | 2023-02-17T19:00:32.091393 | 2021-01-18T03:48:03 | 2021-01-18T03:48:03 | 330,546,612 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 256 | java | package poop.command;
public abstract class Command {
public abstract String getAlias();
public abstract String getDescription();
public abstract String getSyntax();
public abstract void onCommand(String command, String[] args) throws Exception;
}
| [
"75738601+NovaDevUK@users.noreply.github.com"
] | 75738601+NovaDevUK@users.noreply.github.com |
f2c0ee292492090a11adcf013399aec34aa2551b | 3c6fb6dc3224561b9203895591af56fca39eb66b | /SGD/src/com/vista/Usuarios/UsuariosPanel.java | 687f24817db4aa7fda78abb900cfd278bfa56dcd | [] | no_license | DiegoD/Tesis-04-04-2016 | 79f29271ac6c39ab3c9c8f8785e808e3c0447a8c | a68f77bf1eb899aff648f05548715928a538b1a1 | refs/heads/master | 2021-01-25T14:21:52.450940 | 2017-03-05T15:46:11 | 2017-03-05T15:46:11 | 55,455,242 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 818 | java | package com.vista.Usuarios;
import com.vaadin.annotations.AutoGenerated;
import com.vaadin.annotations.DesignRoot;
import com.vaadin.ui.Button;
import com.vaadin.ui.Grid;
import com.vaadin.ui.Label;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.declarative.Design;
/**
* !! DO NOT EDIT THIS FILE !!
*
* This class is generated by Vaadin Designer and will be overwritten.
*
* Please make a subclass with logic and additional interfaces as needed,
* e.g class LoginView extends LoginDesign implements View { }
*/
@DesignRoot
@AutoGenerated
@SuppressWarnings("serial")
public class UsuariosPanel extends VerticalLayout {
protected Label lblTitulo;
protected Grid gridUsuarios;
protected Button btnNuevoUsuario;
public UsuariosPanel() {
Design.read(this);
}
}
| [
"dorner.diego@gmail.com"
] | dorner.diego@gmail.com |
ed23f2be8dfa5d160b13d3903167a785eaf0602c | 218b55cc84be7087f3a901a147313cc2e84b8072 | /src/main/java/hello/HelloController.java | c47c0f670b689fb504d03fb75fac6ef9ae101c4d | [] | no_license | philipbhs/ping | 10ca42951b40fa230391767606d98ab90b9efe9a | bb75163a0a971410790c110bed2be004e410e19c | refs/heads/master | 2020-03-28T12:35:30.082787 | 2018-09-11T11:34:42 | 2018-09-11T11:34:42 | 148,313,619 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 614 | java | package hello;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
@RestController
public class HelloController {
@RequestMapping("/ping")
public String ping() {
return "PONG!";
}
@PostMapping(value = "/ping", consumes = "text/plain")
public String put(@RequestBody final String msg) {
return msg.toUpperCase() + "PONG!";
}
@GetMapping("/web")
public String getExternal() {
return new RestTemplate().getForObject("https://elg.no", String.class).replace("elg.jpg", "https://elg.no/elg.jpg");
}
}
| [
"philipbakken.holt-seeland@drift.oslo.kommune.no"
] | philipbakken.holt-seeland@drift.oslo.kommune.no |
4154da017075e371c8a2c835a29f6e8e8ad000e1 | be02fb345e335fb9eae87422773cbc3348856c2b | /app/src/androidTest/java/com/example/ritesham/firapp/ExampleInstrumentedTest.java | 57d86f876c9fed0cf96c58ab99886ff228782795 | [] | no_license | ritesham/FIR_app | d6573d44c2bc02dbaf00873b557212f5f3d6be78 | 45a693199fd5b8d247467edff4aa8ba73b5f5c66 | refs/heads/master | 2020-03-09T21:17:30.017523 | 2018-04-10T23:12:58 | 2018-04-10T23:12:58 | 129,005,535 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 755 | java | package com.example.ritesham.firapp;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.ritesham.firapp", appContext.getPackageName());
}
}
| [
"ritesham@gmail.com"
] | ritesham@gmail.com |
b45be9a0e20f975530d91994e98993c695f20b32 | cdc9b1e859227de257e2c1920c14b03cc63d987a | /src/Modelo/VO/VO_Usuario.java | 3868fbc44a10be069106e3926f2a6682f10fe0f5 | [] | no_license | TESMAN117/Food_Fit_INC | 84d85bd38e50a2b7c1e847879f5516a809aff47f | 0480b46e9d967a232834b1ba6a5355ae2d490fac | refs/heads/master | 2022-11-26T20:32:36.328992 | 2020-07-31T17:17:04 | 2020-07-31T17:17:04 | 275,712,196 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,781 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Modelo.VO;
/**
*
* @author jesus
*/
public class VO_Usuario {
private int int_ID_Usuario;
private int int_Tipo_Usuario;
private String vch_Usuario;
private String vch_Password;
private int CLV_Cliente_Usuario;
private int CLV_Empleado_User;
private String Tipito;
public int getInt_ID_Usuario() {
return int_ID_Usuario;
}
public void setInt_ID_Usuario(int int_ID_Usuario) {
this.int_ID_Usuario = int_ID_Usuario;
}
public int getInt_Tipo_Usuario() {
return int_Tipo_Usuario;
}
public void setInt_Tipo_Usuario(int int_Tipo_Usuario) {
this.int_Tipo_Usuario = int_Tipo_Usuario;
}
public String getVch_Usuario() {
return vch_Usuario;
}
public void setVch_Usuario(String vch_Usuario) {
this.vch_Usuario = vch_Usuario;
}
public String getVch_Password() {
return vch_Password;
}
public void setVch_Password(String vch_Password) {
this.vch_Password = vch_Password;
}
public int getCLV_Cliente_Usuario() {
return CLV_Cliente_Usuario;
}
public void setCLV_Cliente_Usuario(int CLV_Cliente_Usuario) {
this.CLV_Cliente_Usuario = CLV_Cliente_Usuario;
}
public int getCLV_Empleado_User() {
return CLV_Empleado_User;
}
public void setCLV_Empleado_User(int CLV_Empleado_User) {
this.CLV_Empleado_User = CLV_Empleado_User;
}
public String getTipito() {
return Tipito;
}
public void setTipito(String Tipito) {
this.Tipito = Tipito;
}
}
| [
"67400857+TESMAN117@users.noreply.github.com"
] | 67400857+TESMAN117@users.noreply.github.com |
d195ab911f80dddb9610880ac815646afe5586b9 | 9de7fd8a552f9ec4c9b78e4b6ad7ac50e41fcfba | /src/model/SocketAction.java | 2a389ad0edf35ab1978a279568dd404da0160346 | [] | no_license | LeoDorbes/DisplayPanelClient | 01536c158b5f009f0f6df1f14623f516be89a420 | 11d9155c47544df7e944bc94ae971c1e3f36dff8 | refs/heads/master | 2021-01-12T10:49:42.275209 | 2017-01-05T10:46:24 | 2017-01-05T10:46:24 | 72,723,146 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 1,832 | java | package model;
//Classe trouvée sur le web, elle organise la gestion des sockets et flux input/output en un seul objet: SocketAction :-)!
//All code graciously developed by Greg Turner. You have the right
//to reuse this code however you choose. Thanks Greg!
//Imports
import java.net.*;
import java.io.*;
public class SocketAction extends Thread {
private ObjectInputStream inStream = null;
private ObjectOutputStream outStream = null;
private Socket socket = null;
public SocketAction() {
}
public SocketAction(Socket sock) {
// super("SocketAction");
socket = sock;
try {
// Java is evil...
outStream = new ObjectOutputStream(socket.getOutputStream());
inStream = new ObjectInputStream(socket.getInputStream());
System.out.println("SocketAction::ObjectStreams Created");
} catch (IOException e) {
System.out.println("Couldn't initialize SocketAction: " + e);
System.exit(1);
}
}
public void run() {
}
public void send(Object s) {
// outStream.println(s);
try {
outStream.writeObject(s);
outStream.reset();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Object receive() throws IOException, ClassNotFoundException {
// return inStream.readLine();
return inStream.readObject();
}
public void closeConnections() {
if (socket != null) {
try {
socket.close();
socket = null;
} catch (IOException e) {
System.out.println("Couldn't close socket: " + e);
}
}
}
public boolean isConnected() {
// System.out.println("SocketAction::IsConnected Called");
return !(socket == null);
}
protected void finalize() {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
System.out.println("Couldn't close socket: " + e);
}
socket = null;
}
}
} | [
"leodorbes@gmail.com"
] | leodorbes@gmail.com |
6f710265dbbf7932b9283f02769fa7d5d852e2b2 | 64cc3aa316ca573a4c3701683249e4709ec29047 | /app/src/main/java/com/lixinjia/myapplication/adapter/MainAdapter.java | a7683837a6d8a9aa5ef6131721f956aa6443b665 | [] | no_license | XinJiaGe/MyApplication | 4b292ca3c918f8f44f01f3042ada8592ffe0b5f7 | 5c7a3b568c95f19628c4ef3dcb9d5c92633d75ce | refs/heads/master | 2021-04-26T22:17:00.440500 | 2019-11-14T05:10:20 | 2019-11-14T05:10:20 | 90,335,057 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,242 | java | package com.lixinjia.myapplication.adapter;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.lixinjia.myapplication.R;
import com.lixinjia.myapplication.model.MainEntity;
import java.util.List;
/**
* 作者:李忻佳
* 时间:2017/5/2
* 说明:MainAdapter
*/
public class MainAdapter extends BaseAdapter<MainEntity> {
public MainAdapter(List<MainEntity> listModel, Activity activity) {
super(listModel, activity);
}
@Override
public int getLayoutId(int position, View convertView, ViewGroup parent) {
return R.layout.item_main;
}
@Override
public void bindData(int position, View convertView, ViewGroup parent, final MainEntity model) {
TextView text = convertView.findViewById(R.id.item_main_text);
text.setText(model.getName());
convertView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(mActivity, model.getClz());
mActivity.startActivity(intent);
}
});
}
}
| [
"347292753@qq.com"
] | 347292753@qq.com |
21c77991360d0163cc7919c503691fc03e0d8c38 | 647508b7af8ef6b10573157841e73ccc7ee90b86 | /practice_Chap06(배열)/src/example01/ArrayEx03.java | 4537caca988ffe85b6480115317869d786601480 | [] | no_license | kimlsy2444/JAVA-Study | f2fc8cd47879db1c84cd5ca0bf5572b58bebcc70 | 592d0d603f2ba6f953950189eb1c3151474490fd | refs/heads/main | 2023-07-16T19:17:43.457984 | 2021-09-02T09:14:36 | 2021-09-02T09:14:36 | 402,355,464 | 1 | 0 | null | null | null | null | UHC | Java | false | false | 1,228 | java | package example01;
import java.util.Arrays;
public class ArrayEx03 {
public static void main(String[] args) {
//40 바이트가 힙에 생성 되었다
int[] arr1 = new int[10];
// 6 바이트가 힙에 생성 되었다
char[] ch =new char[] {'a','b','c'};
// arr1배열에다 난수를 10개 대입
for (int i =0;i<arr1.length;i++){
// 1~10 까지의 난수 대입
arr1[i] = (int)(Math.random()*10)+1;
}
for (int i =0;i<arr1.length;i++){
if(i == (arr1.length)-1 ) {
System.out.print(arr1[i]);
}
else {
System.out.print(arr1[i]+",");
}
}
System.out.println();
// Arrays클래스는 배열을 조작하기 쉽게 만들어 놓은 유틸리티 클래스
System.out.println(Arrays.toString(arr1));
System.out.println(Arrays.toString(ch));
//주소 값 출력
// 출력 스트림에다가 참조 변수를 넣으면
// 참조 변수명.tostring()호출이된다
// char 타입 은 주소를 출력하려면 반듯이 toString()호출
System.out.println(arr1);
System.out.println(arr1.toString()); //타입@16진수
System.out.println(ch.toString());
System.out.println(ch);
}
}
| [
"[Github"
] | [Github |
6792e3f16a69fe3c1fe44e55e2e87ab32fa4d218 | d5d40e6b214ee15b0b63f87bba2220aef64c0a4c | /net.sf.smbt.i2c.thingm/src-model/net/sf/smbt/commands/impl/FadeToHSBColorCmdImpl.java | 68191b35816473cd57c96259e3313613f88f8c7e | [] | no_license | lucascraft/ubiquisense | adb2cc6cc2615bd8440d825be9a4bf59a854799b | 70c4a0c0790c3b37346c2e7117190802e5441ba5 | refs/heads/master | 2021-01-10T21:48:42.021551 | 2015-08-13T21:17:34 | 2015-08-13T21:17:34 | 37,203,783 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 892 | java | /**
* <copyright>
* </copyright>
*
* $Id: FadeToHSBColorCmdImpl.java,v 1.1 2008/12/28 12:32:54 lucascraft Exp $
*/
package net.sf.smbt.commands.impl;
import net.sf.smbt.commands.CommandsPackage;
import net.sf.smbt.commands.FadeToHSBColorCmd;
import org.eclipse.emf.ecore.EClass;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Fade To HSB Color Cmd</b></em>'.
* <!-- end-user-doc -->
* <p>
* </p>
*
* @generated
*/
public class FadeToHSBColorCmdImpl extends BlinkMCmdImpl implements FadeToHSBColorCmd {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected FadeToHSBColorCmdImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return CommandsPackage.Literals.FADE_TO_HSB_COLOR_CMD;
}
} //FadeToHSBColorCmdImpl
| [
"lucas.bigeardel@gmail.com"
] | lucas.bigeardel@gmail.com |
31af28fa0bcd20b17f03df8446daefc5d0ead227 | 33cdd6d7838f0c4769aaae766e5d760e9916a6ba | /BinarySearch.java | eb33298a23985ec6f67449017f7209b348d42966 | [] | no_license | Mricecool/SearchOrSort | 831e939312830e56722d2941768c627ec9ed52b2 | 51f223f652b7eaca4a04f378f6a33600645ab34b | refs/heads/master | 2021-07-04T18:44:31.333122 | 2017-09-26T08:47:04 | 2017-09-26T08:47:04 | 103,251,688 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,408 | java | package com.maptools.controller;
/**
* 二分查找(有序队列)
* Created by mr on 2017/9/26.
*/
public class BinarySearch {
static int target = 221;
public static void main(String[] args) {
int[] a = {2, 6, 9, 11, 12, 24, 27, 37, 48, 69, 88, 91, 193, 221};
System.out.println(search(a, target) + "");
System.out.println(binarySearch(a, target) + "");
}
//me
private static int search(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
int middle = (right - left) / 2;
while (left <= right) {
if (arr[middle] > target) {
right = middle - 1;
middle = (right - left) / 2;
} else if (arr[middle] < target) {
left = middle + 1;
middle = (right - left) / 2 + left;
} else {
return middle;
}
}
return -1;
}
//binarySearch
private static int binarySearch(int[] arr, int target) {
int l = 0;
int r = arr.length - 1;
while (l <= r) {
int middle = l + (r - l) / 2;
if (target < arr[middle]) {
r = middle - 1;
} else if (target > arr[middle]) {
l = middle + 1;
} else {
return middle;
}
}
return -1;
}
}
| [
"mricecool@sina.com"
] | mricecool@sina.com |
c7643077f48a1e9c9e8257ac847d533934b13844 | 90454419aa816f38fb9b9db0da844cc344df4d37 | /kodilla-patterns/src/test/java/com/kodilla/patterns/singleton/SettingsFileEngineTestSuite.java | 8d655ab623f60a527b87fa7439dd63d068641d01 | [] | no_license | kolodzij/java-course | 38cb487766fbd37d859d5fefe90d68b4df3d78af | 301d2dfa476c699f014762e09b7393315986892d | refs/heads/master | 2020-04-19T17:22:09.326709 | 2019-01-30T11:39:43 | 2019-01-30T11:39:43 | 168,333,220 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,202 | java | package com.kodilla.patterns.singleton;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class SettingsFileEngineTestSuite {
private static SettingsFileEngine settingsFileEngine;
@BeforeClass
public static void openSettingsFile() {
SettingsFileEngine.getInstance().open("myapp.settings");
}
@AfterClass
public static void closeSettingsFile() {
SettingsFileEngine.getInstance().close();
}
@Test
public void testGetFileName() {
//Given
//When
String fileName = SettingsFileEngine.getInstance().getFileName();
System.out.println("Opened: " + fileName);
//Then
Assert.assertEquals("myapp.settings", fileName);
}
@Test
public void testLoadSettings() {
//Given
//When
boolean result = SettingsFileEngine.getInstance().loadSettings();
//Then
Assert.assertTrue(result);
}
@Test
public void testSaveSettings() {
//Given
//When
boolean result = SettingsFileEngine.getInstance().saveSettings();
//Then
Assert.assertTrue(result);
}
} | [
"j.baranowska@gmail.com"
] | j.baranowska@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.