blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
12692226785ed5bf504fa162c95c6cd39cef2de3
Java
yangmo193829/spring_security
/src/main/java/fun/zyjk/spring_security/sys/entity/OtherSysUser.java
UTF-8
689
1.867188
2
[]
no_license
package fun.zyjk.spring_security.sys.entity; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; @Data @AllArgsConstructor @NoArgsConstructor public class OtherSysUser { private Long id; // 第三方系统 private String scope; // 第三方系统唯一账户 private String uuid; // 关联系统用户表的id private Long userId; // 本系统登陆的用户名 private String username; @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss") private Date createTime; @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss") private Date updateTime; }
true
7f776983175abbc0c7daf3e187fef69577348c2a
Java
hkbruvold/fellesprosjektet
/application/src/data/Group.java
UTF-8
1,397
3.1875
3
[]
no_license
package data; import java.io.Serializable; import java.util.List; import java.util.ArrayList; @SuppressWarnings("serial") public class Group implements Serializable { private int id; private String name; private String description; private ArrayList<User> members; public Group(){ members = new ArrayList<User>(); } /** * Use id = 0 when creating new objects. Actual id should come from database */ public Group(int id, String name, String description) { this.name = name; members = new ArrayList<User>(); this.description = description; } public String tosString() { return String.format("Group; ID: %s, Group name: %s, Description: %s, Number of members: %s", id, name, description, members.size()); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public ArrayList<User> getMembers() { return members; } public void addMember(User newMember) { if (!members.contains(newMember)) { members.add(newMember); } } public void addMembers(List<User> users) { for (User user : users) { addMember(user); } } public int getSize() { return members.size(); } }
true
8c2242a59c5e8e346b5070c0d6098ca322edb8b3
Java
matheussilva123/api-ticketopen
/src/main/java/com/ticketopen/resources/CategoryResources.java
UTF-8
1,870
2.25
2
[]
no_license
package com.ticketopen.resources; import com.ticketopen.domain.Category; import com.ticketopen.dto.CategoryDTO; import com.ticketopen.dto.CategoryNewDTO; import com.ticketopen.services.CategoryService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import javax.validation.Valid; import java.net.URI; @RestController @RequestMapping(value = "/categories") public class CategoryResources { @Autowired private CategoryService service; @PreAuthorize("hasAnyRole('USER')") @RequestMapping(value = "/{id}", method = RequestMethod.GET) public ResponseEntity<Category> findById(@PathVariable Integer id) { Category obj = service.findById(id); return ResponseEntity.ok().body(obj); } @PreAuthorize("hasAnyRole('ADMIN')") @RequestMapping(value = "/{id}", method = RequestMethod.PUT) public ResponseEntity<Void> update(@Valid @RequestBody CategoryDTO objDTO, @PathVariable Integer id) { Category obj = service.fromDTO(objDTO); obj.setId(id); obj = service.updateCategory(obj); return ResponseEntity.noContent().build(); } @PreAuthorize("hasAnyRole('ADMIN')") @RequestMapping(method = RequestMethod.POST) public ResponseEntity<Void> insertCategory(@Valid @RequestBody CategoryNewDTO objDto) { Category obj = service.fromDTO(objDto); obj = service.insertCategory(obj); URI uri = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{id}").buildAndExpand(obj.getId()).toUri(); return ResponseEntity.created(uri).build(); } }
true
0bceafd5998ae14d803a934a629618f6ba20bb62
Java
sahilk01/notes-mvvm-using-architecture-components
/app/src/main/java/com/elgigs/notesmvvm/NotesDatabase.java
UTF-8
1,759
2.484375
2
[]
no_license
package com.elgigs.notesmvvm; import android.content.Context; import android.os.AsyncTask; import androidx.annotation.NonNull; import androidx.room.Database; import androidx.room.Room; import androidx.room.RoomDatabase; import androidx.sqlite.db.SupportSQLiteDatabase; @Database(entities = {NotesEntity.class}, version = 1, exportSchema = false) public abstract class NotesDatabase extends RoomDatabase { private static NotesDatabase instance; public abstract NotesDao notesDao(); public static synchronized NotesDatabase getInstance(Context context) { if (instance == null) { instance = Room.databaseBuilder(context.getApplicationContext(), NotesDatabase.class, "notes_database") .fallbackToDestructiveMigration() .addCallback(roomCallback) .build(); } return instance; } private static RoomDatabase.Callback roomCallback = new RoomDatabase.Callback() { @Override public void onCreate(@NonNull SupportSQLiteDatabase db) { super.onCreate(db); new PolulateDBAsyncTask(instance).execute(); } }; private static class PolulateDBAsyncTask extends AsyncTask<Void, Void, Void> { private NotesDao notesDao; private PolulateDBAsyncTask(NotesDatabase db) { notesDao = db.notesDao(); } @Override protected Void doInBackground(Void... voids) { notesDao.insert(new NotesEntity("Title 1", "Description 1", 1)); notesDao.insert(new NotesEntity("Title 2", "Description 2", 2)); notesDao.insert(new NotesEntity("Title 3", "Description 3", 3)); return null; } } }
true
3b91e6f4fd48edd62af9305a3134558dc585d769
Java
shafaet3/Android-Apps-Pracitce
/CRUD APP Firebase/app/src/main/java/com/example/shafaet/crud/MainActivity.java
UTF-8
3,803
2.53125
3
[]
no_license
package com.example.shafaet.crud; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.Spinner; import android.widget.Toast; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private EditText editTextName; private Spinner spinner; private Button buttonAddArtist; private ListView listView; List<Artist> artistList; DatabaseReference databaseReferenceArtist; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //get firebase database reference. here artist node databaseReferenceArtist = FirebaseDatabase.getInstance().getReference("artist"); editTextName = findViewById(R.id.id_et_name); spinner = findViewById(R.id.id_spinner); buttonAddArtist = findViewById(R.id.id_btn_add_artist); listView = findViewById(R.id.id_lv_list_view); artistList = new ArrayList<Artist>(); buttonAddArtist.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { addArtist(); } }); } private void addArtist() { String artistName = editTextName.getText().toString().trim(); String genre = spinner.getSelectedItem().toString(); if(!TextUtils.isEmpty(artistName)){ //push method will create a unique string inside artist node. get key method will //return the unique string created by push method. String id = databaseReferenceArtist.push().getKey(); //Now creating Artist class object and passing id, artistName and genre by constructor. Artist artist = new Artist(id, artistName, genre); //Sending artist object to Firebase Database inside id, artist will save databaseReferenceArtist.child(id).setValue(artist); Toast.makeText(this, "Artist added", Toast.LENGTH_SHORT).show(); //Every time when addArtist method is called, push method will generate uniquely //identified key string and by get key method we will store it to id. when sending //artist object to firebase database inside each id artist object will saved. } else{ Toast.makeText(this, "You should enter a name", Toast.LENGTH_SHORT).show(); } } @Override protected void onStart() { super.onStart(); databaseReferenceArtist.addValueEventListener(new ValueEventListener() { //onDataChange method will execute everytime when data is changed firebase database. @Override public void onDataChange(DataSnapshot dataSnapshot) { artistList.clear(); for(DataSnapshot artistSnapshot : dataSnapshot.getChildren()){ Artist artist = artistSnapshot.getValue(Artist.class); artistList.add(artist); } ArtistList adapter = new ArtistList(MainActivity.this, artistList); listView.setAdapter(adapter); } @Override public void onCancelled(DatabaseError databaseError) { } }); } }
true
1488308ec3758a795dbfbfbae91cad669f37df61
Java
hkdijia/disruptor
/disruptorDemo/src/test/java/Test.java
UTF-8
2,813
2.609375
3
[ "Apache-2.0" ]
permissive
import com.gotkx.bean.RbCmd; import com.gotkx.bean.RbCmdFactory; import com.gotkx.bean.RbData; import com.gotkx.exception.DisruptorExceptionHandler; import com.lmax.disruptor.BlockingWaitStrategy; import com.lmax.disruptor.EventHandler; import com.lmax.disruptor.EventTranslatorOneArg; import com.lmax.disruptor.dsl.Disruptor; import com.lmax.disruptor.dsl.ProducerType; import lombok.extern.log4j.Log4j2; import net.openhft.affinity.AffinityStrategies; import net.openhft.affinity.AffinityThreadFactory; import java.util.Timer; import java.util.TimerTask; /** * @author HuangKai * @date 2021/7/18 16:12 */ @Log4j2 public class Test { public static void main(String[] args) { new Test().initDisruptor(); } private Disruptor disruptor; private void initDisruptor(){ disruptor = new Disruptor( // event factory new RbCmdFactory(), 1024, // 线程池 new AffinityThreadFactory("aft_core", AffinityStrategies.ANY), // 1个生产者线程 ProducerType.SINGLE, new BlockingWaitStrategy() ); // 全局异常处理器 DisruptorExceptionHandler<RbCmd> exceptionHandler = new DisruptorExceptionHandler<>("disruptor-1", (exception, seq) -> { log.error("Exception thrown on seq={}", seq, exception); }); disruptor.setDefaultExceptionHandler(exceptionHandler); // 定义消费者 消费排序 ConsumerA consumerA = new ConsumerA(); ConsumerB consumerB = new ConsumerB(); disruptor.handleEventsWith(consumerA).then(consumerB); disruptor.start(); // 定义生产者 1s发布一条数据 new Timer().schedule(new ProducerTask(),2000,1000); } private int index = 0; /** * 生产者线程 */ private class ProducerTask extends TimerTask{ @Override public void run() { disruptor.getRingBuffer().publishEvent(PUB_TRANSLATOR, new RbData(index, "hello world")); index++; } } private static final EventTranslatorOneArg<RbCmd, RbData> PUB_TRANSLATOR = ((rbCmd, seq, rbData) -> { rbCmd.code = rbData.code; rbCmd.msg = rbData.msg; }); /** * 消费线程A */ private class ConsumerA implements EventHandler<RbCmd>{ @Override public void onEvent(RbCmd rbCmd, long seq, boolean b) throws Exception { log.info("ConsumerA recv : {}", rbCmd); } } /** * 消费线程B */ private class ConsumerB implements EventHandler<RbCmd>{ @Override public void onEvent(RbCmd rbCmd, long seq, boolean b) throws Exception { log.info("ConsumerB recv : {}", rbCmd); } } }
true
6cae11cfd307b2cab3c40bd885b053877f0e295a
Java
DragooNArT/Capstone-Project
/brewers_notepad/src/main/java/com/example/brewersnotepad/mobile/adapters/GrainListAdapter.java
UTF-8
2,660
2.203125
2
[]
no_license
package com.example.brewersnotepad.mobile.adapters; import android.app.ActionBar; import android.content.Context; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.example.brewersnotepad.R; import com.example.brewersnotepad.mobile.data.GrainEntry; import com.example.brewersnotepad.mobile.listeners.DeleteListListener; import com.example.brewersnotepad.mobile.providers.RecipeRuntimeManager; /** * Created by xnml on 12.5.2016 г.. */ public class GrainListAdapter<T> extends BaseListAdapter<GrainEntry> { private LayoutInflater inflater; private DeleteListListener removeListener; private ListView grainList; public GrainListAdapter(Context context, int resource,ListView grainList) { super(context, resource); this.grainList = grainList; this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); MAX_HEIGHT = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 180, getContext().getResources().getDisplayMetrics()); removeListener = new DeleteListListener(this); } @Override public void remove(GrainEntry object) { RecipeRuntimeManager.getCurrentRecipe().getRecipe_grains().remove(object); super.remove(object); } @Override public void notifyDataSetChanged() { super.notifyDataSetChanged(); LinearLayout.LayoutParams mParam = new LinearLayout.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,Math.round(getTargetHeight())); grainList.setLayoutParams(mParam); } @Override public View getView(int position, View convertView, ViewGroup parent) { if(convertView == null) { convertView = inflater.inflate(R.layout.grain_list_item, parent, false); } GrainEntry grainEntry = getItem(position); TextView grainTypeUi = (TextView)convertView.findViewById(R.id.grain_list_type_entry); TextView grainQuantityUi = (TextView)convertView.findViewById(R.id.grain_list_quantity_entry); ImageView deleteGrainBtn = (ImageView)convertView.findViewById(R.id.deleteGrainButton); deleteGrainBtn.setTag(position); //TODO always removes last element(fixme) deleteGrainBtn.setOnClickListener(removeListener); grainTypeUi.setText(grainEntry.getGrainType()); grainQuantityUi.setText(metricsProvider.convertWeightToText(grainEntry.getGrainQuantity())); return convertView; } }
true
36053993bc7d89ab298c2938f78c43b300679caa
Java
nikhatmallick/NikhatGit
/Lab/Lab_1.1/Registration/src/main/java/com/uciext/springfw/class01/courses/service/CourseService.java
UTF-8
190
1.867188
2
[]
no_license
package com.uciext.springfw.class01.courses.service; import com.uciext.springfw.class01.courses.model.Course; public interface CourseService { public Course getCourse(String courseId); }
true
3b89329d209f135d540abf182791387665e65aef
Java
FatConan/formic-acid
/src/main/java/de/themonstrouscavalca/formicacid/extractors/impl/basic/IntegerExtractor.java
UTF-8
1,303
2.71875
3
[ "MIT" ]
permissive
package de.themonstrouscavalca.formicacid.extractors.impl.basic; import com.fasterxml.jackson.databind.JsonNode; import de.themonstrouscavalca.formicacid.extractors.defn.IExtract; import de.themonstrouscavalca.formicacid.extractors.impl.AbstractExtractor; import de.themonstrouscavalca.formicacid.helpers.ParsableValue; public class IntegerExtractor extends AbstractExtractor<Integer> implements IExtract<Integer>{ @Override protected String parsingErrorText(){ return "This should be an integer"; } @Override public ParsableValue<Integer> extractValueFromJson(JsonNode node){ if(this.missing(node)){ return ParsableValue.empty(); } if(node.isInt()){ return ParsableValue.of(true, node.asInt()); } if(node.isLong()){ if(node.asLong() <= Integer.MAX_VALUE && node.asLong() >= Integer.MIN_VALUE){ return ParsableValue.of(true, node.asInt()); }else{ return ParsableValue.invalid(); } } if(node.isTextual()){ try{ return ParsableValue.of(true, Integer.parseInt(node.asText())); }catch(NumberFormatException e){ } } return ParsableValue.invalid(); } }
true
6414039a01cf3954269484a54cabda584518e3c3
Java
gorans90/cb-sb-api
/src/main/java/com/carbook/http/server/exceptions/general/HTTPServerException.java
UTF-8
220
2.140625
2
[]
no_license
package com.carbook.http.server.exceptions.general; /** * Created by Marko Pozdnjakov on 12/13/17. */ public class HTTPServerException extends Exception{ public HTTPServerException(String message){ super(message); } }
true
07efc51cb55f8d2c59d8e6bbb026b3f61445c2ea
Java
PedroAlmeidacode/SGP-WebService
/Projeto/src/tests/pt/ufp/info/esof/sgp/models/TarefaTest.java
UTF-8
6,064
2.890625
3
[]
no_license
package pt.ufp.info.esof.sgp.models; import org.junit.jupiter.api.Test; import pt.ufp.info.esof.sgp.models.enums.Cargo; import pt.ufp.info.esof.sgp.models.enums.Estado; import java.time.LocalDateTime; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; class TarefaTest { @Test void testGetCustoTarefa() { // empregado nao existe Tarefa tarefa = new Tarefa(); assertEquals(tarefa.getCustoTarefa(),0); // empregado nao tem cargo atribuido Empregado empregado = new Empregado(); empregado.adicionarTarefa(tarefa); assertEquals(tarefa.getCustoTarefa(),0); // caso normal Analista_junior tarefa.setDuracaoEstimada(60); empregado.setCargo(Cargo.ANALISTA_JUNIOR); assertEquals(tarefa.getCustoTarefa(),20); // caso normal Des_junior empregado.setCargo(Cargo.DES_JUNIOR); assertEquals(tarefa.getCustoTarefa(),10); // caso normal Des_senior empregado.setCargo(Cargo.DES_SENIOR); assertEquals(tarefa.getCustoTarefa(),40); // caso normal Analista_senior empregado.setCargo(Cargo.ANLISTA_SENIOR); assertEquals(tarefa.getCustoTarefa(),80); // TODO return 0 not reached } @Test void TestsetLocalDates() { Tarefa tarefa = new Tarefa(); tarefa.setTarefaAtual(new TarefaAtual()); LocalDateTime now = LocalDateTime.now(); tarefa.setDataIniciacao(now); tarefa.getTarefaAtual().setUltimaAtualizacao(now); // atualiza todas as datas para agora tarefa.setLocalDates(); assertNotEquals(tarefa.getTarefaAtual().getUltimaAtualizacao(), now); assertNotEquals(tarefa.getDataIniciacao(), now); } @Test void testGetEstadoTarefa() { // esperado um estado de tarefa normal Tarefa tarefa = new Tarefa(); Empregado empregado = new Empregado(); empregado.adicionarTarefa(tarefa); // duaracao estimada = 1000 min tarefa.setDuracaoEstimada(1000); // percentual de conclusao = 50 tarefa.getTarefaAtual().setPercentualConclusao(50); // tempo dedicado = 500 min tarefa.getTarefaAtual().setTempoDedicado(500); // percentagem de tempo usado = 500 * 100 / 1000 = 50% (diferencial 50 - 50 = 0) assertEquals(Estado.NORMAL, tarefa.getEstadoTarefa()); // esperado um estado de tarefa normal , diferencial de menos de 10 entre // a percentagem de tempo usada em relacao ao tempo que tem e a percentagem de conclusao tarefa.getTarefaAtual().setTempoDedicado(580); // percentagem de tempo usado = 580 * 100 / 1000 = 58% (diferencial 58-50 = 8) assertEquals(Estado.NORMAL, tarefa.getEstadoTarefa()); // esperado um estado de tarefa atrasada visto que conclui menos do que o tempo que usou // e o diferencial entre o tempo usado e o feito é maior que 10 tarefa.getTarefaAtual().setTempoDedicado(700); // percentagem de tempo usado = 700 * 100 / 1000 = 70% (diferencial 70-50 = 20) assertEquals(Estado.ATRASADA, tarefa.getEstadoTarefa()); // esperado um estado de tarefa adiantada visto que conclui mais do que o tempo que usou tarefa.getTarefaAtual().setTempoDedicado(400); // percentagem de tempo usado = 400 * 100 / 1000 = 40% (40 < 50-> percentual de concluao) assertEquals(Estado.ADIANTADA, tarefa.getEstadoTarefa()); // esperando um estado de tarefa concluida visto que o seu estado de conclusao e 100 tarefa.getTarefaAtual().setPercentualConclusao(100); assertEquals(Estado.CONCLUIDA, tarefa.getEstadoTarefa()); // esperando um estado de tarefa "TAREFA_NAO_ATRBUIDA" Tarefa tarefa1 = new Tarefa(); assertEquals(Estado.TAREFA_NAO_ATRBUIDA, tarefa1.getEstadoTarefa()); // existem duas formas de a tarefa estar atrasada por exesso de tempo // 1 - o tempo dedicado pelo empregado é maior do que o tempo previsto // 2 - tarefaAtual.ultimaAtualizacao > Tarefa.dataIniciacao + Tarefa.duracaoEstimada // 1 - esperando um esatado de tarefa atrasado pois // a tarefa nao foi concluida dentro da duracao estimada Empregado empregado1 = new Empregado(); empregado1.adicionarTarefa(tarefa1); // duaracao estimada = 100 min tarefa1.setDuracaoEstimada(100); tarefa1.getTarefaAtual().setPercentualConclusao(50); // tempo dedicado = 500 min tarefa1.getTarefaAtual().setTempoDedicado(500); assertEquals(Estado.ATRASADA, tarefa1.getEstadoTarefa()); // 2 - esperando um esatado de tarefa atrasado pois // a ultima do gestor e depois do prazo previsto Tarefa tarefa2 = new Tarefa(); Empregado empregado2 = new Empregado(); empregado2.adicionarTarefa(tarefa2); tarefa2.setDuracaoEstimada(100); tarefa2.getTarefaAtual().setTempoDedicado(50); tarefa2.getTarefaAtual().setPercentualConclusao(50); // excede 10 minutos o prazo de finalizacao da tarefa que era de Tarefa.dataIniciacao + Tarefa.duracaoEstimada tarefa2.getTarefaAtual().setUltimaAtualizacao(tarefa2.getDataIniciacao().plusMinutes(110)); assertEquals(Estado.ATRASADA, tarefa2.getEstadoTarefa()); } @Test void testsetTempoDedicadoEmTarefaAtual() { // tempo negativo Empregado empregado = new Empregado(); Tarefa tarefa = new Tarefa(); empregado.adicionarTarefa(tarefa); tarefa.setTempoDedicadoEmTarefaAtual(-1); assertNotEquals(tarefa.getTarefaAtual().getTempoDedicado(),-1); // caso normal tarefa.setTempoDedicadoEmTarefaAtual(28); assertEquals(tarefa.getTarefaAtual().getTempoDedicado(), 28); // caso mais 22 que da 50 tarefa.setTempoDedicadoEmTarefaAtual(22); assertEquals(tarefa.getTarefaAtual().getTempoDedicado(), 50); } }
true
80c98323878ff965c88562899a5254e8ad182803
Java
apache/curator
/curator-recipes/src/main/java/org/apache/curator/framework/recipes/cache/PathChildrenCache.java
UTF-8
30,961
1.75
2
[ "Apache-2.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.curator.framework.recipes.cache; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import java.io.Closeable; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Exchanger; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.EnsureContainers; import org.apache.curator.framework.WatcherRemoveCuratorFramework; import org.apache.curator.framework.api.BackgroundCallback; import org.apache.curator.framework.api.CuratorEvent; import org.apache.curator.framework.listen.Listenable; import org.apache.curator.framework.listen.StandardListenerManager; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.framework.state.ConnectionStateListener; import org.apache.curator.utils.CloseableExecutorService; import org.apache.curator.utils.PathUtils; import org.apache.curator.utils.ThreadUtils; import org.apache.curator.utils.ZKPaths; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p>A utility that attempts to keep all data from all children of a ZK path locally cached. This class * will watch the ZK path, respond to update/create/delete events, pull down the data, etc. You can * register a listener that will get notified when changes occur.</p> * <p></p> * <p><b>IMPORTANT</b> - it's not possible to stay transactionally in sync. Users of this class must * be prepared for false-positives and false-negatives. Additionally, always use the version number * when updating data to avoid overwriting another process' change.</p> * * @deprecated replace by {@link org.apache.curator.framework.recipes.cache.CuratorCache} */ @Deprecated public class PathChildrenCache implements Closeable { private final Logger log = LoggerFactory.getLogger(getClass()); private final WatcherRemoveCuratorFramework client; private final String path; private final CloseableExecutorService executorService; private final boolean cacheData; private final boolean dataIsCompressed; private final StandardListenerManager<PathChildrenCacheListener> listeners = StandardListenerManager.standard(); private final ConcurrentMap<String, ChildData> currentData = Maps.newConcurrentMap(); private final AtomicReference<Map<String, ChildData>> initialSet = new AtomicReference<Map<String, ChildData>>(); private final Set<Operation> operationsQuantizer = Sets.newSetFromMap(Maps.<Operation, Boolean>newConcurrentMap()); private final AtomicReference<State> state = new AtomicReference<State>(State.LATENT); private final EnsureContainers ensureContainers; private enum State { LATENT, STARTED, CLOSED } private static final ChildData NULL_CHILD_DATA = new ChildData("/", null, null); private static final boolean USE_EXISTS = Boolean.getBoolean("curator-path-children-cache-use-exists"); private volatile Watcher childrenWatcher = new Watcher() { @Override public void process(WatchedEvent event) { offerOperation(new RefreshOperation(PathChildrenCache.this, RefreshMode.STANDARD)); } }; private volatile Watcher dataWatcher = new Watcher() { @Override public void process(WatchedEvent event) { try { if (event.getType() == Event.EventType.NodeDeleted) { remove(event.getPath()); } else if (event.getType() == Event.EventType.NodeDataChanged) { offerOperation(new GetDataOperation(PathChildrenCache.this, event.getPath())); } } catch (Exception e) { ThreadUtils.checkInterrupted(e); handleException(e); } } }; @VisibleForTesting volatile Exchanger<Object> rebuildTestExchanger; private volatile ConnectionStateListener connectionStateListener = new ConnectionStateListener() { @Override public void stateChanged(CuratorFramework client, ConnectionState newState) { handleStateChange(newState); } }; public static final Supplier<ThreadFactory> defaultThreadFactorySupplier = () -> ThreadUtils.newThreadFactory("PathChildrenCache"); /** * @param client the client * @param path path to watch * @param mode caching mode * @deprecated use {@link #PathChildrenCache(CuratorFramework, String, boolean)} instead */ @Deprecated @SuppressWarnings("deprecation") public PathChildrenCache(CuratorFramework client, String path, PathChildrenCacheMode mode) { this( client, path, mode != PathChildrenCacheMode.CACHE_PATHS_ONLY, false, new CloseableExecutorService( Executors.newSingleThreadExecutor(defaultThreadFactorySupplier.get()), true)); } /** * @param client the client * @param path path to watch * @param mode caching mode * @param threadFactory factory to use when creating internal threads * @deprecated use {@link #PathChildrenCache(CuratorFramework, String, boolean, ThreadFactory)} instead */ @Deprecated @SuppressWarnings("deprecation") public PathChildrenCache( CuratorFramework client, String path, PathChildrenCacheMode mode, ThreadFactory threadFactory) { this( client, path, mode != PathChildrenCacheMode.CACHE_PATHS_ONLY, false, new CloseableExecutorService(Executors.newSingleThreadExecutor(threadFactory), true)); } /** * @param client the client * @param path path to watch * @param cacheData if true, node contents are cached in addition to the stat */ public PathChildrenCache(CuratorFramework client, String path, boolean cacheData) { this( client, path, cacheData, false, new CloseableExecutorService( Executors.newSingleThreadExecutor(defaultThreadFactorySupplier.get()), true)); } /** * @param client the client * @param path path to watch * @param cacheData if true, node contents are cached in addition to the stat * @param threadFactory factory to use when creating internal threads */ public PathChildrenCache(CuratorFramework client, String path, boolean cacheData, ThreadFactory threadFactory) { this( client, path, cacheData, false, new CloseableExecutorService(Executors.newSingleThreadExecutor(threadFactory), true)); } /** * @param client the client * @param path path to watch * @param cacheData if true, node contents are cached in addition to the stat * @param dataIsCompressed if true, data in the path is compressed * @param threadFactory factory to use when creating internal threads */ public PathChildrenCache( CuratorFramework client, String path, boolean cacheData, boolean dataIsCompressed, ThreadFactory threadFactory) { this( client, path, cacheData, dataIsCompressed, new CloseableExecutorService(Executors.newSingleThreadExecutor(threadFactory), true)); } /** * @param client the client * @param path path to watch * @param cacheData if true, node contents are cached in addition to the stat * @param dataIsCompressed if true, data in the path is compressed * @param executorService ExecutorService to use for the PathChildrenCache's background thread. This service should be single threaded, otherwise the cache may see inconsistent results. */ public PathChildrenCache( CuratorFramework client, String path, boolean cacheData, boolean dataIsCompressed, final ExecutorService executorService) { this(client, path, cacheData, dataIsCompressed, new CloseableExecutorService(executorService)); } /** * @param client the client * @param path path to watch * @param cacheData if true, node contents are cached in addition to the stat * @param dataIsCompressed if true, data in the path is compressed * @param executorService Closeable ExecutorService to use for the PathChildrenCache's background thread. This service should be single threaded, otherwise the cache may see inconsistent results. */ public PathChildrenCache( CuratorFramework client, String path, boolean cacheData, boolean dataIsCompressed, final CloseableExecutorService executorService) { this.client = client.newWatcherRemoveCuratorFramework(); this.path = PathUtils.validatePath(path); this.cacheData = cacheData; this.dataIsCompressed = dataIsCompressed; this.executorService = executorService; ensureContainers = new EnsureContainers(client, path); } /** * Start the cache. The cache is not started automatically. You must call this method. * * @throws Exception errors */ public void start() throws Exception { start(StartMode.NORMAL); } /** * Same as {@link #start()} but gives the option of doing an initial build * * @param buildInitial if true, {@link #rebuild()} will be called before this method * returns in order to get an initial view of the node; otherwise, * the cache will be initialized asynchronously * @throws Exception errors * @deprecated use {@link #start(StartMode)} */ @Deprecated public void start(boolean buildInitial) throws Exception { start(buildInitial ? StartMode.BUILD_INITIAL_CACHE : StartMode.NORMAL); } /** * Method of priming cache on {@link PathChildrenCache#start(StartMode)} */ public enum StartMode { /** * The cache will be primed (in the background) with initial values. * Events for existing and new nodes will be posted. */ NORMAL, /** * The cache will be primed (in the foreground) with initial values. * {@link PathChildrenCache#rebuild()} will be called before * the {@link PathChildrenCache#start(StartMode)} method returns * in order to get an initial view of the node. */ BUILD_INITIAL_CACHE, /** * After cache is primed with initial values (in the background) a * {@link PathChildrenCacheEvent.Type#INITIALIZED} will be posted. */ POST_INITIALIZED_EVENT } /** * Start the cache. The cache is not started automatically. You must call this method. * * @param mode Method for priming the cache * @throws Exception errors */ public void start(StartMode mode) throws Exception { Preconditions.checkState(state.compareAndSet(State.LATENT, State.STARTED), "already started"); mode = Preconditions.checkNotNull(mode, "mode cannot be null"); client.getConnectionStateListenable().addListener(connectionStateListener); switch (mode) { case NORMAL: { offerOperation(new RefreshOperation(this, RefreshMode.STANDARD)); break; } case BUILD_INITIAL_CACHE: { rebuild(); break; } case POST_INITIALIZED_EVENT: { initialSet.set(Maps.<String, ChildData>newConcurrentMap()); offerOperation(new RefreshOperation(this, RefreshMode.POST_INITIALIZED)); break; } } } /** * NOTE: this is a BLOCKING method. Completely rebuild the internal cache by querying * for all needed data WITHOUT generating any events to send to listeners. * * @throws Exception errors */ public void rebuild() throws Exception { Preconditions.checkState(state.get() == State.STARTED, "cache has been closed"); ensurePath(); clear(); List<String> children = client.getChildren().forPath(path); for (String child : children) { String fullPath = ZKPaths.makePath(path, child); internalRebuildNode(fullPath); if (rebuildTestExchanger != null) { rebuildTestExchanger.exchange(new Object()); } } // this is necessary so that any updates that occurred while rebuilding are taken offerOperation(new RefreshOperation(this, RefreshMode.FORCE_GET_DATA_AND_STAT)); } /** * NOTE: this is a BLOCKING method. Rebuild the internal cache for the given node by querying * for all needed data WITHOUT generating any events to send to listeners. * * @param fullPath full path of the node to rebuild * @throws Exception errors */ public void rebuildNode(String fullPath) throws Exception { Preconditions.checkArgument( ZKPaths.getPathAndNode(fullPath).getPath().equals(path), "Node is not part of this cache: " + fullPath); Preconditions.checkState(state.get() == State.STARTED, "cache has been closed"); ensurePath(); internalRebuildNode(fullPath); // this is necessary so that any updates that occurred while rebuilding are taken // have to rebuild entire tree in case this node got deleted in the interim offerOperation(new RefreshOperation(this, RefreshMode.FORCE_GET_DATA_AND_STAT)); } /** * Close/end the cache * * @throws IOException errors */ @Override public void close() throws IOException { if (state.compareAndSet(State.STARTED, State.CLOSED)) { client.getConnectionStateListenable().removeListener(connectionStateListener); listeners.clear(); executorService.close(); client.removeWatchers(); // TODO // This seems to enable even more GC - I'm not sure why yet - it // has something to do with Guava's cache and circular references connectionStateListener = null; childrenWatcher = null; dataWatcher = null; } } /** * Return the cache listenable * * @return listenable */ public Listenable<PathChildrenCacheListener> getListenable() { return listeners; } /** * Return the current data. There are no guarantees of accuracy. This is * merely the most recent view of the data. The data is returned in sorted order. * * @return list of children and data */ public List<ChildData> getCurrentData() { return ImmutableList.copyOf(Sets.<ChildData>newTreeSet(currentData.values())); } /** * Return the current data for the given path. There are no guarantees of accuracy. This is * merely the most recent view of the data. If there is no child with that path, <code>null</code> * is returned. * * @param fullPath full path to the node to check * @return data or null */ public ChildData getCurrentData(String fullPath) { return currentData.get(fullPath); } /** * As a memory optimization, you can clear the cached data bytes for a node. Subsequent * calls to {@link ChildData#getData()} for this node will return <code>null</code>. * * @param fullPath the path of the node to clear */ public void clearDataBytes(String fullPath) { clearDataBytes(fullPath, -1); } /** * As a memory optimization, you can clear the cached data bytes for a node. Subsequent * calls to {@link ChildData#getData()} for this node will return <code>null</code>. * * @param fullPath the path of the node to clear * @param ifVersion if non-negative, only clear the data if the data's version matches this version * @return true if the data was cleared */ public boolean clearDataBytes(String fullPath, int ifVersion) { ChildData data = currentData.get(fullPath); if (data != null) { if ((ifVersion < 0) || (ifVersion == data.getStat().getVersion())) { if (data.getData() != null) { currentData.replace(fullPath, data, new ChildData(data.getPath(), data.getStat(), null)); } return true; } } return false; } /** * Clear out current data and begin a new query on the path * * @throws Exception errors */ public void clearAndRefresh() throws Exception { currentData.clear(); offerOperation(new RefreshOperation(this, RefreshMode.STANDARD)); } /** * Clears the current data without beginning a new query and without generating any events * for listeners. */ public void clear() { currentData.clear(); } enum RefreshMode { STANDARD, FORCE_GET_DATA_AND_STAT, POST_INITIALIZED, NO_NODE_EXCEPTION } void refresh(final RefreshMode mode) throws Exception { ensurePath(); final BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { if (reRemoveWatchersOnBackgroundClosed()) { return; } if (event.getResultCode() == KeeperException.Code.OK.intValue()) { processChildren(event.getChildren(), mode); } else if (event.getResultCode() == KeeperException.Code.NONODE.intValue()) { if (mode == RefreshMode.NO_NODE_EXCEPTION) { log.debug( "KeeperException.NoNodeException received for getChildren() and refresh has failed. Resetting ensureContainers but not refreshing. Path: [{}]", path); ensureContainers.reset(); } else { log.debug( "KeeperException.NoNodeException received for getChildren(). Resetting ensureContainers. Path: [{}]", path); ensureContainers.reset(); offerOperation(new RefreshOperation(PathChildrenCache.this, RefreshMode.NO_NODE_EXCEPTION)); } } } }; client.getChildren() .usingWatcher(childrenWatcher) .inBackground(callback) .forPath(path); } void callListeners(final PathChildrenCacheEvent event) { listeners.forEach(listener -> { try { listener.childEvent(client, event); } catch (Exception e) { ThreadUtils.checkInterrupted(e); handleException(e); } }); } void getDataAndStat(final String fullPath) throws Exception { BackgroundCallback callback = new BackgroundCallback() { @Override public void processResult(CuratorFramework client, CuratorEvent event) throws Exception { if (reRemoveWatchersOnBackgroundClosed()) { return; } applyNewData(fullPath, event.getResultCode(), event.getStat(), cacheData ? event.getData() : null); } }; if (USE_EXISTS && !cacheData) { client.checkExists() .usingWatcher(dataWatcher) .inBackground(callback) .forPath(fullPath); } else { // always use getData() instead of exists() to avoid leaving unneeded watchers which is a type of resource // leak if (dataIsCompressed && cacheData) { client.getData() .decompressed() .usingWatcher(dataWatcher) .inBackground(callback) .forPath(fullPath); } else { client.getData() .usingWatcher(dataWatcher) .inBackground(callback) .forPath(fullPath); } } } /** * Default behavior is just to log the exception * * @param e the exception */ protected void handleException(Throwable e) { log.error("", e); } protected void ensurePath() throws Exception { ensureContainers.ensure(); } @VisibleForTesting protected void remove(String fullPath) { ChildData data = currentData.remove(fullPath); if (data != null) { offerOperation(new EventOperation( this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CHILD_REMOVED, data))); } Map<String, ChildData> localInitialSet = initialSet.get(); if (localInitialSet != null) { localInitialSet.remove(ZKPaths.getNodeFromPath(fullPath)); maybeOfferInitializedEvent(localInitialSet); } } private boolean reRemoveWatchersOnBackgroundClosed() { if (state.get().equals(State.CLOSED)) { client.removeWatchers(); return true; } return false; } private void internalRebuildNode(String fullPath) throws Exception { if (cacheData) { try { Stat stat = new Stat(); byte[] bytes = dataIsCompressed ? client.getData().decompressed().storingStatIn(stat).forPath(fullPath) : client.getData().storingStatIn(stat).forPath(fullPath); currentData.put(fullPath, new ChildData(fullPath, stat, bytes)); } catch (KeeperException.NoNodeException ignore) { // node no longer exists - remove it currentData.remove(fullPath); } } else { Stat stat = client.checkExists().forPath(fullPath); if (stat != null) { currentData.put(fullPath, new ChildData(fullPath, stat, null)); } else { // node no longer exists - remove it currentData.remove(fullPath); } } } private void handleStateChange(ConnectionState newState) { switch (newState) { case SUSPENDED: { offerOperation(new EventOperation( this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CONNECTION_SUSPENDED, null))); break; } case LOST: { offerOperation(new EventOperation( this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CONNECTION_LOST, null))); break; } case CONNECTED: case RECONNECTED: { try { offerOperation(new RefreshOperation(this, RefreshMode.FORCE_GET_DATA_AND_STAT)); offerOperation(new EventOperation( this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CONNECTION_RECONNECTED, null))); } catch (Exception e) { ThreadUtils.checkInterrupted(e); handleException(e); } break; } } } private void processChildren(List<String> children, RefreshMode mode) throws Exception { Set<String> removedNodes = Sets.newHashSet(currentData.keySet()); for (String child : children) { removedNodes.remove(ZKPaths.makePath(path, child)); } for (String fullPath : removedNodes) { remove(fullPath); } for (String name : children) { String fullPath = ZKPaths.makePath(path, name); if ((mode == RefreshMode.FORCE_GET_DATA_AND_STAT) || !currentData.containsKey(fullPath)) { getDataAndStat(fullPath); } updateInitialSet(name, NULL_CHILD_DATA); } maybeOfferInitializedEvent(initialSet.get()); } private void applyNewData(String fullPath, int resultCode, Stat stat, byte[] bytes) { if (resultCode == KeeperException.Code.OK .intValue()) // otherwise - node must have dropped or something - we should be getting another // event { ChildData data = new ChildData(fullPath, stat, bytes); ChildData previousData = currentData.put(fullPath, data); if (previousData == null) // i.e. new { offerOperation(new EventOperation( this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CHILD_ADDED, data))); } else if (stat.getMzxid() != previousData.getStat().getMzxid()) { offerOperation(new EventOperation( this, new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.CHILD_UPDATED, data))); } updateInitialSet(ZKPaths.getNodeFromPath(fullPath), data); } else if (resultCode == KeeperException.Code.NONODE.intValue()) { log.debug("NoNode at path {}, removing child from initialSet", fullPath); remove(fullPath); } } private void updateInitialSet(String name, ChildData data) { Map<String, ChildData> localInitialSet = initialSet.get(); if (localInitialSet != null) { localInitialSet.put(name, data); maybeOfferInitializedEvent(localInitialSet); } } private void maybeOfferInitializedEvent(Map<String, ChildData> localInitialSet) { if (!hasUninitialized(localInitialSet)) { // all initial children have been processed - send initialized message if (initialSet.getAndSet(null) != null) // avoid edge case - don't send more than 1 INITIALIZED event { final List<ChildData> children = ImmutableList.copyOf(localInitialSet.values()); PathChildrenCacheEvent event = new PathChildrenCacheEvent(PathChildrenCacheEvent.Type.INITIALIZED, null) { @Override public List<ChildData> getInitialData() { return children; } }; offerOperation(new EventOperation(this, event)); } } } private boolean hasUninitialized(Map<String, ChildData> localInitialSet) { if (localInitialSet == null) { return false; } Map<String, ChildData> uninitializedChildren = Maps.filterValues(localInitialSet, new Predicate<ChildData>() { @Override public boolean apply(ChildData input) { return (input == NULL_CHILD_DATA); // check against ref intentional } }); return (uninitializedChildren.size() != 0); } void offerOperation(final Operation operation) { if (operationsQuantizer.add(operation)) { submitToExecutor(new Runnable() { @Override public void run() { try { operationsQuantizer.remove(operation); operation.invoke(); } catch (InterruptedException e) { // We expect to get interrupted during shutdown, // so just ignore these events if (state.get() != State.CLOSED) { handleException(e); } Thread.currentThread().interrupt(); } catch (Exception e) { ThreadUtils.checkInterrupted(e); handleException(e); } } }); } } /** * Submits a runnable to the executor. * <p> * This method is synchronized because it has to check state about whether this instance is still open. Without this check * there is a race condition with the dataWatchers that get set. Even after this object is closed() it can still be * called by those watchers, because the close() method cannot actually disable the watcher. * <p> * The synchronization overhead should be minimal if non-existant as this is generally only called from the * ZK client thread and will only contend if close() is called in parallel with an update, and that's the exact state * we want to protect from. * * @param command The runnable to run */ private synchronized void submitToExecutor(final Runnable command) { if (state.get() == State.STARTED) { executorService.submit(command); } } }
true
a804bebe071bca517be55b91454375c8b9690ec9
Java
yany8060/SpringDemo
/SpringWar/src/main/java/com/yany/common/redis/JedisClusterFactory.java
UTF-8
1,994
2.375
2
[]
no_license
package com.yany.common.redis; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import redis.clients.jedis.HostAndPort; import java.util.HashSet; import java.util.Set; /** * spring bean形式引用 */ public class JedisClusterFactory { private String redisConnectList; private Integer timeout; private Integer maxRedirections; private GenericObjectPoolConfig genericObjectPoolConfig; private redis.clients.jedis.JedisCluster jedisCluster = null; public redis.clients.jedis.JedisCluster getInstance() { return jedisCluster; } public void init() { String[] jedisClusterNodes = redisConnectList.split(","); Set<HostAndPort> jeAndPorts = new HashSet<>(); for (String redisHost : jedisClusterNodes) { String[] hostAndPort = redisHost.split(":"); jeAndPorts.add(new HostAndPort(hostAndPort[0], new Integer(hostAndPort[1]))); } jedisCluster = new redis.clients.jedis.JedisCluster(jeAndPorts, timeout, maxRedirections, genericObjectPoolConfig); } public String getRedisConnectList() { return redisConnectList; } public void setRedisConnectList(String redisConnectList) { this.redisConnectList = redisConnectList; } public Integer getTimeout() { return timeout; } public void setTimeout(Integer timeout) { this.timeout = timeout; } public Integer getMaxRedirections() { return maxRedirections; } public void setMaxRedirections(Integer maxRedirections) { this.maxRedirections = maxRedirections; } public GenericObjectPoolConfig getGenericObjectPoolConfig() { return genericObjectPoolConfig; } public void setGenericObjectPoolConfig(GenericObjectPoolConfig genericObjectPoolConfig) { this.genericObjectPoolConfig = genericObjectPoolConfig; } }
true
88711303d553bf01c0b91b934fa3f11e0826f6e1
Java
tomascarvalho/SystemsIntegration_Assignment3
/IS_Assignment2_copy/projeto2-business/src/main/java/crawler/TopicSender.java
UTF-8
898
2.5625
3
[]
no_license
package crawler; import javax.jms.*; import javax.naming.InitialContext; import javax.naming.NamingException; import data.Car; /** * Created by jorgearaujo on 26/09/2017. */ public class TopicSender { private ConnectionFactory cf; private Topic tpc; public TopicSender() throws NamingException { this.cf = InitialContext.doLookup("jms/RemoteConnectionFactory"); //lookup for Topic this.tpc = (Topic) InitialContext.doLookup("jms/topic/TopicExample"); } public void sendToTopic(Car car) throws NamingException { try (JMSContext cntx = this.cf.createContext("joao", "br1o+sa*")) { //topic producer JMSProducer prod = cntx.createProducer(); //send message to topic ObjectMessage objectMessage = cntx.createObjectMessage(car); prod.send(tpc,objectMessage); } } }
true
8bb886615d135402a6ee60848fbae9e1978b5ea6
Java
apache/netbeans
/platform/openide.text/test/unit/src/org/netbeans/modules/openide/text/AskEditorQuestionsTest.java
UTF-8
2,903
1.890625
2
[ "Apache-2.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.openide.text; import java.awt.Dialog; import java.util.Locale; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Before; import org.junit.Test; import org.netbeans.junit.MockServices; import org.openide.DialogDescriptor; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; public class AskEditorQuestionsTest { public AskEditorQuestionsTest() { } @Before public void setUp() { Locale.setDefault(Locale.ENGLISH); MockServices.setServices(MockDialogDisplayer.class); } @Test public void testAskReloadDocument() { try { boolean result = AskEditorQuestions.askReloadDocument("any.txt"); fail("Expecting dialog not a result: " + result); } catch (DisplayerException ex) { assertTrue(ex.descriptor.getMessage().toString().contains("any.txt")); } } @Test public void testYesReloadDocument() { Locale.setDefault(new Locale("DA")); boolean result = AskEditorQuestions.askReloadDocument("any.txt"); assertTrue("Default answer is yes", result); } @Test public void testNoReloadDocument() { Locale.setDefault(new Locale("NO")); boolean result = AskEditorQuestions.askReloadDocument("any.txt"); assertFalse("Default answer is no", result); } private static final class DisplayerException extends RuntimeException { final NotifyDescriptor descriptor; public DisplayerException(NotifyDescriptor descriptor) { this.descriptor = descriptor; } } public static final class MockDialogDisplayer extends DialogDisplayer { public MockDialogDisplayer() { } @Override public Object notify(NotifyDescriptor nd) { throw new DisplayerException(nd); } @Override public Dialog createDialog(DialogDescriptor dd) { throw new DisplayerException(dd); } } }
true
076c6e1e4c470c4a54a7f943ee12b79a98efe05c
Java
xiaobin00/warehouse-maven
/warehouse-admin/src/main/java/light/mvc/request/ProcedurePlanGetListRequest.java
UTF-8
1,034
2.109375
2
[]
no_license
package light.mvc.request; import javax.servlet.http.HttpServletRequest; import light.mvc.utils.HttpRequestInfo; public class ProcedurePlanGetListRequest extends Request { /** * */ private static final long serialVersionUID = 1296631607672506328L; private String name; private Integer procedureId; private Integer status; @Override public void parse(HttpServletRequest request) { HttpRequestInfo info =new HttpRequestInfo(request); this.name = info.getParameter("name", ""); this.procedureId = info.getIntParameter("procedureId", 0); this.status = info.getIntParameter("status", -1); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getProcedureId() { return procedureId; } public void setProcedureId(Integer procedureId) { this.procedureId = procedureId; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } }
true
ef1ecd7d3743cb5ae0109b6f754a63cca106de72
Java
sava-ucsm/sava-AED
/OrderListLinked.java
UTF-8
1,891
3.5625
4
[]
no_license
public class OrderListLinked<T extends Comparable<T>> extends ListLinked<T> { public OrderListLinked() { super(); } public int search(T x) { Node<T> aux = this.getFirst(); int contador= 0; while(aux != null && aux.getData().compareTo(x) < 0) { aux = aux.getNext(); contador++;//Contador se incrementa hasta encontrar el elemento buscado } if(aux!=null) { if (aux.getData().equals(x)) return contador;//Retorna la posicion del elemento return -1;//Si no lo encuentre devuelve -1 } return -1; } public void insertLast(T x) { Node<T> aux = this.getFirst(); Node<T> temp = null; if(this.isEmptyList()) { this.insertFirst(x); }else if(aux.getData().compareTo(x) > 0) {//Inserta el elemento al comienzo si es menor al primer elemento de la lista enlazada this.insertFirst(x); }else { while(aux != null && aux.getData().compareTo(x) < 0) { temp = aux;//Elemento menor a x aux = aux.getNext();//Elemento mayor a x } if(aux != null && (temp.getData().compareTo(x) < 0 && aux.getData().compareTo(x)>0)) temp.setNext(new Node<T>(x,aux));//Insertamos el elemento entre su menor y su mayor de acuerdo al orden de la lista if(temp.getData().compareTo(x) < 0 && aux==null)//Para insertar el elemento al final de la lista temp.setNext(new Node<T>(x)); this.setCount(this.getCount()+1); } } public void remove(T x) { Node<T> aux = this.getFirst(); Node<T> temp = null; if(this.getFirst().getData().equals(x)) { temp = this.getFirst(); this.setFirst(this.getFirst().getNext()); temp = null; }else { while(aux.getNext()!=null && (aux.getNext().getData().compareTo(x)<0)) aux = aux.getNext(); if(aux.getNext()==null) System.out.println("No se encontro el elemento"); else { temp = aux.getNext(); aux.setNext(temp.getNext()); temp = null; } } } }
true
e7b635f82fdc93123ce10715cab0fcbcc3e620ce
Java
JBFATHR2DU/elec
/src/cn/haut/elec/web/action/ElecBugAction.java
UTF-8
6,762
2.078125
2
[]
no_license
package cn.haut.elec.web.action; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.annotation.Resource; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import cn.haut.elec.domain.ElecBug; import cn.haut.elec.domain.ElecStation; import cn.haut.elec.domain.ElecSystemDDL; import cn.haut.elec.service.IElecBugService; import cn.haut.elec.utils.AnnotationLimit; import cn.haut.elec.utils.ExcelFileGenerator; @Controller("elecBugAction") @Scope(value = "prototype") public class ElecBugAction extends BaseAction<ElecBug> { /** * */ private static final long serialVersionUID = 1L; // 注入elecBugService @Resource(name = IElecBugService.SERVICE_NAME) private IElecBugService bugService; /** * @Name: home * @Description: 跳转到运行情况 * @Author: 甘亮(作者) * @Version: V1.00 (版本号) * @Create Date: 2014-04-27(创建日期) * @Parameters: 无 * @Return: String:跳转到/WEB-INF/pages/building/siteRunIndex.jsp */ @AnnotationLimit(mid = "ai", pid = "ag") public String home() { this.initSystemDDL(); // 获取到站点的名称【不重复的】 List<String> stationNameList = List<String> stationList = bugService.findDistinctStationNameList(); request.setAttribute("stationList", stationList); // 查询所有的站点运行情况 List<ElecBug> bugList = bugService.findBugByCondition(this.getModel()); request.setAttribute("bugList", bugList); String initPage = request.getParameter("initPage"); /** * 如果initPage==null:跳转到userIndex.jsp,如果initPage==1:表示跳转到userList.jsp */ if (initPage != null && initPage.equals("1")) { return "list"; } return "home"; } /** * @Name: edit * @Description: 编辑站点bug * @Author: 甘亮(作者) * @Version: V1.00 (版本号) * @Create Date: 2014-04-27(创建日期) * @Parameters: 无 * @Return: String:跳转到/WEB-INF/pages/building/siteRunIndex.jsp */ @AnnotationLimit(mid = "ai", pid = "ag") public String edit() { this.initSystemDDL(); // 获取到站点的名称【不重复的】 List<ElecStation> stationList = bugService.findAllStation(); request.setAttribute("stationList", stationList); // 根据bugID来找到这个bug的全部信息 ElecBug bug = bugService.findBugById(this.getModel().getBugID()); request.setAttribute("bug", bug); return "edit"; } /** * @Name: update * @Description: 更新站点bug * @Author: 甘亮(作者) * @Version: V1.00 (版本号) * @Create Date: 2014-04-27(创建日期) * @Parameters: 无 * @Return: String:跳转到/WEB-INF/pages/building/siteRunIndex.jsp */ @AnnotationLimit(mid = "ai", pid = "ag") public String update() { bugService.update(this.getModel()); return "close"; } /** * @Name: showRunTime * @Description: 显示站点一共消耗了多少时间 * @Author: 甘亮(作者) * @Version: V1.00 (版本号) * @Create Date: 2014-04-28(创建日期) * @Parameters: 无 * @Return: String:跳转到/WEB-INF/pages/building/siteRunTime.jsp */ @AnnotationLimit(mid = "ai", pid = "ag") public String showRunTime() { String sumHour = bugService.findSumBugHour(); request.setAttribute("sumHour", sumHour); return "showRunTime"; } /** * @Name: exportExcel * @Description: 导出站点bug信息到excel中 使用struts2的开发【使用poi报表导出】 * @Author: 甘亮(作者) * @Version: V1.00 (版本号) * @Create Date: 2014-02-28(创建日期) * @Parameters: 无 * @Return: null */ @AnnotationLimit(mid = "ai", pid = "ag") public String exportExcel() throws Exception { ElecBug bug = this.getModel(); // 表示excel的标题 ArrayList<String> fieldName = bugService.findExcelFiledName(); // 表示excel的数据内容 ArrayList<ArrayList<String>> fieldData = bugService .findExcelFiledData(bug); ExcelFileGenerator excelFileGenerator = new ExcelFileGenerator( fieldName, fieldData); // 重置输出流,该代码可以加,如果不加,要保证resposne缓冲区中没有其他的数据,但是建议加上 response.reset(); ByteArrayOutputStream os = new ByteArrayOutputStream(); // 文件下载(添加的配置) String filename = "站点设备运行情况报表(" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ")"; filename = new String(filename.getBytes("gbk"), "iso-8859-1"); request.setAttribute("filename", filename); excelFileGenerator.expordExcel(os); // struts将excel文件写到输入流中,将输入流放置到栈顶的inputStream的属性中 byte[] buf = os.toByteArray(); ByteArrayInputStream in = new ByteArrayInputStream(buf); bug.setInputStream(in); return "success"; } /** * @Name: importPage * @Description: 进入到导入页面 * @Author: 甘亮(作者) * @Version: V1.00 (版本号) * @Create Date: 2014-04-26(创建日期) * @Parameters: 无 * @Return: null */ @AnnotationLimit(mid = "ai", pid = "ag") public String importPage() { return "importPage"; } /** * @Name: importData * @Description: 导入检测台建筑物【使用的jxl报表导入】 * @Author: 甘亮(作者) * @Version: V1.00 (版本号) * @Create Date: 2014-04-28(创建日期) * @Parameters: 无 * @Return:关闭当前页面 刷新父页面 close */ @AnnotationLimit(mid = "ai", pid = "ag") public String importData() throws IOException { List<String> errorlist = bugService .importData(this.getModel(), request); if (errorlist != null && errorlist.size() > 0) { request.setAttribute("errorList", errorlist); return "importPage"; } return "close"; } /** * @Name: report * @Description: jfreeChart统计建筑物数量 * @Author: 甘亮(作者) * @Version: V1.00 (版本号) * @Create Date: 2014-04-26(创建日期) * @Parameters: 无 * @Return:/WEB-INF/page/system/buildingReport.jsp */ // 初始化数据字典的内容 public void initSystemDDL() { // 所属单位 List<ElecSystemDDL> jctList = bugService .findSystemDDLListByKeyword("所属单位"); request.setAttribute("jctList", jctList); // 故障类型 List<ElecSystemDDL> bugTypeList = bugService .findSystemDDLListByKeyword("故障类型"); request.setAttribute("bugTypeList", bugTypeList); // 站点类别 List<ElecSystemDDL> stationTypeList = bugService .findSystemDDLListByKeyword("站点类别"); request.setAttribute("stationTypeList", stationTypeList); } }
true
ecc25770b5c691ddf73470e29eb1d661c8f87553
Java
zhu-ch/Device-Management-Sub-System
/src/main/java/com/management/admin/modules/tool/entity/ImportExcel.java
UTF-8
678
1.867188
2
[]
no_license
package com.management.admin.modules.tool.entity; import com.management.admin.common.persistence.DataEntity; import lombok.Data; import java.util.List; @Data public class ImportExcel extends DataEntity<ImportExcel> { private String templateName; // 模板名(导入方案名) private String tableName; // 目标表名 private String filePath; // excel模板文件的名字(默认存放src/main/webapp/file/template) private String excelDataName; //数据excel文件名 private String typeId; //模板所属类型的uuid private List<ColumnMapField> columnMapFieldList; // excel列到table字段的映射(以field为基准) }
true
34ed9ea95125e47562749489f593e498634ab138
Java
jcwal/hcrm-webapp
/src/test/java/org/macula/extension/upload/test/UploadFileTest.java
UTF-8
2,067
2.140625
2
[]
no_license
package org.macula.extension.upload.test; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import junit.framework.TestCase; import org.apache.commons.collections.MapUtils; import org.junit.Test; import org.macula.extension.upload.UploadEnhanceOpenApiTemplate; import org.macula.plugins.esb.openapi.vo.ExecuteResponse; import com.fasterxml.jackson.core.type.TypeReference; public class UploadFileTest extends TestCase { private final static String UPLOAD_FILE_URL = "/gbss-esb/admin/gbss-esb-dealer/qualityReport/upload"; @Test public void testUpload() throws IOException { UploadEnhanceOpenApiTemplate template = new UploadEnhanceOpenApiTemplate(); template.setAppId("gbss-trade"); template.setAppSecret("gbss-trade"); template.setEndpoint("https://gbssdev.infinitus.com.cn"); String filePath = "d:\\temp\\key.txt"; File file = new File(filePath); Map<String, Object> postValues = new HashMap<String, Object>(); postValues.put("opAppNo", "123"); postValues.put("certDataType", "P"); postValues.put("allowDownload", "true"); postValues.put("effectiveDate", "2015-07-07"); postValues.put("inactiveDate", "2015-08-07"); postValues.put("uploadUserName", "220029838"); postValues.put("uploadDateTime", "2015-07-07"); postValues.put("comments", "Comments"); Map<String, File> files = new HashMap<String, File>(); files.put("byteFile", file); ExecuteResponse<Map<String, Object>> result = template.postForObject(UPLOAD_FILE_URL, null, null, new TypeReference<ExecuteResponse<Map<String, Object>>>() { }, postValues, files); System.out.println("Success: " + result.isSuccess()); Map<String, Object> returnObject = result.getReturnObject(); System.out.println("Result: " + returnObject); if (MapUtils.isEmpty(returnObject)) { System.out.println("Upload completed success."); } else { for (Map.Entry<String, Object> entry : returnObject.entrySet()) { System.out.println("Upload error: " + entry.getKey() + "->" + entry.getValue()); } } } }
true
ff1eb2c1586cf7377ea9f007c15f1cd655a528c6
Java
yue907/simple-spring
/src/main/java/com/guge/spring/beans/factory/DefaultBeanFactory.java
UTF-8
4,147
2.53125
3
[]
no_license
package com.guge.spring.beans.factory; import com.guge.spring.beans.context.AnnotationUtil; import com.guge.spring.beans.context.PropertyUtil; import com.guge.spring.beans.entity.Bean; import com.guge.spring.beans.entity.Beans; import com.guge.spring.beans.entity.Property; import com.guge.spring.beans.entity.Scan; import com.guge.spring.beans.support.CheckUtil; import com.guge.spring.beans.support.BeanDefinitionRegistry; import com.guge.spring.beans.util.ReflectUtil; import com.guge.spring.beans.util.StringUtil; import org.apache.commons.collections.CollectionUtils; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.ConcurrentHashMap; /** * Created by google on 17/4/15. */ public class DefaultBeanFactory extends AbstractBeanFactory implements BeanDefinitionRegistry { Set<String> beanNames = new HashSet<String>(); private Map<String,Object> singletonBeans = new ConcurrentHashMap<String, Object>(); private Map<String,Bean> beanDefinitionMap = new ConcurrentHashMap<String, Bean>(); @Override Object doGetBean(String name) throws Exception{ if(singletonBeans.containsKey(name)){ return singletonBeans.get(name); } return getBeanFromDefinition(name); } @Override public void registryBeanDefinition(Beans beans) throws Exception{ CheckUtil.checkNullArgs("beans can not bu null", beans); List<Bean> beanList = beans.getBeans(); List<Scan> scanList = beans.getScans(); if(CollectionUtils.isNotEmpty(beanList)){ for(Bean bean : beanList){ registryBeanDefinition(bean.getId(),bean); } } if(CollectionUtils.isNotEmpty(scanList)){ for(Scan scan : scanList){ AnnotationUtil.injectAnnotation(scan.getPackageName(),this); } } } @Override public void registryBeanDefinition(String beanName, Bean bean) { CheckUtil.checkBlankStr("beanName can not be blank", beanName); CheckUtil.checkNullArgs("bean definition can not be null",bean); if(beanDefinitionMap.containsKey(beanName)){ throw new IllegalArgumentException("beanName has existed!"); } beanDefinitionMap.put(beanName, bean); beanNames.add(beanName); } private Object getBeanFromDefinition(String name) throws Exception{ Bean bean = beanDefinitionMap.get(name); if(null == bean){ return null; } Class clazz = Class.forName(bean.getClassName()); singletonBeans.put(bean.getId(), clazz.newInstance()); injectDependences(name, bean.getProps()); return singletonBeans.get(name); } private void injectDependences(String name,List<Property> properties) throws Exception{ if(CollectionUtils.isEmpty(properties)){ return; } Object item = singletonBeans.get(name); if(null == item){ return; } for(Property property : properties){ String propertyName = property.getName(); Field field = ReflectUtil.getDeclaredField(item, propertyName); String methodName = StringUtil.setMethodName(propertyName); Method m = ReflectUtil.getDeclaredMethod(item, methodName, field.getType()); if (null != property.getValue()) { // 其实这里应该尝试进行 prop.getValue() 到 field.getType()的转换 m.invoke(item, PropertyUtil.getPorperty(field.getType(),property.getValue())); } if (null != property.getRef()) { Object refObj = getBean(property.getRef()); m.invoke(item, refObj); } } } public void destoryBeans(){ singletonBeans.clear(); beanDefinitionMap.clear(); beanNames.clear(); } public void preInstantiateSingletons() throws Exception{ if(beanNames.isEmpty()){ return; } for(String beanName : beanNames){ getBean(beanName); } } }
true
ea19fc0fe2dd53bb20e396a38b37913cd65e48ec
Java
13jaque/javaBasico
/curso-java/src/com/cursojava/exercicios/aula13/Exercicio10.java
UTF-8
631
3.796875
4
[]
no_license
package com.cursojava.exercicios.aula13; import java.util.Scanner; public class Exercicio10 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); //(20 °C × 9/5) + 32 = 68 °F System.out.println("Digite a temperatura em Graus Celsius: "); int celsius = scan.nextInt(); int fahrenheit = (celsius * 9/5) + 32; System.out.println("Temperatura em Fahrenheit é: " + fahrenheit + "°F"); //sem Scanner /*int celsius = 20; int fahrenheit = (celsius * 9/5) + 32; System.out.println(fahrenheit + "°F");*/ } }
true
7378722b98f21454f02ea220574afcaa67041951
Java
cumtwyt/GradleDemo
/src/main/java/mj/mapper/EnrollMapper.java
UTF-8
505
2
2
[]
no_license
package mj.mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import mj.domain.User; public interface EnrollMapper { @Select("insert into tb_user values(#{id},#{name},#{pwd},#{sex},#{age},#{tel},#{que},#{anw})") User insertuser(@Param("id")String id,@Param("name")String name, @Param("pwd") String pwd,@Param("sex") String sex, @Param("age") String age,@Param("tel") String tel,@Param("que") String que,@Param("anw") String anw); }
true
29ccac0857047d62fe27c70a20239a4dc010f5c4
Java
GabrielNourrit/Framework_JAVA
/RMIv3/rmiserveur/src/BaseDeDonnee/connexion/ConnexionBase.java
UTF-8
208
2.078125
2
[]
no_license
package BaseDeDonnee.connexion; public abstract class ConnexionBase { protected String link_properties; protected ConnexionBase(String link_properties){ this.link_properties = link_properties; } }
true
79c5fbb8439fbc0e3c7d3a4deeec78561f36f75d
Java
reverseengineeringer/me.lyft.android
/src/com/facebook/internal/PlatformServiceClient$1.java
UTF-8
466
1.5
2
[]
no_license
package com.facebook.internal; import android.os.Handler; import android.os.Message; class PlatformServiceClient$1 extends Handler { PlatformServiceClient$1(PlatformServiceClient paramPlatformServiceClient) {} public void handleMessage(Message paramMessage) { this$0.handleMessage(paramMessage); } } /* Location: * Qualified Name: com.facebook.internal.PlatformServiceClient.1 * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
c79be1b9ed6bbc5fcf8a62cabf012b783ed0cf82
Java
yurchello/design-patterns
/proxy-pattern/src/main/java/example_1/Main.java
UTF-8
393
2.375
2
[]
no_license
package example_1; /** * Created by Mezentsev.Y on 2/26/2016. */ public class Main { public static void main(String[] args) { User user = new User("admin", "admin"); FolderProxy proxy = new FolderProxy(user); proxy.doAction(); User user2 = new User("aaa", "ssss"); FolderProxy proxy2 = new FolderProxy(user2); proxy2.doAction(); } }
true
2b039a380cee2b25b0b1c6cd8c3e31546c669f0c
Java
ResurrectionRemix/android_vendor_qcom_opensource_packages_apps_Bluetooth
/tests/unit/src/com/android/bluetooth/mapclient/MapClientStateMachineTest.java
UTF-8
8,609
1.585938
2
[]
no_license
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.bluetooth.mapclient; import static org.mockito.Mockito.*; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothProfile; import android.bluetooth.SdpMasRecord; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import androidx.test.InstrumentationRegistry; import androidx.test.filters.MediumTest; import androidx.test.runner.AndroidJUnit4; import com.android.bluetooth.R; import com.android.bluetooth.btservice.ProfileService; import org.junit.After; import org.junit.Assert; import org.junit.Assume; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @MediumTest @RunWith(AndroidJUnit4.class) public class MapClientStateMachineTest { private static final String TAG = "MapStateMachineTest"; private static final int ASYNC_CALL_TIMEOUT_MILLIS = 100; private BluetoothAdapter mAdapter; private MceStateMachine mMceStateMachine = null; private BluetoothDevice mTestDevice; private Context mTargetContext; private Handler mHandler; private ArgumentCaptor<Intent> mIntentArgument = ArgumentCaptor.forClass(Intent.class); @Mock private MapClientService mMockMapClientService; @Mock private MasClient mMockMasClient; @Before public void setUp() { MockitoAnnotations.initMocks(this); mTargetContext = InstrumentationRegistry.getTargetContext(); Assume.assumeTrue("Ignore test when MapClientService is not enabled", mTargetContext.getResources().getBoolean(R.bool.profile_supported_mapmce)); doReturn(mTargetContext.getResources()).when(mMockMapClientService).getResources(); // This line must be called to make sure relevant objects are initialized properly mAdapter = BluetoothAdapter.getDefaultAdapter(); // Get a device for testing mTestDevice = mAdapter.getRemoteDevice("00:01:02:03:04:05"); when(mMockMasClient.makeRequest(any(Request.class))).thenReturn(true); mMceStateMachine = new MceStateMachine(mMockMapClientService, mTestDevice, mMockMasClient); Assert.assertNotNull(mMceStateMachine); if (Looper.myLooper() == null) { Looper.prepare(); } mHandler = new Handler(); } @After public void tearDown() { if (!mTargetContext.getResources().getBoolean(R.bool.profile_supported_mapmce)) { return; } if (mMceStateMachine != null) { mMceStateMachine.doQuit(); } } /** * Test that default state is STATE_CONNECTING */ @Test public void testDefaultConnectingState() { Log.i(TAG, "in testDefaultConnectingState"); Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, mMceStateMachine.getState()); } /** * Test transition from * STATE_CONNECTING --> (receive MSG_MAS_DISCONNECTED) --> STATE_DISCONNECTED */ @Test public void testStateTransitionFromConnectingToDisconnected() { Log.i(TAG, "in testStateTransitionFromConnectingToDisconnected"); setupSdpRecordReceipt(); Message msg = Message.obtain(mHandler, MceStateMachine.MSG_MAS_DISCONNECTED); mMceStateMachine.sendMessage(msg); // Wait until the message is processed and a broadcast request is sent to // to MapClientService to change // state from STATE_CONNECTING to STATE_DISCONNECTED verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)).sendBroadcast( mIntentArgument.capture(), eq(ProfileService.BLUETOOTH_PERM)); Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED, mMceStateMachine.getState()); } /** * Test transition from STATE_CONNECTING --> (receive MSG_MAS_CONNECTED) --> STATE_CONNECTED */ @Test public void testStateTransitionFromConnectingToConnected() { Log.i(TAG, "in testStateTransitionFromConnectingToConnected"); setupSdpRecordReceipt(); Message msg = Message.obtain(mHandler, MceStateMachine.MSG_MAS_CONNECTED); mMceStateMachine.sendMessage(msg); // Wait until the message is processed and a broadcast request is sent to // to MapClientService to change // state from STATE_CONNECTING to STATE_CONNECTED verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)).sendBroadcast( mIntentArgument.capture(), eq(ProfileService.BLUETOOTH_PERM)); Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, mMceStateMachine.getState()); } /** * Test transition from STATE_CONNECTING --> (receive MSG_MAS_CONNECTED) --> STATE_CONNECTED * --> (receive MSG_MAS_DISCONNECTED) --> STATE_DISCONNECTED */ @Test public void testStateTransitionFromConnectedWithMasDisconnected() { Log.i(TAG, "in testStateTransitionFromConnectedWithMasDisconnected"); setupSdpRecordReceipt(); Message msg = Message.obtain(mHandler, MceStateMachine.MSG_MAS_CONNECTED); mMceStateMachine.sendMessage(msg); // Wait until the message is processed and a broadcast request is sent to // to MapClientService to change // state from STATE_CONNECTING to STATE_CONNECTED verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)).sendBroadcast( mIntentArgument.capture(), eq(ProfileService.BLUETOOTH_PERM)); Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, mMceStateMachine.getState()); msg = Message.obtain(mHandler, MceStateMachine.MSG_MAS_DISCONNECTED); mMceStateMachine.sendMessage(msg); verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(4)).sendBroadcast( mIntentArgument.capture(), eq(ProfileService.BLUETOOTH_PERM)); Assert.assertEquals(BluetoothProfile.STATE_DISCONNECTED, mMceStateMachine.getState()); } /** * Test receiving an empty event report */ @Test public void testReceiveEmptyEvent() { setupSdpRecordReceipt(); Message msg = Message.obtain(mHandler, MceStateMachine.MSG_MAS_CONNECTED); mMceStateMachine.sendMessage(msg); // Wait until the message is processed and a broadcast request is sent to // to MapClientService to change // state from STATE_CONNECTING to STATE_CONNECTED verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(2)).sendBroadcast( mIntentArgument.capture(), eq(ProfileService.BLUETOOTH_PERM)); Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, mMceStateMachine.getState()); // Send an empty notification event, verify the mMceStateMachine is still connected Message notification = Message.obtain(mHandler, MceStateMachine.MSG_NOTIFICATION); mMceStateMachine.getCurrentState().processMessage(msg); Assert.assertEquals(BluetoothProfile.STATE_CONNECTED, mMceStateMachine.getState()); } private void setupSdpRecordReceipt() { // Perform first part of MAP connection logic. verify(mMockMapClientService, timeout(ASYNC_CALL_TIMEOUT_MILLIS).times(1)).sendBroadcast( mIntentArgument.capture(), eq(ProfileService.BLUETOOTH_PERM)); Assert.assertEquals(BluetoothProfile.STATE_CONNECTING, mMceStateMachine.getState()); // Setup receipt of SDP record SdpMasRecord record = new SdpMasRecord(1, 1, 1, 1, 1, 1, "MasRecord"); Message msg = Message.obtain(mHandler, MceStateMachine.MSG_MAS_SDP_DONE, record); mMceStateMachine.sendMessage(msg); } }
true
108acfe406a26683ea2a32fc3226b41728b6f5ac
Java
antoniomilla/hackaton-comics
/Acme-Comics/src/main/java/domain/Volume.java
UTF-8
3,854
2
2
[]
no_license
package domain; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.Entity; import javax.persistence.Index; import javax.persistence.Lob; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.PreRemove; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.Valid; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Past; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.URL; import org.springframework.format.annotation.DateTimeFormat; import validators.NullOrNotBlank; import validators.PastOrPresent; @Entity @Access(AccessType.PROPERTY) @Table(indexes = { @Index(columnList = "comic_id, orderNumber, name"), // findByComicOrderByOrderNumberAscNameAsc @Index(columnList = "author_id, releaseDate"), // findVolumesAndUserComicsForAuthorAndUserOrderByReleaseDateDesc }) public class Volume extends DomainEntity { private int orderNumber; private String name; private Date releaseDate; private Integer chapterCount; private String description; private String image; private Comic comic; private Author author; private List<Comment> comments = new ArrayList<>(); private List<UserComic> userComics = new ArrayList<>(); public Volume() {} public Volume(Comic comic) { this.comic = comic; } public int getOrderNumber() { return this.orderNumber; } public void setOrderNumber(final int orderNumber) { this.orderNumber = orderNumber; } @NotBlank public String getName() { return this.name; } public void setName(final String name) { this.name = name; } @PastOrPresent @Temporal(TemporalType.DATE) @DateTimeFormat(pattern = "dd/MM/yyyy") @NotNull public Date getReleaseDate() { return this.releaseDate; } public void setReleaseDate(final Date releaseDate) { this.releaseDate = releaseDate; } @Min(1) public Integer getChapterCount() { return this.chapterCount; } public void setChapterCount(Integer chapterCount) { this.chapterCount = chapterCount; } @NullOrNotBlank @Lob public String getDescription() { return this.description; } public void setDescription(final String description) { this.description = description; } @URL @NullOrNotBlank public String getImage() { return this.image; } public void setImage(final String image) { this.image = image; } @NotNull @ManyToOne(optional = false) public Comic getComic() { return this.comic; } public void setComic(final Comic comic) { this.comic = comic; } @NotNull @ManyToOne(optional = false) public Author getAuthor() { return this.author; } public void setAuthor(final Author author) { this.author = author; } @NotNull @OneToMany(mappedBy = "volume") @Cascade(CascadeType.DELETE) public List<Comment> getComments() { return this.comments; } public void setComments(final List<Comment> comments) { this.comments = comments; } @NotNull @ManyToMany(mappedBy = "readVolumes") public List<UserComic> getUserComics() { return this.userComics; } public void setUserComics(final List<UserComic> userComics) { this.userComics = userComics; } @PreRemove public void onRemoval() { // Dissociate with volume with UserComics. for (UserComic userComic : getUserComics()) { userComic.getReadVolumes().remove(this); userComic.setReadVolumeCount(userComic.getReadVolumes().size()); } } }
true
c3def75f166c860887c8ec41bba6904be1194ace
Java
gl-porytskyi/BusNotifier
/app/src/main/java/oporytskyi/busnotifier/manager/MessageManager.java
UTF-8
1,761
2.28125
2
[]
no_license
package oporytskyi.busnotifier.manager; import static android.content.Context.NOTIFICATION_SERVICE; import android.app.Application; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.support.v4.app.NotificationCompat; import oporytskyi.busnotifier.R; import oporytskyi.busnotifier.activity.MainActivity; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; /** * @author Oleksandr Porytskyi */ public class MessageManager { private final int mNotificationId = 1; private Application application; private NotificationManager notificationManager; public MessageManager(Application application) { this.application = application; notificationManager = (NotificationManager) application.getSystemService(NOTIFICATION_SERVICE); } public void showNotification(DateTime dateTime, String directionName) { DateTimeFormatter dateTimeFormatter = DateTimeFormat.shortTime(); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(application) .setSmallIcon(R.drawable.ic_dialog_time) .setContentTitle(directionName) .setContentText("Departure at " + dateTime.toString(dateTimeFormatter)); Intent intent = new Intent(application, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(application, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(pendingIntent); mBuilder.setOngoing(true); notificationManager.notify(mNotificationId, mBuilder.build()); } public void remove() { notificationManager.cancel(mNotificationId); } }
true
7e7d1f9b5723371b5beaa4001a15686da18f15fb
Java
lukasthekid/horseapplication
/Horse Web Application/backend/src/main/java/at/ac/tuwien/sepm/assignment/individual/endpoint/SportEndpoint.java
UTF-8
3,423
2.375
2
[]
no_license
package at.ac.tuwien.sepm.assignment.individual.endpoint; import at.ac.tuwien.sepm.assignment.individual.endpoint.dto.SportDto; import at.ac.tuwien.sepm.assignment.individual.endpoint.mapper.SportMapper; import at.ac.tuwien.sepm.assignment.individual.entity.Sport; import at.ac.tuwien.sepm.assignment.individual.exception.NotFoundException; import at.ac.tuwien.sepm.assignment.individual.exception.ServiceException; import at.ac.tuwien.sepm.assignment.individual.service.SportService; import java.lang.invoke.MethodHandles; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; @RestController @RequestMapping(SportEndpoint.BASE_URL) public class SportEndpoint { static final String BASE_URL = "/sports"; private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private final SportService sportService; private final SportMapper sportMapper; @Autowired public SportEndpoint(SportService sportService, SportMapper sportMapper) { this.sportService = sportService; this.sportMapper = sportMapper; } @GetMapping(value = "/{id}") public SportDto getOneById(@PathVariable("id") Long id) { LOGGER.info("GET " + BASE_URL + "/{}", id); try { return sportMapper.entityToDto(sportService.getOneById(id)); } catch (NotFoundException e) { LOGGER.error(e.getMessage()); throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Error during reading sport", e); } } @GetMapping("/all") public ResponseEntity<List<SportDto>> findAllSports() { LOGGER.info("GET " + BASE_URL + "/all"); try { List<Sport> sports = sportService.getAllSports(); List<SportDto> sportsDto = sportMapper.entityListToDtoList(sports); return new ResponseEntity<>(sportsDto, HttpStatus.OK); } catch (NotFoundException e) { LOGGER.error(e.getMessage()); throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Error during reading sports", e); } } @PostMapping("/add") public ResponseEntity<SportDto> saveSport(@RequestBody SportDto sportDTO) { LOGGER.info("POST " + BASE_URL + "/add {}", sportDTO); try { Sport sport = sportMapper.dtoToEntity(sportDTO); return new ResponseEntity<>(sportMapper.entityToDto(sportService.saveSport(sport)), HttpStatus.OK); } catch (ServiceException e) { LOGGER.error(e.getMessage()); throw new ResponseStatusException(HttpStatus.CONFLICT, "Error during saving sport", e); } } @DeleteMapping("/delete/{id}") public ResponseEntity<?> deleteSportById(@PathVariable("id") Long id) { LOGGER.info("DELETE " + BASE_URL + "/delete/{}", id); try { sportService.deleteSportById(id); return new ResponseEntity<>(HttpStatus.OK); } catch (ServiceException e) { LOGGER.error(e.getMessage()); throw new ResponseStatusException(HttpStatus.CONFLICT, "Error during deleting sport", e); } } }
true
f0335a31c27d029bc56fdb4dc55e403f3efa4669
Java
PujolCity/To-Do-List
/BackEnd/ToDoList/src/main/java/com/todolist/service/impl/FolderServiceImpl.java
UTF-8
628
2
2
[]
no_license
package com.todolist.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Service; import com.todolist.commons.GenericServiceImpl; import com.todolist.dao.api.FolderDaoApi; import com.todolist.model.Folder; import com.todolist.service.api.FolderServiceApi; @Service public class FolderServiceImpl extends GenericServiceImpl<Folder, Long> implements FolderServiceApi{ @Autowired private FolderDaoApi folderDaoApi; @Override public CrudRepository<Folder, Long> getDao() { return folderDaoApi; } }
true
14a1c9dda3c9732f913bc9bff552d6e17c7da10c
Java
skoogiz/code-n-stuff
/samples/java/tic-tac-toe/src/main/java/view/MarkerButton.java
UTF-8
351
2.453125
2
[]
no_license
package view; import javax.swing.JButton; public class MarkerButton extends JButton { private static final long serialVersionUID = 1L; private int axisX; private int axisY; public MarkerButton(int x, int y) { this.axisX = x; this.axisY = y; } public int getAxisX() { return axisX; } public int getAxisY() { return axisY; } }
true
98e2b080fecd542de82028b6196fb090baf77a4e
Java
AY2021S1-CS2113T-T12-2/tp
/src/main/java/seedu/duke/Parser.java
UTF-8
3,924
2.90625
3
[]
no_license
package seedu.duke; import seedu.duke.command.AddCommand; import seedu.duke.command.AddInfoCommand; import seedu.duke.command.Command; import seedu.duke.command.CountdownCommand; import seedu.duke.command.DeleteCommand; import seedu.duke.command.DeleteInfoCommand; import seedu.duke.command.DoneCommand; import seedu.duke.command.ExitCommand; import seedu.duke.command.FindCommand; import seedu.duke.command.HelpCommand; import seedu.duke.command.PrintEventsCommand; import seedu.duke.command.PrintPriorityCommand; import seedu.duke.command.PrintProgressCommand; import seedu.duke.command.PrintSuggestionCommand; import seedu.duke.command.PrintTasksCommand; import seedu.duke.command.PrintTimelineCommand; import seedu.duke.command.PrioritizeCommand; import seedu.duke.command.ViewInfoCommand; /** * Determines the type of command input by the user and calls for the respective command function. */ public class Parser { public static final String COMMAND_DELETE = "-"; public static final String COMMAND_DONE = "done"; public static final String COMMAND_EXIT = "bye"; public static final String COMMAND_FIND = "/f"; public static final String COMMAND_HELP = "help"; public static final String COMMAND_PRINT_EVENTS = "print events"; public static final String COMMAND_PRINT_TASKS = "print tasks"; public static final String COMMAND_PRINT_TIMELINE = "print timeline"; public static final String COMMAND_SHOW_PROGRESS = "print progress"; public static final String COMMAND_SHOW_COUNTDOWN = "countdown"; public static final String COMMAND_ADD_INFO = "/a"; public static final String COMMAND_VIEW_INFO = "/v"; public static final String COMMAND_DELETE_INFO = "/-"; public static final String COMMAND_PRIORITIZE = "*"; public static final String COMMAND_PRINT_PRIORITY = "print *"; public static final String COMMAND_PRINT_SUGGESTION = "suggestion"; public static Command handleUserInput(String userInput) { if (userInput.equals(COMMAND_EXIT)) { return new ExitCommand(userInput); } else if (userInput.equals(COMMAND_HELP)) { return new HelpCommand(userInput); } else if (userInput.equals(COMMAND_PRINT_TASKS)) { return new PrintTasksCommand(userInput); } else if (userInput.equals(COMMAND_PRINT_EVENTS)) { return new PrintEventsCommand(userInput); } else if (userInput.startsWith(COMMAND_PRINT_TIMELINE)) { return new PrintTimelineCommand(userInput); } else if (userInput.startsWith(COMMAND_DONE)) { return new DoneCommand(userInput); } else if (userInput.startsWith(COMMAND_DELETE)) { return new DeleteCommand(userInput); } else if (userInput.startsWith(COMMAND_FIND)) { return new FindCommand(userInput); } else if (userInput.startsWith(COMMAND_ADD_INFO)) { return new AddInfoCommand(userInput); } else if (userInput.startsWith(COMMAND_VIEW_INFO)) { return new ViewInfoCommand(userInput); } else if (userInput.startsWith(COMMAND_DELETE_INFO)) { return new DeleteInfoCommand(userInput); } else if (userInput.equals(COMMAND_SHOW_PROGRESS)) { return new PrintProgressCommand(userInput); } else if (userInput.startsWith(COMMAND_SHOW_COUNTDOWN)) { return new CountdownCommand(userInput); } else if (userInput.startsWith((COMMAND_PRIORITIZE))) { return new PrioritizeCommand(userInput); } else if (userInput.equals(COMMAND_PRINT_PRIORITY)) { return new PrintPriorityCommand(userInput); } else if (userInput.equals(COMMAND_PRINT_SUGGESTION)) { return new PrintSuggestionCommand(userInput); } else { /** An invalid command is catered for in AddCommand */ return new AddCommand(userInput); } } }
true
28f9a86f09142594518cfa4c9ea869f084927427
Java
xNauman/Java
/Code/Demo 250909/PBSS-NAV-RMI/src/RMI/SCHClientForNavImpl.java
UTF-8
6,832
2.203125
2
[]
no_license
/** * */ package RMI; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.rmi.NotBoundException; import java.rmi.RMISecurityManager; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.Scanner; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.BadLocationException; //import chat.gui.client.SCHClientForNavImpl; /** * @author Raja Noman Saeed * */ public class SCHClientForNavImpl { Registry mRemoteRegistry; protected SCHServer mServerObject; private String mServerAddress = "127.0.0.1"; private String mServerPort = "1234"; private String mConsoleString = ""; private String mServerMessage = ""; Scanner mCInput =null; private JTextArea mConvoArea = null; private JTextField mFieldForMessage = null; private JButton mSendButton = null; private JFrame mMainFrame; private JPanel mSouthPane = null; private JPanel mContentPane =null; private SCHClientForNavImpl mClientRMIInfo = null; // private String mEventID = ""; private String mMessageToRMI = " "; //private String mServerAddress = "127.0.0.1"; //private String mServerPort = "1234"; //private String mConsoleString = ""; //private String mServerMessage = ""; public void ChatWindowInterface() { /** * setting up main frame. */ mMainFrame = new JFrame(); mMainFrame.setTitle("Chat Window"); mMainFrame.setSize(new Dimension(400,600)); mMainFrame.setResizable(false); mContentPane = new JPanel(); mContentPane.setSize(250, 200); mSouthPane = new JPanel(); mConvoArea = new JTextArea(); mConvoArea.setPreferredSize(new Dimension(300,300)); mConvoArea.setEditable(false); /** * initialize button */ mFieldForMessage = new JTextField(20); mFieldForMessage. getDocument(). addDocumentListener( new DocumentListener(){ public void changedUpdate(DocumentEvent de) { // TODO Auto-generated method stub int vTotalChar = de.getDocument().getLength(); String vStr=""; try { vStr = de.getDocument().getText(0, vTotalChar); mMessageToRMI = vStr; System.out.println(vStr); } catch (BadLocationException e1) { e1.printStackTrace(); } } //@Override public void insertUpdate(DocumentEvent de) { // TODO Auto-generated method stub int vTotalChar = de.getDocument().getLength(); String vStr=""; //System.out.println(vStr); try { vStr = de.getDocument().getText(0, vTotalChar); //System.out.println(vStr); mMessageToRMI = vStr; } catch (BadLocationException e1) { e1.printStackTrace(); } } //@Override public void removeUpdate(DocumentEvent de) { // TODO Auto-generated method stub int vTotalChar = de.getDocument().getLength(); String vStr=""; //System.out.println(vStr); try { vStr = de.getDocument().getText(0, vTotalChar); //System.out.println(vStr); mMessageToRMI = vStr; } catch (BadLocationException e1) { e1.printStackTrace(); } } } ); //initialize button. mSendButton = new JButton(); mSendButton.setText("Send"); mSendButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent e){ //System.out.println("Send Button is clicked:"+ mMessageToRMI); //mClientRMIInfo.setMessage(mMessageToRMI); String vResponce =""; try { TalkToServer(); } catch (RemoteException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (NotBoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } mConvoArea.append("\n Client>"+mServerMessage); mFieldForMessage.setText(""); mFieldForMessage.requestFocusInWindow(); } } ); //setting up the layout of the south panel components. mSouthPane.setLayout( new BorderLayout() ); mSouthPane.add( mFieldForMessage,BorderLayout.CENTER ); mSouthPane.add( mSendButton,BorderLayout.EAST); //adding text area. mContentPane.add(mConvoArea,BorderLayout.CENTER); //adding South Panel. mContentPane.add(mSouthPane,BorderLayout.SOUTH); //set the content pane for main frame. mMainFrame.setContentPane(mContentPane); mMainFrame.setDefaultCloseOperation(mMainFrame.EXIT_ON_CLOSE); mMainFrame.setVisible(true); this.mFieldForMessage.requestFocusInWindow(); } /** * @param args */ private SCHClientForNavImpl() throws RemoteException { super(); /** * get registry location * */ mCInput = new Scanner(System.in); try{ System.out.println("Registering server"); //finding the registry. mRemoteRegistry = LocateRegistry.getRegistry( mServerAddress, (new Integer(mServerPort).intValue())); System.out.println("Creating Remote-Object"); /** * get the object from the remote-registry */ mServerObject = (SCHServer)mRemoteRegistry.lookup("SCHServer"); }catch(Exception e){ e.printStackTrace(); } this.ChatWindowInterface(); /*try{ TalkToServer(); }catch(Exception e){ e.printStackTrace(); }*/ } public void TalkToServer()throws RemoteException, NotBoundException{ try{ //read text of console. System.out.println("Please Type Client>"); mConsoleString = mCInput.nextLine(); //RMI call and get the response. mServerMessage = mServerObject.sendToNAV( this.mMessageToRMI); System.out.println( "Server>"+ mServerMessage); }catch(RemoteException e){ e.printStackTrace(); } /* try{ TalkToServer(); }catch(Exception e){ e.printStackTrace(); } */ } public static void main(String[] srgs){ try{ SCHClientForNavImpl vClient = new SCHClientForNavImpl(); }catch(Exception e){ } } }
true
6f565a13e9a6379d531576fb86febd65d8def0f9
Java
caixin07/xian52
/xian52/src/main/java/com/xian52/service/PicService.java
UTF-8
420
1.679688
2
[]
no_license
package com.xian52.service; import java.util.List; import org.apache.ibatis.annotations.Lang; import com.xian52.domain.Image; import com.xian52.domain.News; import com.xian52.domain.Pic; public interface PicService { public void insert(Pic pic); public Pic getOneByUrl(Pic pic); public List<Pic> getPicList(); public List<Pic> getChildPicList(Pic pic); public List<Pic> getPicListRandom(); }
true
873c5cde128d790d0686aab184e83e6767ee4238
Java
joaojomoura/UA
/2_ano/P3/feito por outros/Prog3-master/A3 - Herança e Polimorfismo/aula3/e2/Ponto.java
UTF-8
716
3.21875
3
[ "MIT" ]
permissive
package aula3.e2; public class Ponto { private int xx; private int yy; public Ponto(int x, int y) { xx = x; yy = y; } public Ponto() { this(0, 0); } @Override public String toString() { return "(" + xx + ", " + yy + ")"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + xx; result = prime * result + yy; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Ponto other = (Ponto) obj; if (xx != other.xx) return false; if (yy != other.yy) return false; return true; } }
true
4c3927f40ae5bd6f57e77b86fc1a24fb311f87b1
Java
Chrishayes94/JEngine
/JRPG/src/core/io/SaveGameState.java
UTF-8
1,181
3.09375
3
[]
no_license
package core.io; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import core.player.Player; public class SaveGameState { public static void save(Player p) throws IOException { String saveLocation = "JRPG/saves/" + p.getName() + ".character"; // Create the list string of all possible save List<String> saveInformation = new ArrayList<String>(); /// Player Information saveInformation.add("[PLAYER]"); saveInformation.add("name=" + p.getName()); saveInformation.add("x=" + p.getX()); saveInformation.add("y=" + p.getY()); // Create a binary file (encoded) List<byte[]> bytes = getBytes(saveInformation); FileOutputStream out = new FileOutputStream(saveLocation); for (byte[] byteStr : bytes) { out.write(byteStr); } out.close(); } protected static List<byte[]> getBytes(List<String> listStr) { List<byte[]> bytes = new ArrayList<byte[]>(); for (String str : listStr) { byte[] bytesStr = new byte[str.length()]; int index = 0; for (char c : str.toCharArray()) { bytesStr[index] = (byte)c; } bytes.add(bytesStr); } return bytes; } }
true
0fafd5f21992b0a21617223bf6941b5d63524ae4
Java
Renato-Sampaio/java-basico
/java-basico/src/exercicios/Exercicio49.java
IBM852
1,116
3.421875
3
[]
no_license
package exercicios; import javax.swing.JOptionPane; /** * LER 3 VALORES E MOSTRAR O MENOR DELES * @author Renato Sampaio * @SINCE 09/02/2021 */ public class Exercicio49 { /** * Mtodo principal pra rodar a classe */ public static void main(String[] args) { //criando variaveis double valor1,valor2,valor3; JOptionPane.showInternalMessageDialog(null,"INSIRA 3 VALORES E TE MOSTRAREI O MENOR ENTRE ELES "); valor1= Double.parseDouble(JOptionPane.showInputDialog("INSIRA O 1 VALOR")); valor2= Double.parseDouble(JOptionPane.showInputDialog("INSIRA O 2 VALOR")); valor3= Double.parseDouble(JOptionPane.showInputDialog("INSIRA O 3 VALOR")); //verificando saldo atual e apresentando em tela if ((valor1 < valor2) && ( valor1 < valor3)) { JOptionPane.showInternalMessageDialog(null,"O MENOR ENTRE ELES : " + valor1 +"."); } else if ((valor2 < valor3) && ( valor2 < valor1)) { JOptionPane.showInternalMessageDialog(null,"O MENOR ENTRE ELES : " + valor2 +"."); } else { JOptionPane.showInternalMessageDialog(null,"O MENOR ENTRE ELES : " + valor3 +"."); } } } //fim
true
4ed9b560571a993facf9faebc03ff262682a89be
Java
InJamie/ClmTakeAway
/takeaway/product-service/src/main/java/pers/jamie/mapper/ProductCategoryMapper.java
UTF-8
409
1.679688
2
[]
no_license
package pers.jamie.mapper; import pers.jamie.entity.ProductCategory; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import pers.jamie.vo.ProductCategortVo; import java.util.List; /** * <p> * 类目表 Mapper 接口 * </p> * * @author Jamie * @since 2020-08-20 */ public interface ProductCategoryMapper extends BaseMapper<ProductCategory> { public String findNameByType(Integer id); }
true
07a380524f4960b8f76e71220784fd4775067a1c
Java
enaawy/gproject
/gp_JADX/com/google/android/finsky/bb/p149a/C1562d.java
UTF-8
5,679
1.578125
2
[]
no_license
package com.google.android.finsky.bb.p149a; import android.text.TextUtils; import com.google.android.finsky.aa.C0954a; import com.google.android.finsky.ba.C1461c; import com.google.android.finsky.ba.C1552e; import com.google.android.finsky.bb.C1561c; import com.google.android.finsky.cv.p177a.lh; import com.google.android.finsky.dx.C2910a; import com.google.android.finsky.utils.FinskyLog; import com.google.wireless.android.finsky.dfe.h.a.g; import com.google.wireless.android.finsky.dfe.h.a.j; import com.google.wireless.android.finsky.dfe.h.a.o; import com.google.wireless.android.finsky.dfe.nano.cn; import com.google.wireless.android.finsky.dfe.nano.gy; public final class C1562d implements C1561c { public final C2910a f8353a; public final C1461c f8354b; public final String f8355c; public final j f8356d; public final o f8357e; public C1562d(C2910a c2910a, C1461c c1461c, String str) { j jVar; this.f8353a = c2910a; this.f8354b = c1461c; this.f8355c = str; if (this.f8355c != null) { gy b = this.f8353a.m15190b(this.f8355c); if (b != null) { jVar = b.c; this.f8356d = jVar; this.f8357e = m9072q(); } } jVar = null; this.f8356d = jVar; this.f8357e = m9072q(); } public final String mo2318a() { return this.f8355c; } public final j mo2320b() { return this.f8356d; } public final boolean mo2323d() { return this.f8357e != null; } public final boolean mo2324e() { return this.f8357e != null && this.f8357e.c == 5; } public final boolean mo2325f() { if (!mo2323d()) { return false; } for (o oVar : this.f8356d.c.a) { if (oVar.c == 5) { return true; } } return false; } public final boolean mo2329j() { return this.f8354b.mo2249j(this.f8355c).mo2294a(12603772); } public final boolean mo2330k() { return this.f8354b.mo2249j(this.f8355c).mo2294a(12613100); } public final boolean mo2319a(int i) { C1552e j = this.f8354b.mo2249j(this.f8355c); switch (i) { case 1: return j.mo2294a(12604245); case 3: return j.mo2294a(12604244); case 4: return j.mo2294a(12604246); default: return false; } } public final boolean mo2326g() { gy b = this.f8353a.m15190b(this.f8355c); if (b != null) { cn cnVar = b.e; if (cnVar != null) { return "1".equals(cnVar.b); } } return false; } public final o mo2322c() { return this.f8357e; } public final boolean mo2327h() { if (this.f8357e == null || this.f8357e.c != 1) { return false; } return true; } public final boolean mo2328i() { if (this.f8357e == null || (this.f8357e.c != 1 && this.f8357e.c != 4)) { return false; } return true; } public final o mo2317a(String str) { if (mo2323d()) { for (o oVar : this.f8356d.c.a) { if (str.equals(oVar.d.f12097d)) { return oVar; } } } return null; } public final void mo2321b(String str) { if (TextUtils.isEmpty(this.f8355c)) { FinskyLog.m21669e("AccountName should never be null to save consistency token.", new Object[0]); } else if (!TextUtils.isEmpty(str)) { lh lhVar = new lh(); lhVar.f13011b |= 1; lhVar.f13012c = "X-DFE-Family-Consistency-Token"; lhVar.m13029a(str); C2910a.m15175a(this.f8355c, lhVar); } } public final boolean mo2331l() { if (this.f8356d != null && this.f8356d.b == 2 && this.f8356d.e == 1) { return true; } return false; } public final boolean mo2332m() { if (this.f8356d == null) { return true; } return ((Long) C0954a.aE.m5777b(this.f8355c).m5760a()).longValue() >= this.f8356d.d; } public final boolean mo2333n() { return (this.f8356d == null || !mo2331l() || mo2332m()) ? false : true; } public final void mo2334o() { if (this.f8356d == null) { FinskyLog.m21669e("No family info while dismissing paused edu card.", new Object[0]); } else { C0954a.aE.m5777b(this.f8355c).m5763a(Long.valueOf(this.f8356d.d)); } } public final String mo2335p() { String str; if (this.f8356d == null) { str = "Null familyInfo"; } else { int i = this.f8356d.b; str = "Family status: " + i + "\nInactive Reason: " + this.f8356d.e; } boolean g = mo2326g(); return new StringBuilder(String.valueOf(str).length() + 49).append(str).append("\nTos Accepted: ").append(g).append("\nOnboarding Experiment: ").append(mo2329j()).toString(); } private final o m9072q() { if (this.f8356d != null) { g gVar = this.f8356d.c; if (!(gVar == null || gVar.a == null)) { for (o oVar : gVar.a) { if (oVar.d != null && oVar.d.f12112s != null && oVar.d.f12112s.f12059l != null && oVar.d.f12112s.f12059l.f12064b) { return oVar; } } } } return null; } }
true
cf5f4863f57494e4dac4672f57e8f261c2ff5d81
Java
gaopeipaopao/Novel
/account/src/main/java/com/example/account/Adapters/AccountManageAdapter.java
UTF-8
2,029
2.390625
2
[]
no_license
package com.example.account.Adapters; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.account.Holders.AccountViewHolder; import com.example.account.Models.AccountModel; import com.example.account.R; import java.util.List; public class AccountManageAdapter extends RecyclerView.Adapter<AccountViewHolder> { private Context mContext; private List<AccountModel> mDatas; public static final int ACCOUNT = 0; public static final int ADD_ACCOUNT = 1; public static final int QUIT_ACCOUNT = 2; public AccountManageAdapter(Context context, List<AccountModel> datas) { this.mContext = context; this.mDatas = datas; } @Override public int getItemViewType(int position) { if(position<mDatas.size()){ return ACCOUNT; }else if(position == mDatas.size()){ return ADD_ACCOUNT; }else { return QUIT_ACCOUNT; } } @NonNull @Override public AccountViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view; if(viewType == ACCOUNT){ view = LayoutInflater.from(mContext).inflate(R.layout.account_layout_account_manage_item ,parent,false); }else if(viewType == ADD_ACCOUNT){ view = LayoutInflater.from(mContext).inflate(R.layout.account_layout_account_mamage_add_account ,parent,false); }else { view = LayoutInflater.from(mContext).inflate(R.layout.account_layout_account_manage_quit_item ,parent,false); } return new AccountViewHolder(view,viewType); } @Override public void onBindViewHolder(@NonNull AccountViewHolder holder, int position) { } @Override public int getItemCount() { return mDatas.size()+2; } }
true
cedee9bafb52c49d5f95167fceb0dfef7382b6bd
Java
akash-starvin/mpl-volleyball-fantasy-league
/app/src/main/java/com/example/mpl/SelectCaptainViceCaptain.java
UTF-8
4,187
2.09375
2
[]
no_license
package com.example.mpl; import androidx.appcompat.app.AppCompatActivity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.Toast; import com.example.mpl.ui.Matches.Matches_Fragment; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class SelectCaptainViceCaptain extends AppCompatActivity { Spinner scap,svc; FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference(Constants.TBL_CURRENT_LEADERBOARD); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_select_captain_vice_captain); scap = findViewById(R.id.spcaptain); ArrayAdapter<String> spinner1ArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, Constants.TEAM_ARRY); scap.setAdapter(spinner1ArrayAdapter); svc = findViewById(R.id.spvicecaptain); ArrayAdapter<String> spinner2ArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, Constants.TEAM_ARRY); svc.setAdapter(spinner2ArrayAdapter); findViewById(R.id.ascvcBtnSave).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(!Constants.STATUS.equals("Select Players")) { new ShowToast(SelectCaptainViceCaptain.this, "Match has already started"); Intent i = new Intent(getApplicationContext(),Home_Page.class); startActivity(i); finish(); } else { if(scap.getSelectedItemId()==svc.getSelectedItemId()) new ShowToast(SelectCaptainViceCaptain.this, "Captain and Vice Captain cannot be the same"); else { sort(); MBCurrentMatchLeaderboard mb = new MBCurrentMatchLeaderboard(Constants.TEAM_ARRY[0],Constants.TEAM_ARRY[1],Constants.TEAM_ARRY[2],Constants.TEAM_ARRY[3],Constants.TEAM_ARRY[4],Constants.TEAM_ARRY[5],Constants.TEAM_ARRY[6],Constants.TEAM_ARRY[7],Constants.PHONE,Constants.POSITION,"0","0","0","0","0","0","0","0",0,Constants.NAME); myRef.child("Leaderboard-"+Constants.POSITION).child(Constants.PHONE).setValue(mb); new ShowToast(SelectCaptainViceCaptain.this,"Team Created"); Intent i = new Intent(getApplicationContext(), Home_Page.class); finishAffinity(); startActivity(i); } } } }); findViewById(R.id.ascvcBtnTeamPreview).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(getApplicationContext(),CourtLayoutPreview.class) ; startActivity(i); } }); } public void sort() { String temp1,temp2; String cap,vc; cap =""+ scap.getSelectedItem(); vc =""+ svc.getSelectedItem(); for (int i=0; i<Constants.TEAM_ARRY.length;i++) { if (Constants.TEAM_ARRY[i].equals(cap)){ temp1 = Constants.TEAM_ARRY[i]; Constants.TEAM_ARRY[i] = Constants.TEAM_ARRY[0]; Constants.TEAM_ARRY[0] = temp1; } } for (int i=0; i<Constants.TEAM_ARRY.length;i++) { if (Constants.TEAM_ARRY[i].equals(vc)){ temp2 = Constants.TEAM_ARRY[i]; Constants.TEAM_ARRY[i] = Constants.TEAM_ARRY[1]; Constants.TEAM_ARRY[1] = temp2; } } } }
true
d6298b02b10cdc27a0d06db5495b6cd9f9920d27
Java
Jsevenk/practice
/db-practice/src/main/java/com/si/practice/dbpractice/client/order/api/OrderQueryService.java
UTF-8
353
1.828125
2
[]
no_license
package com.si.practice.dbpractice.client.order.api; import com.si.practice.dbpractice.client.order.request.QueryOrderRequest; import com.si.practice.dbpractice.common.order.OrderDTO; import java.util.List; public interface OrderQueryService { OrderDTO queryOrderById(Long orderId); List<OrderDTO> listOrders(QueryOrderRequest request); }
true
ec3f419cb309459932882dfeb3b12044ec7f9c26
Java
tgdslsg/forum
/src/main/java/com/lsg/dao/ReplyDao.java
UTF-8
1,413
2.203125
2
[]
no_license
package com.lsg.dao; import com.lsg.entity.Reply; import com.lsg.entity.User; import com.lsg.util.Config; import com.lsg.util.DbHelp; import org.apache.commons.dbutils.BasicRowProcessor; import org.apache.commons.dbutils.handlers.AbstractListHandler; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; /** * Created by tgdsl on 2016/12/22. */ public class ReplyDao { public void savaReply(Reply reply){ String sql="insert into t_reply (content,userid,topicid)values(?,?,?)"; DbHelp.update(sql,reply.getContent(),reply.getUserid(),reply.getTopicid()); } public List<Reply> findListByTopicId(String topicId) { String sql = "select tu.id,tu.avatar,tu.username,tr.* from t_reply tr ,t_user tu where tr.userid=tu.id and topicid=?"; return DbHelp.query(sql, new AbstractListHandler<Reply>() { @Override protected Reply handleRow(ResultSet resultSet) throws SQLException { Reply reply = new BasicRowProcessor().toBean(resultSet,Reply.class); User user = new User(); user.setAvatar(Config.get("qiniu.domain")+resultSet.getString("avatar")); user.setUsername(resultSet.getString("username")); user.setId(resultSet.getInt("id")); reply.setUser(user); return reply; } },topicId); } }
true
fd013fe292cf23432d3ee5ef6d2dfab50fbafd81
Java
AkankshaMishra297/BookRoomUsingTemplate
/BookMeetingRoom4/src/main/java/com/SecurityDemo/demo/controller/UserCRUDController.java
UTF-8
2,642
2.015625
2
[]
no_license
package com.SecurityDemo.demo.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.SecurityDemo.demo.model.Dept_request; import com.SecurityDemo.demo.model.User; import com.SecurityDemo.demo.model.mail_request; import com.SecurityDemo.demo.repository.tlRepository; import com.SecurityDemo.demo.service.DeptRequestService; import com.SecurityDemo.demo.service.MailRequestService; import com.SecurityDemo.demo.service.NotificationService; import com.SecurityDemo.demo.service.UserService; @Controller public class UserCRUDController { Authentication auth; @Autowired NotificationService notificationService; @Autowired UserService userService; @Autowired MailRequestService mailRequestService; @Autowired DeptRequestService deptRequestService; @Autowired tlRepository repo; @RequestMapping(value = "/save", method = RequestMethod.POST) public String saveEmp(@ModelAttribute("user") User user) { userService.SaveEditUser(user); if (user.getRoles().toString().equalsIgnoreCase("[TL]")) { int id = user.getId(); String name = user.getName(); String email = user.getEmail(); String dept = user.getDepartment(); repo.saveTl(name, dept, id, email); } return "redirect:/userManagement/1"; } @RequestMapping("/edit/{id}") public ModelAndView showEditUserForm(@PathVariable(name = "id") int id) { ModelAndView mv = new ModelAndView("newUser/edit_user"); User user = userService.get(id); mv.addObject("user", user); return mv; } @RequestMapping(value = "/edit_mailsave", method = RequestMethod.POST) public String editMailRequest(Authentication auth,mail_request mail) { String user=auth.getName(); mailRequestService.savemailreq(mail); String type="Mail_Change"; String role="USER"; notificationService.savetl(user,type,role); return "redirect:/userHome"; } @RequestMapping(value = "/edit_deptsave", method = RequestMethod.POST) public String editDeptRequest(Authentication auth,Dept_request dept) { String user=auth.getName(); deptRequestService.savemailreq(dept); String type="Department_Change"; String role="USER"; notificationService.savetl(user,type,role); return "redirect:/userHome"; } }
true
ebafe8773ad7fbd2ea21c480838887a1ce425b20
Java
dddemons/demo
/src/main/java/com/junc/demo/entity/UserAccountInformation.java
UTF-8
2,860
2.1875
2
[]
no_license
package com.junc.demo.entity; import java.io.Serializable; import java.util.Date; public class UserAccountInformation implements Serializable { private String id; private String name; private String signature; private String account; private String password; private Integer phone; private String email; private Date lastLoginTime; private Integer status; private Date createTime; private String createUuid; private Date lastUpdateTime; private String lastUpdateUuid; private static final long serialVersionUID = 1L; public String getId() { return id; } public void setId(String id) { this.id = id == null ? null : id.trim(); } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getSignature() { return signature; } public void setSignature(String signature) { this.signature = signature == null ? null : signature.trim(); } public String getAccount() { return account; } public void setAccount(String account) { this.account = account == null ? null : account.trim(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password == null ? null : password.trim(); } public Integer getPhone() { return phone; } public void setPhone(Integer phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email == null ? null : email.trim(); } public Date getLastLoginTime() { return lastLoginTime; } public void setLastLoginTime(Date lastLoginTime) { this.lastLoginTime = lastLoginTime; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getCreateUuid() { return createUuid; } public void setCreateUuid(String createUuid) { this.createUuid = createUuid == null ? null : createUuid.trim(); } public Date getLastUpdateTime() { return lastUpdateTime; } public void setLastUpdateTime(Date lastUpdateTime) { this.lastUpdateTime = lastUpdateTime; } public String getLastUpdateUuid() { return lastUpdateUuid; } public void setLastUpdateUuid(String lastUpdateUuid) { this.lastUpdateUuid = lastUpdateUuid == null ? null : lastUpdateUuid.trim(); } }
true
e860322f56be2c135a2d952adb20ff3ece8ae523
Java
YongSoekChoeng/framework3.0
/src/net/dstone/sample/dept/cud/DeptCudDao.java
UTF-8
2,067
1.875
2
[]
no_license
package net.dstone.sample.dept.cud; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.orm.ibatis.SqlMapClientTemplate; @Repository public class DeptCudDao extends net.dstone.common.biz.BaseDao { @Autowired @Qualifier("sqlMapClientTemplate2") private SqlMapClientTemplate sqlMapClientTemplate2; /******************************************* 샘플부서[SAMPLE_DEPT] 시작 *******************************************/ /* * 샘플부서[SAMPLE_DEPT] NEW키값 조회 */ public net.dstone.sample.dept.cud.vo.SampleDeptCudVo selectSampleDeptNewKey(net.dstone.sample.dept.cud.vo.SampleDeptCudVo sampleDeptCudVo) throws Exception { return (net.dstone.sample.dept.cud.vo.SampleDeptCudVo) sqlMapClientTemplate2.queryForObject("COM_SAMPLE_DEPT_CUD_DEPTCUDDAO.selectSampleDeptNewKey", sampleDeptCudVo); } /* * 샘플부서[SAMPLE_DEPT] 입력 */ public void insertSampleDept(net.dstone.sample.dept.cud.vo.SampleDeptCudVo sampleDeptCudVo) throws Exception { sqlMapClientTemplate2.insert("COM_SAMPLE_DEPT_CUD_DEPTCUDDAO.insertSampleDept", sampleDeptCudVo); } /* * 샘플부서[SAMPLE_DEPT] 수정 */ public void updateSampleDept(net.dstone.sample.dept.cud.vo.SampleDeptCudVo sampleDeptCudVo) throws Exception { sqlMapClientTemplate2.update("COM_SAMPLE_DEPT_CUD_DEPTCUDDAO.updateSampleDept", sampleDeptCudVo); } /* * 샘플부서[SAMPLE_DEPT] 삭제 */ public void deleteSampleDept(net.dstone.sample.dept.cud.vo.SampleDeptCudVo sampleDeptCudVo) throws Exception { sqlMapClientTemplate2.delete("COM_SAMPLE_DEPT_CUD_DEPTCUDDAO.deleteSampleDept", sampleDeptCudVo); } /******************************************* 샘플부서[SAMPLE_DEPT] 끝 *******************************************/ }
true
a2a4b50f46283474023d1e793cb24cda1daa699c
Java
MapperTV/mapperbase
/src/main/java/tv/mapper/mapperbase/world/level/block/BaseBlocks.java
UTF-8
2,523
1.882813
2
[ "MIT" ]
permissive
package tv.mapper.mapperbase.world.level.block; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.PressurePlateBlock; import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.state.BlockBehaviour.Properties; import net.minecraft.world.level.material.Material; import net.minecraft.world.level.material.MaterialColor; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.RegistryObject; import tv.mapper.mapperbase.MapperBase; public class BaseBlocks { public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, MapperBase.MODID); private static Properties steelProperties = Block.Properties.of(Material.METAL, MaterialColor.STONE).strength(5.0F, 6.0F).sound(SoundType.LANTERN).requiresCorrectToolForDrops(); public static final RegistryObject<CustomBlock> STEEL_BLOCK = BLOCKS.register("steel_block", () -> new CustomBlock(steelProperties, ToolTypes.PICKAXE, ToolTiers.IRON)); public static final RegistryObject<CustomStairsBlock> STEEL_STAIRS = BLOCKS.register("steel_stairs", () -> new CustomStairsBlock(() -> STEEL_BLOCK.get().defaultBlockState(), steelProperties, ToolTypes.PICKAXE, ToolTiers.IRON)); public static final RegistryObject<CustomSlabBlock> STEEL_SLAB = BLOCKS.register("steel_slab", () -> new CustomSlabBlock(steelProperties, ToolTypes.PICKAXE, ToolTiers.IRON)); public static final RegistryObject<CustomWallBlock> STEEL_WALL = BLOCKS.register("steel_wall", () -> new CustomWallBlock(steelProperties, ToolTypes.PICKAXE, ToolTiers.IRON)); public static final RegistryObject<CustomPressurePlateBlock> STEEL_PRESSURE_PLATE = BLOCKS.register("steel_pressure_plate", () -> new CustomPressurePlateBlock(PressurePlateBlock.Sensitivity.MOBS, steelProperties.noCollission(), ToolTypes.PICKAXE, ToolTiers.IRON)); public static final RegistryObject<CustomFenceBlock> STEEL_FENCE = BLOCKS.register("steel_fence", () -> new CustomFenceBlock(steelProperties, ToolTypes.PICKAXE, ToolTiers.IRON)); public static final RegistryObject<CustomFenceGateBlock> STEEL_FENCE_GATE = BLOCKS.register("steel_fence_gate", () -> new CustomFenceGateBlock(steelProperties, ToolTypes.PICKAXE, ToolTiers.IRON)); public static void init() { BLOCKS.register(FMLJavaModLoadingContext.get().getModEventBus()); } }
true
42b544d1bf4b2577899ff9393835d9801360f545
Java
moutainhigh/main-pom
/main4-item/main4-item-default/src/main/java/com/shigu/main4/item/services/impl/TaobaoUnauthorizedSynService.java
UTF-8
16,659
1.875
2
[]
no_license
package com.shigu.main4.item.services.impl; import com.opentae.core.mybatis.utils.FieldUtil; import com.opentae.data.mall.beans.*; import com.opentae.data.mall.examples.ShiguGoodsSoldoutExample; import com.opentae.data.mall.examples.ShiguGoodsTinyExample; import com.opentae.data.mall.interfaces.TaobaoItemPropMapper; import com.opentae.data.mall.interfaces.TaobaoPropValueMapper; import com.shigu.main4.item.enums.ItemFrom; import com.shigu.main4.item.exceptions.SynException; import com.shigu.main4.item.services.utils.OuterSynUtil; import com.shigu.main4.item.vo.ShiguPropImg; import com.shigu.main4.item.vo.SynItem; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.*; /** * 类名:TaobaoUnauthorizedSynService * 类路径:com.shigu.main4.item.services.impl.TaobaoUnauthorizedSynService * 创建者:王浩翔 * 创建时间:2017-11-05 11:54 * 项目:main-pom * 描述: */ @Component("taobaoUnauthorizedSynService") public class TaobaoUnauthorizedSynService extends OuterSynUtil { @Autowired TaobaoPropValueMapper taobaoPropValueMapper; @Autowired TaobaoItemPropMapper taobaoItemPropMapper; @Override protected void goodsExecute(SynShopBean synBean, Long otherGoodsId) { } @Override protected Map<Long, ShiguGoodsTiny> getLocalOuterGoodsMap(Long shopId, String webSite) { ShiguGoodsTinyExample tinyExample = new ShiguGoodsTinyExample(); tinyExample.setWebSite(webSite); tinyExample.createCriteria().andStoreIdEqualTo(shopId).andIsExcelImpEqualTo(ItemFrom.TAOBAO.ordinal()); HashMap<Long, ShiguGoodsTiny> result = new HashMap<>(); for (ShiguGoodsTiny tiny : shiguGoodsTinyMapper.selectFieldsByExample(tinyExample, FieldUtil.codeFields("goods_id,num_iid"))) { result.put(tiny.getNumIid(),tiny); } return result; } @Override protected Map<Long, ShiguGoodsSoldout> getSynLocalSoldoutMap(List<Long> outerIds, Long shopId, String webSite) { if (outerIds.size() == 0) { return new HashMap<>(); } ShiguGoodsSoldoutExample soldoutExample = new ShiguGoodsSoldoutExample(); soldoutExample.setWebSite(webSite); soldoutExample.createCriteria().andStoreIdEqualTo(shopId).andNumIidIn(outerIds); HashMap<Long, ShiguGoodsSoldout> result = new HashMap<>(); for (ShiguGoodsSoldout soldout : shiguGoodsSoldoutMapper.selectByExample(soldoutExample)) { result.put(soldout.getNumIid(),soldout); } return result; } @Override protected Map<Long, ?> getPagedGoodsInfo(SynShopBean synShopBean, int pageNo) throws SynException { String shopUrl = "https://".concat(synShopBean.shop.getTaobaoUrl().replace("http://","").replace("https://","")); if (shopUrl.endsWith("/")) { shopUrl = shopUrl.substring(0,shopUrl.length()-1); } try { Document dynaVerify = Jsoup.connect(String.format("%s/search.htm",shopUrl)).get(); String dynaParam = dynaVerify.select("input#J_ShopAsynSearchURL").val(); Connection connect = Jsoup.connect(String.format("%s%s&pageNo=%d", shopUrl,dynaParam, pageNo)); Document orignalDoc = connect.get(); String orignalHtml = orignalDoc.html().replaceAll("\\\\&quot;", "").replaceAll("\\\\\"","").replaceAll("=\"\"",""); Document shopGoodsInfo = Jsoup.parse(orignalHtml); if ("0".equals(shopGoodsInfo.select("div.search-result").select("span").text())) { //分页数据搜索结束 throw new SynException(SynException.SynExceptionEnum.END_OF_PAGED_SYN_INFO_EXCEPTION); } //不能直接拿到商品修改时间,先返回numiid,以后有需要了把map里的值改为其他数据 Elements elements = shopGoodsInfo.select("dl"); HashMap<Long, Object> resultMap = new HashMap<>(); for (Element element : elements) { resultMap.put(Long.valueOf(element.attr("data-id")),Long.valueOf(element.attr("data-id"))); } return resultMap; } catch (IOException e) { throw new SynException(SynException.SynExceptionEnum.COULD_NOT_GET_SYN_INFO_EXCEPTION); } } //todo 单商品信息获取封装 @Override protected SynItem getGoodsInfo(Long outGoodsId, SynShopBean synShopBean, Long ignored) throws SynException { SynItem synItem = new SynItem(); try { ShiguShop shop=synShopBean.shop; //不是抓取到的数据 Date now = new Date(); synItem.setListTime(now); synItem.setModified(now); //创建时间不应该为空 synItem.setCreated(now); Calendar instance = Calendar.getInstance(); instance.setTime(now); instance.add(Calendar.DATE,7); synItem.setDelistTime(instance.getTime()); synItem.setNum(100L); //档口数据 synItem.setItemFrom(ItemFrom.TAOBAO); synItem.setShopId(shop.getShopId()); synItem.setWebSite(shop.getWebSite()); synItem.setMarketId(shop.getMarketId()); synItem.setFloorId(shop.getFloorId()); //抓取数据 String detailUrl = String.format("https://item.taobao.com/item.htm?id=%d", outGoodsId); synItem.setDetailUrl(detailUrl); Document goodsDoc = Jsoup.connect(detailUrl).get(); synItem.setNumIid(outGoodsId); String title = goodsDoc.select("h3.tb-main-title").get(0).attr("data-title"); synItem.setTitle(title); String piPriceStr = goodsDoc.select("em.tb-rmb-num").text(); synItem.setPiPriceString(piPriceStr); synItem.setPriceString(piPriceStr); List<ShiguPropImg> propImgs = new ArrayList<>(); synItem.setPropImgs(propImgs); for (Element script : goodsDoc.head().select("script")) { boolean configScriptIs = false; String confHtml = script.html(); int startIndex = confHtml.indexOf("//desc.alicdn.com"); if (startIndex>0) { configScriptIs = true; int endIndex = confHtml.indexOf("'", startIndex); Document descDoc = Jsoup.connect(String.format("https:%s", confHtml.substring(startIndex, endIndex))).get(); String descResp = descDoc.html(); //WebClient webClient = new WebClient(); //webClient.getOptions().setCssEnabled(false); //webClient.getOptions().setJavaScriptEnabled(false); //TextPage page = webClient.getPage(String.format("https:%s", confHtml.substring(startIndex, endIndex))); //String descResp = page.getContent(); //webClient.close(); int descStart = descResp.indexOf("'"); int descEnd = descResp.indexOf("';"); if (descEnd>descStart && descStart>0) { String descStr = descResp.substring(descStart + 1, descEnd).replaceAll("<img src=\"https://img.alicdn.com/imgextra/i4/1642658218/TB2f_L8cV9gSKJjSspbXXbeNXXa-1642658218.jpg\" />","").replaceAll("<img src=\"https://img.alicdn.com/imgextra/i4/1642658218/TB2f_L8cV9gSKJjSspbXXbeNXXa-1642658218.jpg\">","").replaceAll("\\\\",""); synItem.setGoodsDesc(descStr); } } if (configScriptIs) { String online = getContextFromString(confHtml, "online", ":", ",", 6); boolean onsale = online != null && online.contains("true"); synItem.setOnsale(onsale); int parentCidIndex = confHtml.indexOf("rcid"); int cidIndex = confHtml.indexOf("cid"); if (cidIndex == parentCidIndex + 1) { cidIndex = confHtml.indexOf("cid",parentCidIndex+4); } int cidStart = confHtml.indexOf("'", cidIndex); if (cidStart>0) { int cidEnd = confHtml.indexOf("'", cidStart + 1); Long cid = Long.valueOf(confHtml.substring(cidStart + 1, cidEnd)); synItem.setCid(cid); } int idataIndex = confHtml.indexOf("idata : {"); int picIndex = confHtml.indexOf("pic", idataIndex); int picStart = confHtml.indexOf("'", picIndex); int picEnd = confHtml.indexOf("'", picStart + 1); synItem.setPicUrl(confHtml.substring(picStart+1,picEnd)); //商品六张图 List<String> imageList = new ArrayList<>(6); String images = getContextFromString(confHtml, "auctionImages", "[", "]", 0).replace("[","").replace("]",""); String[] splitImgs = images.split(","); for (String splitImg : splitImgs) { imageList.add("https:".concat(splitImg.replaceAll("\"",""))); } synItem.setImageList(imageList); } } for (Element bodyScript : goodsDoc.body().select("script")) { String scriptContext = bodyScript.html().trim(); boolean isConfig = scriptContext.startsWith("Hub"); if (isConfig) { int cidAllIndex = scriptContext.indexOf("rstShopcatlist"); if (cidAllIndex>0) { String cidAll = getContextFromString(scriptContext, "rstShopcatlist", "'", "'", 0); synItem.setCidAll(cidAll); } } } StringBuffer propBuf = new StringBuffer(); StringBuffer propNamesBuf = new StringBuffer(); StringBuffer propAlias = new StringBuffer(); StringBuffer inputPids = new StringBuffer(); StringBuffer inputStr = new StringBuffer(); for (Element element : goodsDoc.select("ul[data-property]")) { String propName = element.attr("data-property"); for (Element li : element.select("li")) { //颜色,尺码 String kvPairStr = li.attr("data-value"); propBuf.append(';').append(kvPairStr); propNamesBuf.append(';').append(kvPairStr).append(':').append(propName).append(':').append(li.select("a").select("span").html()); Elements propImgElement = li.select("a[style]"); if (propImgElement.size()>0) { String origalPropUrl = propImgElement.get(0).attr("style"); int endIndex = origalPropUrl.indexOf(".jpg"); int startIndex = origalPropUrl.indexOf("//"); if (startIndex > 0 && endIndex >0) { String propUrl = "https:".concat(origalPropUrl.substring(startIndex, endIndex + 4)); String[] kvPair = kvPairStr.split(":"); ShiguPropImg shiguPropImg = new ShiguPropImg(); shiguPropImg.setPid(Long.valueOf(kvPair[0])); shiguPropImg.setVid(Long.valueOf(kvPair[1])); shiguPropImg.setUrl(propUrl); propImgs.add(shiguPropImg); } } } } long inputIndex = -1001; for (Element element : goodsDoc.select("ul.attributes-list").select("li")) { String[] kvPair = element.text().split(":"); String keyStr = kvPair[0]; String valueStr = element.attr("title"); if ("货号".equals(keyStr)||"款号".equals(keyStr)) { synItem.setGoodsNo(valueStr); } else if ("颜色".equals(keyStr)||"尺码".equals(keyStr)||"尺寸".equals(keyStr)){ // 颜色尺码忽略,在其他地方获取 } else { TaobaoPropValue taobaoPropValue = new TaobaoPropValue(); taobaoPropValue.setCid(synItem.getCid()); taobaoPropValue.setPropName(keyStr); taobaoPropValue.setName(valueStr); taobaoPropValue = taobaoPropValueMapper.selectOne(taobaoPropValue); Long pid = null; Long vid = null; if (taobaoPropValue != null) { pid = taobaoPropValue.getPid(); vid = taobaoPropValue.getVid(); propBuf.append(';').append(pid).append(':').append(vid); } else { TaobaoItemProp taobaoItemProp = new TaobaoItemProp(); taobaoItemProp.setCid(synItem.getCid()); taobaoItemProp.setName(keyStr); taobaoItemProp = taobaoItemPropMapper.selectOne(taobaoItemProp); if (taobaoItemProp != null) { if (taobaoItemProp.getIsSaleProp() != null && taobaoItemProp.getIsSaleProp() ==1) { //销售属性在其他地方取 continue; } pid = taobaoItemProp.getPid(); vid = inputIndex--; Integer isAllowAlias = taobaoItemProp.getIsAllowAlias(); if (isAllowAlias != null && isAllowAlias == 1) { propAlias.append(';').append(pid).append(':').append(vid).append(':').append(valueStr); } else { inputPids.append(',').append(pid); inputStr.append(',').append(valueStr); } } } propNamesBuf.append(';').append("pid").append(':').append("vid").append(':').append(keyStr).append(':').append(valueStr); } } if (propBuf.length()>0) { synItem.setProps(propBuf.substring(1)); } if (propNamesBuf.length()>0) { synItem.setPropsName(propNamesBuf.substring(1)); } if (propAlias.length()>0) { synItem.setPropertyAlias(propAlias.substring(1)); } if (inputPids.length()>0) { synItem.setInputPids(inputPids.substring(1)); synItem.setInputStr(inputStr.substring(1)); } } catch (Exception e) { throw new SynException(SynException.SynExceptionEnum.SYN_ONE_ITEM_EXCEPTION); } return synItem; } public static String getContextFromString(String original,String target,String begin,String end,int rotate){ int targetIndex = original.indexOf(target); if (targetIndex > 0) { int targetStart = original.indexOf(begin, targetIndex + rotate)+1; int targetEnd = original.indexOf(end, targetStart); if (targetStart>0&&targetEnd>0) { return original.substring(targetStart,targetEnd); } } return null; } @Override protected boolean checkGoodsSyn(ShiguGoodsTiny goods, Object synGoods) { //暂时默认为所有淘宝上架且档口上架的都已经同步 return true; } @Override protected boolean checkLocalModified(ShiguGoodsModified modified, OuterSynUtil.ModifiedStateEnum modifiedState) { //对应ShiguGoodsModified记录不存在,则没修改过 if (modified == null) { return false; } switch (modifiedState){ case HAS_LOCAL_UP: return !modified.getHasModInstock().equals(0); case HAS_LOCAL_DOWN: //手动进行过下架 return !modified.getHasModInstock().equals(1); } return false; } }
true
01fb691dfe5a55b011ae26be2d9617100d5346ea
Java
AlexanderCOLD/imagick-FT
/src/main/java/se/imagick/ft/common/FTUtils.java
UTF-8
2,255
2.75
3
[ "MIT" ]
permissive
package se.imagick.ft.common; /** * Utility methods for Complex-Polar / Polar-Complex conversions.<br> * <br> * ---------------------<br> * The MIT License (MIT)<br> * <br> * Copyright (c) 2015 Olav Holten<br> * <br> * 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:<br> * <br> * The above copyright notice and this permission notice shall be included in<br> * all copies or substantial portions of the Software.<br> * <br> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ public class FTUtils { public static final double RAD_TWO_PI = 2d * Math.PI; public static final double DEG_360 = 360d; public static void complex2Polar(final Complex complex, Polar polar) { final double real = complex.getReal(); final double imag = complex.getImaginary(); polar.setMagnitude(Math.sqrt(real * real + imag * imag)); polar.setPhase(Math.atan2(imag, real)); } public static void polar2Complex(final Polar polar, final Complex complex) { final double mag = polar.getMagnitude(); final double phase = polar.getPhase(); complex.setReal(Math.cos(phase) * mag); complex.setImaginary(Math.sin(phase) * mag); } public static double degrees2Radians(final double deg) { return RAD_TWO_PI * (deg / DEG_360); } public static double radians2Degrees(final double rad) { return (rad / RAD_TWO_PI) * DEG_360; } }
true
dd7c148f938b4c17d14c2f019afdf517b2b591e9
Java
Ericnk1/spring-PetClinic
/src/main/java/com/example/springpetclinic/controllers/OwnerController.java
UTF-8
2,471
2.34375
2
[]
no_license
package com.example.springpetclinic.controllers; import com.example.springpetclinic.exceptions.NotFoundException; import com.example.springpetclinic.models.Owner; import com.example.springpetclinic.services.OwnerService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.Date; import java.util.List; import java.util.Optional; @CrossOrigin(origins = "*", allowedHeaders = "*") @RestController @RequestMapping("/owner") public class OwnerController { @Autowired private OwnerService ownerService; @PostMapping public ResponseEntity<String> createOwner(@RequestBody Owner owner) { ownerService.createOwner(owner); return new ResponseEntity<>(HttpStatus.CREATED); } @GetMapping public List<Owner> getAllOwners() { return ownerService.getAllOwners(); } @RequestMapping("/active") public List<Owner> getActiveUsers(Model model) {return ownerService.getActiveOwners();} @PutMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<String> updateOwner(@RequestBody Owner owner) { ownerService.updateOwner(owner); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setDate(new Date().toInstant()); return new ResponseEntity<>(HttpStatus.OK); } @DeleteMapping("/{id}") public ResponseEntity<String> deleteOwner(@PathVariable Long id) { ownerService.deleteOwnerById(id); return new ResponseEntity<>(HttpStatus.OK); } @GetMapping("/full-delete/{id}") public ResponseEntity<String> fullDeleteOwner(@PathVariable Long id) { ownerService.fullDeleteOwnerById(id); return new ResponseEntity<>(HttpStatus.OK); } @GetMapping("/restore/{id}") public ResponseEntity<String> restoreOwner(@PathVariable Long id) { ownerService.restoreOwnerById(id); return new ResponseEntity<>(HttpStatus.OK); } @RequestMapping("/res/{id}") public Optional<Owner> findOwnerById(@PathVariable("id") Long id){ return ownerService.findOwnerById(id); } }
true
8f7c7bdefed7302fc31168ed9f438da52a5c80e0
Java
wcx410/Backstage
/dao/src/main/java/com/mapper/CommentsMapper.java
UTF-8
598
1.890625
2
[]
no_license
package com.mapper; import com.Comments; import com.CommentsAndCommodity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; public interface CommentsMapper extends BaseMapper<Comments> { @Select(" SELECT c.*,m.content AS content FROM commodity c \n" + " INNER JOIN comments AS m ON c.`id` =m.cid \n" + " WHERE m.uid=#{uid} AND m.isdelete = 0 ORDER BY m.comtime") public List<CommentsAndCommodity> getComments(@Param("uid") Integer uid); }
true
36ee08aa3dc81441db6855b0cfdc5dbb4b936bb3
Java
prowide/prowide-iso20022
/model-acmt-types/src/generated/java/com/prowidesoftware/swift/model/mx/dic/SettlementInstructionReason1Code.java
UTF-8
2,553
2.203125
2
[ "Apache-2.0" ]
permissive
package com.prowidesoftware.swift.model.mx.dic; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for SettlementInstructionReason1Code. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="SettlementInstructionReason1Code"&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;enumeration value="CSHI"/&gt; * &lt;enumeration value="ALLL"/&gt; * &lt;enumeration value="CSHO"/&gt; * &lt;enumeration value="CHAR"/&gt; * &lt;enumeration value="DIVI"/&gt; * &lt;enumeration value="INTE"/&gt; * &lt;enumeration value="SAVP"/&gt; * &lt;enumeration value="REDM"/&gt; * &lt;enumeration value="SAVE"/&gt; * &lt;enumeration value="BUYI"/&gt; * &lt;enumeration value="SELL"/&gt; * &lt;enumeration value="SUBS"/&gt; * &lt;enumeration value="WTHP"/&gt; * &lt;enumeration value="CORP"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * </pre> * */ @XmlType(name = "SettlementInstructionReason1Code") @XmlEnum public enum SettlementInstructionReason1Code { /** * Settlement of all credit amounts. * */ CSHI, /** * Settlement of all credit and debit amounts. * */ ALLL, /** * Settlement of all debit amounts. * */ CSHO, /** * Settlement of charges. * */ CHAR, /** * Settlement of dividends. * */ DIVI, /** * Settlement of interest. * */ INTE, /** * Settlement of investments to a savings plan. * */ SAVP, /** * Settlement of redemptions or redemption legs of a switch transaction. * */ REDM, /** * Settlement of investments to a savings plan and withdrawals from a savings plan. * */ SAVE, /** * Settlement of securities purchases. * */ BUYI, /** * Settlement of securities sales. * */ SELL, /** * Settlement of subscriptions or subscription legs of a switch transaction. * */ SUBS, /** * Settlement of withdrawals from a savings plan. * */ WTHP, /** * Settlement of corporate actions. * */ CORP; public String value() { return name(); } public static SettlementInstructionReason1Code fromValue(String v) { return valueOf(v); } }
true
92941cd42c342dad7c34a25528c296f93e1b089c
Java
realmadrid/aircraft-battle
/app/src/androidTest/java/edu/anu/comp6442/retrogame2018s1/SpriteInstrumentedTest.java
UTF-8
1,825
2.609375
3
[ "MIT" ]
permissive
package edu.anu.comp6442.retrogame2018s1; /* * Copyright (C) 2018, * * Jiewei Qian <u7472740@anu.edu.au> */ import android.content.Context; import android.graphics.BitmapFactory; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import edu.anu.comp6442.retrogame2018s1.model.Sprite; import static org.junit.Assert.*; import android.graphics.Bitmap; /** * 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 SpriteInstrumentedTest { private static float EPSILON = 0.001f; @Test public void bitmapRelatedGetter() throws Exception { Context appContext = InstrumentationRegistry.getTargetContext(); Bitmap bmp = BitmapFactory.decodeResource(appContext.getResources(), R.drawable.player); Sprite s = new Sprite(bmp); assertEquals(bmp.getWidth(), s.getWidth(), EPSILON); assertEquals(bmp.getHeight(), s.getHeight(), EPSILON); s.moveTo(10,20); // checks centerX, centerY are computed correctly assertEquals(10.0f + bmp.getWidth() / 2.0, s.getCenterX(), EPSILON); assertEquals(20.0f + bmp.getHeight() / 2.0, s.getCenterY(), EPSILON); } @Test public void collision() throws Exception { Context appContext = InstrumentationRegistry.getTargetContext(); Bitmap bmp = BitmapFactory.decodeResource(appContext.getResources(), R.drawable.player); Sprite a = new Sprite(bmp); Sprite b = new Sprite(bmp); assertEquals(true, a.collideWith(b)); a.moveTo(2 * bmp.getWidth(), 2 * bmp.getHeight()); assertEquals(false, a.collideWith(b)); } }
true
16ff518b2466cb4cc99b3ac6243b0c4833632145
Java
kbmg28/ws-pessoa
/src/main/java/br/com/kbmg/domain/PessoaJuridica.java
UTF-8
2,163
2.234375
2
[]
no_license
package br.com.kbmg.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.br.CNPJ; import com.fasterxml.jackson.annotation.JsonIgnore; @Entity public class PessoaJuridica implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long idPj; @Column @NotNull @CNPJ(message = "CNPJ inválido.") private String cnpj; @Column private String inscricaoEstadual; @OneToOne(fetch = FetchType.LAZY) @JoinColumn(name = "PESSOA_ID") @JsonIgnore private Pessoa pessoa; public PessoaJuridica() { } public PessoaJuridica(String cnpj, String inscricaoEstadual, Pessoa pessoa) { this.cnpj = cnpj; this.inscricaoEstadual = inscricaoEstadual; this.pessoa = pessoa; } public Long getIdPj() { return idPj; } public void setIdPj(Long idPj) { this.idPj = idPj; } public String getCnpj() { return cnpj; } public void setCnpj(String cnpj) { this.cnpj = cnpj; } public String getInscricaoEstadual() { return inscricaoEstadual; } public void setInscricaoEstadual(String inscricaoEstadual) { this.inscricaoEstadual = inscricaoEstadual; } public Pessoa getPessoa() { return pessoa; } public void setPessoa(Pessoa pessoa) { this.pessoa = pessoa; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((idPj == null) ? 0 : idPj.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; PessoaJuridica other = (PessoaJuridica) obj; if (idPj == null) { if (other.idPj != null) return false; } else if (!idPj.equals(other.idPj)) return false; return true; } }
true
bac011a72984cc353b2078e7be3219b8b54c61e7
Java
alphantom/organizations-task
/src/main/java/com/albina/springproject/services/OfficeServiceImpl.java
UTF-8
3,853
2.453125
2
[]
no_license
package com.albina.springproject.services; import com.albina.springproject.filter.*; import com.albina.springproject.filter.filters.Filter; import com.albina.springproject.models.Office; import com.albina.springproject.models.Organization; import com.albina.springproject.repositories.OfficeRepository; import com.albina.springproject.repositories.OrganizationRepository; import com.albina.springproject.view.office.OfficeItemView; import com.albina.springproject.view.office.OfficeListView; import ma.glasnost.orika.MapperFacade; import ma.glasnost.orika.impl.DefaultMapperFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.validation.Valid; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Optional; import java.util.stream.Collectors; @Service public class OfficeServiceImpl implements OfficeService{ @Autowired private OfficeRepository officeRepository; @Autowired private OrganizationRepository organizationRepository; private MapperFacade mapperFactory = new DefaultMapperFactory.Builder().build().getMapperFacade(); @Override public void add(@Valid OfficeItemView officeView) { Office office = mapperFactory.map(officeView, Office.class); Optional<Organization> optionalOrganization = organizationRepository.findById(officeView.organizationId); if (optionalOrganization.isPresent()) { office.addOrganization(optionalOrganization.get()); officeRepository.save(office); } else { throw new NoSuchElementException("Organization with id = " + officeView.organizationId + " can't be found"); } } @Override public void update(@Valid OfficeItemView officeView) { Optional<Office> optionalOffice = officeRepository.findById(officeView.id); if (optionalOffice.isPresent()) { Optional<Organization> optionalOrganization = organizationRepository.findById(officeView.organizationId); if (optionalOrganization.isPresent()) { Office office = optionalOffice.get(); office.setName(officeView.name); office.setAddress(officeView.address); office.setPhone(officeView.phone); if (null != officeView.isActive) office.setIsActive(officeView.isActive); office.removeOrganizations(office.getOrganizations()); office.addOrganization(optionalOrganization.get()); officeRepository.save(office); } else { throw new NoSuchElementException("Organization with id = " + officeView.organizationId + " can't be found"); } } else { throw new NoSuchElementException("Office with id = " + officeView.id + " can't be found"); } } @Override public OfficeItemView get(Long id) { Optional<Office> optionalOffice = officeRepository.findById(id); if (optionalOffice.isPresent()) { return mapperFactory.map(optionalOffice.get(), OfficeItemView.class); } else { throw new NoSuchElementException("Office with id = " + id + " can't be found"); } } @Override public List<OfficeListView> all() { List<Office> offices = officeRepository.findAll(); return offices.stream() .map(org -> mapperFactory.map(org, OfficeListView.class)) .collect(Collectors.toList()); } @Override public List<OfficeListView> getFilteredList(@Valid Filter<Office> filter) { return officeRepository.findAll(filter.getFilter()).stream() .map(office -> mapperFactory.map(office, OfficeListView.class)) .collect(Collectors.toList()); } }
true
bd9fb6d3d06f5fe6d947fd3bf2c490c30f09c9ad
Java
liberaljunior/LicentaNarcis
/app/src/main/java/com/narcis/neamtiu/licentanarcis/util/AudioFileHelper.java
UTF-8
1,445
2.453125
2
[]
no_license
package com.narcis.neamtiu.licentanarcis.util; import android.os.Build; import android.os.Environment; import androidx.annotation.RequiresApi; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class AudioFileHelper { @RequiresApi(api = Build.VERSION_CODES.R) public static String saveAudio() { int count = 0; String getPath = null; File sdDirectory = Environment.getStorageDirectory(); File subDirectory = new File(sdDirectory.toString() + "/Music/Record"); if(subDirectory.exists()) { File[] existing = subDirectory.listFiles(); for(File file : existing) { if(file.getName().endsWith(".3gp") || file.getName().endsWith(".mp3")) { count++; } } } else { subDirectory.mkdir(); } if(subDirectory.exists()) { File audio = new File(subDirectory, "/record_" + (count + 1) + ".3gp" ); FileOutputStream fileOutputStream; getPath = audio.getPath(); try { fileOutputStream = new FileOutputStream(audio); fileOutputStream.flush(); fileOutputStream.close(); } catch (FileNotFoundException e) { } catch (IOException e) { } } return getPath; } }
true
7b364da6cbc59363005e595eac4013f093ce2fb9
Java
linbin91/SQL
/app/src/main/java/com/felink/sql/User.java
UTF-8
563
2.171875
2
[]
no_license
package com.felink.sql; import com.felink.sql.sqlitecore.DbFiled; import com.felink.sql.sqlitecore.DbTable; /** * Created by Administrator on 2016/12/16. */ @DbTable("tb_user") public class User { @DbFiled("name") public String name; public String password; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
true
7733c40af47e6b523fc86c86439fb14bee4b7173
Java
Ametys/runtime
/test/src/org/ametys/runtime/test/users/jdbc/AbstractJdbcUsersTestCase.java
UTF-8
18,012
1.742188
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2009 Anyware Services_configureRuntime * * 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.ametys.runtime.test.users.jdbc; import java.io.FileInputStream; import java.io.InputStream; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import org.apache.commons.io.IOUtils; import org.ametys.core.user.InvalidModificationException; import org.ametys.core.user.User; import org.ametys.core.user.directory.ModifiableUserDirectory; import org.ametys.core.user.directory.UserDirectory; import org.ametys.core.user.directory.UserDirectoryFactory; import org.ametys.plugins.core.impl.user.directory.JdbcUserDirectory; import org.ametys.runtime.test.AbstractJDBCTestCase; import org.ametys.runtime.test.Init; /** * Tests JDBC user directory */ public abstract class AbstractJdbcUsersTestCase extends AbstractJDBCTestCase { /** the user manager */ protected UserDirectory _userDirectory; @Override protected void setUp() throws Exception { super.setUp(); _startApplication("test/environments/runtimes/runtime6.xml", "test/environments/configs/config1.xml", null, "test/environments/webapp1"); _userDirectory = _createUserDirectory(); } @Override protected void tearDown() throws Exception { _cocoon.dispose(); super.tearDown(); } private UserDirectory _createUserDirectory() throws Exception { String modelId = "org.ametys.plugins.core.user.directory.Jdbc"; Map<String, Object> parameters = new LinkedHashMap<>(); parameters.put("runtime.users.jdbc.datasource", "SQL-test"); parameters.put("runtime.users.jdbc.table", "Users"); return ((UserDirectoryFactory) Init.getPluginServiceManager().lookup(UserDirectoryFactory.ROLE)).createUserDirectory("foo", modelId, parameters, "foo", null); } @Override protected String[] _getStartScripts() throws Exception { String[] scripts = new String[2]; try (InputStream is = new FileInputStream("main/plugin-core/scripts/" + _getDBType() + "/jdbc_users.template.sql")) { scripts[0] = IOUtils.toString(is, "UTF-8"); scripts[0] = scripts[0].replaceAll("%TABLENAME%", "Users"); } try (InputStream is = new FileInputStream("main/plugin-core/scripts/" + _getDBType() + "/jdbc_groups.template.sql")) { scripts[1] = IOUtils.toString(is, "UTF-8"); scripts[1] = scripts[1].replaceAll("%TABLENAME%", "Groups"); scripts[1] = scripts[1].replaceAll("%TABLENAME_COMPOSITION%", "Groups_Users"); } return scripts; } /** * Test the getting of users on mysql * @throws Exception if an error occurs */ public void testType() throws Exception { // JDBC IMPL assertTrue(_userDirectory instanceof JdbcUserDirectory); // MODIFIABLE assertTrue(_userDirectory instanceof ModifiableUserDirectory); } /** * Test the addition of a new user that should failed * @throws Exception if an error occurs */ public void testIncorrectAdd() throws Exception { ModifiableUserDirectory modifiableUserDirectory = (ModifiableUserDirectory) _userDirectory; // Incorrect additions Map<String, String> userInformation; try { userInformation = new HashMap<>(); modifiableUserDirectory.add(userInformation); fail("An empty addition should fail"); } catch (InvalidModificationException e) { // normal behavior } try { userInformation = new HashMap<>(); userInformation.put("login", "test"); userInformation.put("firstname", "test"); modifiableUserDirectory.add(userInformation); fail("A non complete addition should fail"); } catch (InvalidModificationException e) { // normal behavior } try { userInformation = new HashMap<>(); userInformation.put("login", "test"); userInformation.put("firstname", "test"); userInformation.put("lastname", "test"); userInformation.put("email", ""); modifiableUserDirectory.add(userInformation); fail("A non complete addition should fail"); } catch (InvalidModificationException e) { // normal behavior } try { userInformation = new HashMap<>(); userInformation.put("login", "test"); userInformation.put("firstname", "test"); userInformation.put("lastname", "test"); userInformation.put("password", "test"); userInformation.put("email", "testthatisnotacorrectemail"); modifiableUserDirectory.add(userInformation); fail("An incorrect addition should fail"); } catch (InvalidModificationException e) { // normal behavior } } /** * Test the addition of a new user * @throws Exception if an error occurs */ public void testCorrectAdd() throws Exception { ModifiableUserDirectory modifiableUserDirectory = (ModifiableUserDirectory) _userDirectory; User user; // Correct additions Map<String, String> userInformation; userInformation = new HashMap<>(); userInformation.put("login", "test"); userInformation.put("firstname", "Test"); userInformation.put("lastname", "TEST"); userInformation.put("email", ""); userInformation.put("password", "testpassword"); modifiableUserDirectory.add(userInformation); assertTrue(_userDirectory.checkCredentials("test", "testpassword")); assertFalse(_userDirectory.checkCredentials("test", "wrongpassword")); assertFalse(_userDirectory.checkCredentials("test2", "testpassword")); userInformation = new HashMap<>(); userInformation.put("login", "test2"); userInformation.put("firstname", "Test2"); userInformation.put("lastname", "TEST2"); userInformation.put("email", "test2@test.te"); userInformation.put("password", "testpassword"); modifiableUserDirectory.add(userInformation); assertTrue(_userDirectory.checkCredentials("test", "testpassword")); assertFalse(_userDirectory.checkCredentials("test", "wrongpassword")); assertTrue(_userDirectory.checkCredentials("test2", "testpassword")); user = _userDirectory.getUser("test"); assertNotNull(user); assertEquals(user.getIdentity().getLogin(), "test"); assertEquals(user.getLastName(), "TEST"); assertEquals(user.getFirstName(), "Test"); assertEquals(user.getFullName(), "Test TEST"); assertEquals(user.getSortableName(), "TEST Test"); assertEquals(user.getEmail(), ""); user = _userDirectory.getUser("test2"); assertNotNull(user); assertEquals(user.getIdentity().getLogin(), "test2"); assertEquals(user.getLastName(), "TEST2"); assertEquals(user.getFirstName(), "Test2"); assertEquals(user.getFullName(), "Test2 TEST2"); assertEquals(user.getSortableName(), "TEST2 Test2"); assertEquals(user.getEmail(), "test2@test.te"); try { userInformation = new HashMap<>(); userInformation.put("login", "test"); userInformation.put("firstname", "Test"); userInformation.put("lastname", "TEST"); userInformation.put("email", ""); userInformation.put("password", "testpassword"); modifiableUserDirectory.add(userInformation); fail("Add should have failed"); } catch (InvalidModificationException e) { // normal behavior since login already exists } } /** * Test the update of a user incorrectly * @throws Exception if an error occurs */ public void testIncorrectUpdate() throws Exception { ModifiableUserDirectory modifiableUserDirectory = (ModifiableUserDirectory) _userDirectory; // Incorrect modification Map<String, String> userInformation; try { userInformation = new HashMap<>(); userInformation.put("login", "test"); userInformation.put("firstname", "Test"); userInformation.put("lastname", "TEST"); userInformation.put("email", ""); userInformation.put("password", "testpassword"); modifiableUserDirectory.update(userInformation); fail("Update should have failed"); } catch (InvalidModificationException e) { // normal behavior since login does not exist } userInformation = new HashMap<>(); userInformation.put("login", "test"); userInformation.put("firstname", "Test"); userInformation.put("lastname", "TEST"); userInformation.put("email", ""); userInformation.put("password", "testpassword"); modifiableUserDirectory.add(userInformation); try { userInformation = new HashMap<>(); userInformation.put("firstname", "Test"); userInformation.put("lastname", "TEST"); userInformation.put("email", ""); userInformation.put("password", "testpassword"); modifiableUserDirectory.update(userInformation); fail("Update should have failed"); } catch (InvalidModificationException e) { // normal behavior since no login is given } try { userInformation = new HashMap<>(); userInformation.put("login", "test"); userInformation.put("firstname", "Test"); userInformation.put("lastname", "TEST"); userInformation.put("email", "incorrectemail"); userInformation.put("password", "testpassword"); modifiableUserDirectory.update(userInformation); fail("Update should have failed"); } catch (InvalidModificationException e) { // normal behavior since email is incorrect } try { userInformation = new HashMap<>(); userInformation.put("login", "test"); userInformation.put("firstname", "Test"); userInformation.put("lastname", "TEST"); userInformation.put("password", ""); modifiableUserDirectory.update(userInformation); fail("Update should have failed"); } catch (InvalidModificationException e) { // normal behavior since password is empty } assertTrue(_userDirectory.checkCredentials("test", "testpassword")); assertFalse(_userDirectory.checkCredentials("test", "wrongpassword")); assertFalse(_userDirectory.checkCredentials("test2", "testpassword")); } /** * Test the update of a user * @throws Exception if an error occurs */ public void testCorrectUpdate() throws Exception { ModifiableUserDirectory modifiableUserDirectory = (ModifiableUserDirectory) _userDirectory; User user; Map<String, String> userInformation; userInformation = new HashMap<>(); userInformation.put("login", "test"); userInformation.put("firstname", "Test"); userInformation.put("lastname", "TEST"); userInformation.put("email", ""); userInformation.put("password", "testpassword"); modifiableUserDirectory.add(userInformation); // Correct modification userInformation = new HashMap<>(); userInformation.put("login", "test"); userInformation.put("firstname", "Testmodified"); userInformation.put("lastname", "TESTMODIFIED"); userInformation.put("email", "testModified@test.te"); userInformation.put("password", "testpassword2"); modifiableUserDirectory.update(userInformation); assertFalse(_userDirectory.checkCredentials("test", "testpassword")); assertTrue(_userDirectory.checkCredentials("test", "testpassword2")); user = _userDirectory.getUser("test"); assertNotNull(user); assertEquals(user.getIdentity().getLogin(), "test"); assertEquals(user.getLastName(), "TESTMODIFIED"); assertEquals(user.getFirstName(), "Testmodified"); assertEquals(user.getFullName(), "Testmodified TESTMODIFIED"); assertEquals(user.getSortableName(), "TESTMODIFIED Testmodified"); assertEquals(user.getEmail(), "testModified@test.te"); // partial modification (no password change) userInformation = new HashMap<>(); userInformation.put("login", "test"); userInformation.put("firstname", "Testmodifiedtwice"); modifiableUserDirectory.update(userInformation); assertFalse(_userDirectory.checkCredentials("test", "testpassword")); assertTrue(_userDirectory.checkCredentials("test", "testpassword2")); user = _userDirectory.getUser("test"); assertNotNull(user); assertEquals(user.getIdentity().getLogin(), "test"); assertEquals(user.getLastName(), "TESTMODIFIED"); assertEquals(user.getFirstName(), "Testmodifiedtwice"); assertEquals(user.getFullName(), "Testmodifiedtwice TESTMODIFIED"); assertEquals(user.getSortableName(), "TESTMODIFIED Testmodifiedtwice"); assertEquals(user.getEmail(), "testModified@test.te"); } /** * Test incorrects remove * @throws Exception if an error occurs */ public void testIncorrectRemove() throws Exception { ModifiableUserDirectory modifiableUserDirectory = (ModifiableUserDirectory) _userDirectory; try { modifiableUserDirectory.remove("foo"); fail("Remove should fail"); } catch (InvalidModificationException e) { // normal behavior } Map<String, String> userInformation; userInformation = new HashMap<>(); userInformation.put("login", "test"); userInformation.put("firstname", "Test"); userInformation.put("lastname", "TEST"); userInformation.put("password", "testpassword"); userInformation.put("email", ""); modifiableUserDirectory.add(userInformation); try { modifiableUserDirectory.remove("foo"); fail("Remove should fail"); } catch (InvalidModificationException e) { // normal behavior User user = _userDirectory.getUser("test"); assertNotNull(user); } userInformation = new HashMap<>(); userInformation.put("login", "test"); userInformation.put("firstname", "Testmodified"); userInformation.put("lastname", "TESTMODIFIED"); userInformation.put("email", "testModified@test.te"); userInformation.put("password", "testpassword2"); modifiableUserDirectory.update(userInformation); try { modifiableUserDirectory.remove("foo"); fail("Remove should fail"); } catch (InvalidModificationException e) { // normal behavior User user = _userDirectory.getUser("test"); assertNotNull(user); } assertTrue(_userDirectory.checkCredentials("test", "testpassword2")); } /** * Test corrects remove * @throws Exception if an error occurs */ public void testCorrectRemove() throws Exception { ModifiableUserDirectory modifiableUserDirectory = (ModifiableUserDirectory) _userDirectory; Map<String, String> userInformation; userInformation = new HashMap<>(); userInformation.put("login", "test"); userInformation.put("firstname", "Test"); userInformation.put("lastname", "TEST"); userInformation.put("email", ""); userInformation.put("password", "testpassword"); modifiableUserDirectory.add(userInformation); userInformation = new HashMap<>(); userInformation.put("login", "test2"); userInformation.put("firstname", "Test2"); userInformation.put("lastname", "TEST2"); userInformation.put("email", "email@email.ma"); userInformation.put("password", "test2password"); modifiableUserDirectory.add(userInformation); modifiableUserDirectory.remove("test"); assertFalse(_userDirectory.checkCredentials("test", "testpassword")); assertTrue(_userDirectory.checkCredentials("test2", "test2password")); User user = _userDirectory.getUser("test2"); assertNotNull(user); assertEquals(user.getIdentity().getLogin(), "test2"); assertEquals(user.getLastName(), "TEST2"); assertEquals(user.getFirstName(), "Test2"); assertEquals(user.getFullName(), "Test2 TEST2"); assertEquals(user.getSortableName(), "TEST2 Test2"); assertEquals(user.getEmail(), "email@email.ma"); } }
true
d5d0418d29d7408c98aeff6d4f49bc812f5a1ed6
Java
jasonbrianhall/Jaspersoft-Studio
/com.jaspersoft.studio/src/com/jaspersoft/studio/editor/gef/decorator/text/TextElementDecorator.java
UTF-8
1,569
2.5625
3
[]
no_license
/******************************************************************************* * Copyright (C) 2010 - 2016. TIBCO Software Inc. * All Rights Reserved. Confidential & Proprietary. ******************************************************************************/ package com.jaspersoft.studio.editor.gef.decorator.text; import com.jaspersoft.studio.editor.gef.decorator.IElementDecorator; import com.jaspersoft.studio.editor.gef.figures.ComponentFigure; import com.jaspersoft.studio.editor.gef.parts.FigureEditPart; /** * An element decorator that instances one and only one TextDecorator, that will be * used to paint strings on the figures * @author Orlandin Marco * */ public abstract class TextElementDecorator implements IElementDecorator { /** * Return the text decorator for the current figure if it was created before. * Otherwise first create a new text decorator and assign it to the figure, and * the it is returned * * @param figure the figure to check * @return a not null text decorator. It will a previously created old one * if available, otherwise a new one. */ protected TextDecorator getDecorator(ComponentFigure figure){ TextDecorator decorator = (TextDecorator)figure.getDecorator(TextDecorator.class); if (decorator == null) { decorator = new TextDecorator(); figure.addDecoratorOnce(decorator); } return decorator; } /** * Add the text decorator to the figure if it isn't already present */ @Override public void setupFigure(ComponentFigure fig, FigureEditPart editPart) { getDecorator(fig); } }
true
c42629b9b45495468f94c77a9d0b7200623d6a9a
Java
1gram4/Chemiety
/backend/src/main/java/cn/kastner/chemiety/domain/User.java
UTF-8
2,224
2.296875
2
[ "MIT" ]
permissive
package cn.kastner.chemiety.domain; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.hibernate.annotations.LazyCollection; import org.hibernate.annotations.LazyCollectionOption; import javax.persistence.*; import java.util.List; import java.util.Set; @Entity @Table(name = "user") public class User { public static final String CUR_USER = "currentUser"; public List<Post> getPosts() { return posts; } public void setPosts(List<Post> posts) { this.posts = posts; } public String getName() { return name; } public void setName(String name) { this.name = name; } public enum Role { TEACHER, STUDENT } public Role getRoles() { return roles; } public void setRoles(Role roles) { this.roles = roles; } public enum Gender { MALE, FEMALE } public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long userId; private String username; @JsonIgnore @Column(columnDefinition = "TEXT") private String password; private Gender gender; private Role roles; private String name; @OneToMany @LazyCollection(LazyCollectionOption.FALSE) private List<Post> posts; public User () { } public User (String name, String password) { this.username = name; this.password = password; } public User (String name) { this.roles = Role.STUDENT; this.gender = Gender.MALE; this.name = name; } }
true
52a8ed4856e95fae70ccaccacf3a469b5456c52f
Java
jcna15/project-selenium-webdriver-cucumber
/src/test/java/com/company/projectwebdriver/redmine/RedmineProjectTest.java
UTF-8
1,230
2.203125
2
[]
no_license
package com.company.projectwebdriver.redmine; import com.company.projectwebdriver.base.BaseTest; import com.company.projectwebdriver.model.RedmineProject; import com.company.projectwebdriver.pages.RedmineHomePage; import com.company.projectwebdriver.pages.RedmineProjectsPage; import com.company.projectwebdriver.utils.Util; import org.junit.Test; public class RedmineProjectTest extends BaseTest { @Test public void testCreateProjectRedmine() { RedmineHomePage redmineHomePage = redmineLoginPage.login("jnavarro", "jnavarro"); RedmineProjectsPage redmineProjectsPage = redmineHomePage.clickOnLink("Projects"); String number = Util.generateRandomNumber(); RedmineProject redmineProject = new RedmineProject(); redmineProject.setName("RedmineProjectName" + number); redmineProject.setDescription("Esta es una descripción de prueba" + number); redmineProject.setHomePage("RedmineProjectName" + number); redmineProject.setPublic(true); redmineProjectsPage.createProject(redmineProject); //assertEquals("Successful creation.", redmineProjectsPage.getUIMessage(), "The message is not correct"); //System.out.println(""); } }
true
e6cd6114f551cd44df31217a859c82aa352f56d6
Java
rdorrity/Sea-Otter-Survey
/app/src/main/java/com/example/seaottersurvey/MainActivity.java
UTF-8
1,474
2.03125
2
[]
no_license
package com.example.seaottersurvey; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import com.backendless.Backendless; import com.backendless.async.callback.AsyncCallback; import com.backendless.exceptions.BackendlessFault; public class MainActivity extends AppCompatActivity { TextView tvDescription, tvQuestion, tvQ1; RadioGroup rbG1; RadioButton rb1, rb2, rb3, rb4; Button btnSubmit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvDescription = findViewById(R.id.tvDescription); tvQuestion = findViewById(R.id.tvQuestion); tvQ1 = findViewById(R.id.tvQ1); rbG1= findViewById(R.id.rbG1); rb1 = findViewById(R.id.rb1); rb2 = findViewById(R.id.rb2); rb3 = findViewById(R.id.rb3); rb4 = findViewById(R.id.rb4); btnSubmit = findViewById(R.id.btnSubmit); btnSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "Thank you for your feedback!", Toast.LENGTH_SHORT).show(); } }); } }
true
d15df2a0006355071447f4e0e6dec1f910c384a5
Java
PanSiad/java-databases
/src/main/java/h_inheritance/joinedtable/Fish.java
UTF-8
362
2.734375
3
[]
no_license
package h_inheritance.joinedtable; import javax.persistence.Entity; import javax.persistence.PrimaryKeyJoinColumn; @Entity @PrimaryKeyJoinColumn(name = "petId") public class Fish extends Animal{ private String color; public String getColor() { return color; } public void setColor(String color) { this.color = color; } }
true
7bc03359f5dd14b871235ba2d42553b93d8a7e1f
Java
kojoYeboah53i/expo
/android/versioned-abis/expoview-abi37_0_0/src/main/java/abi37_0_0/expo/modules/cellular/CellularModule.java
UTF-8
3,903
2.078125
2
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
permissive
package abi37_0_0.expo.modules.cellular; import java.util.HashMap; import java.util.Map; import android.content.Context; import android.content.pm.PackageManager; import android.net.sip.SipManager; import android.telephony.TelephonyManager; import abi37_0_0.org.unimodules.core.ExportedModule; import abi37_0_0.org.unimodules.core.ModuleRegistry; import abi37_0_0.org.unimodules.core.Promise; import abi37_0_0.org.unimodules.core.interfaces.ExpoMethod; import abi37_0_0.org.unimodules.core.interfaces.RegistryLifecycleListener; public class CellularModule extends ExportedModule implements RegistryLifecycleListener { private static final String NAME = "ExpoCellular"; private static final String TAG = CellularModule.class.getSimpleName(); private ModuleRegistry mModuleRegistry; private Context mContext; public CellularModule(Context context) { super(context); mContext = context; } public enum CellularGeneration { UNKNOWN(0), CG_2G(1), CG_3G(2), CG_4G(3); private final int value; CellularGeneration(int value) { this.value = value; } public int getValue() { return value; } } @Override public String getName() { return NAME; } @Override public void onCreate(ModuleRegistry moduleRegistry) { mModuleRegistry = moduleRegistry; } @Override public Map<String, Object> getConstants() { HashMap<String, Object> constants = new HashMap<>(); constants.put("allowsVoip", SipManager.isVoipSupported(mContext)); TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); constants.put("isoCountryCode", tm != null ? tm.getSimCountryIso() : null); //check if sim state is ready if (tm != null && tm.getSimState() == TelephonyManager.SIM_STATE_READY) { constants.put("carrier", tm.getSimOperatorName()); String combo = tm.getSimOperator(); constants.put("mobileCountryCode", combo != null ? combo.substring(0, 3) : null); StringBuilder sb = null; if (combo != null) { sb = new StringBuilder(combo); sb.delete(0, 3); } constants.put("mobileNetworkCode", sb != null ? sb.toString() : null); } else { constants.put("carrier", null); constants.put("mobileCountryCode", null); constants.put("mobileNetworkCode", null); } return constants; } @ExpoMethod public void getCellularGenerationAsync(Promise promise) { try { TelephonyManager mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); int networkType = mTelephonyManager.getNetworkType(); switch (networkType) { case TelephonyManager.NETWORK_TYPE_GPRS: case TelephonyManager.NETWORK_TYPE_EDGE: case TelephonyManager.NETWORK_TYPE_CDMA: case TelephonyManager.NETWORK_TYPE_1xRTT: case TelephonyManager.NETWORK_TYPE_IDEN: promise.resolve(CellularGeneration.CG_2G.getValue()); case TelephonyManager.NETWORK_TYPE_UMTS: case TelephonyManager.NETWORK_TYPE_EVDO_0: case TelephonyManager.NETWORK_TYPE_EVDO_A: case TelephonyManager.NETWORK_TYPE_HSDPA: case TelephonyManager.NETWORK_TYPE_HSUPA: case TelephonyManager.NETWORK_TYPE_HSPA: case TelephonyManager.NETWORK_TYPE_EVDO_B: case TelephonyManager.NETWORK_TYPE_EHRPD: case TelephonyManager.NETWORK_TYPE_HSPAP: promise.resolve(CellularGeneration.CG_3G.getValue()); case TelephonyManager.NETWORK_TYPE_LTE: promise.resolve(CellularGeneration.CG_4G.getValue()); default: promise.resolve(CellularGeneration.UNKNOWN.getValue()); } } catch (Exception e) { promise.reject("ERR_CELLULAR_GENERATION_UNKNOWN_NETWORK_TYPE", "Unable to access network type or not connected to a cellular network", e); } } }
true
9592e88b4f51ddcf0c42d5a00a3901d5ec523dfd
Java
yonhbu/Java
/The-Beginning/basic-exercises/src/main/java/com/co/vectores/Practica6.java
UTF-8
899
4
4
[]
no_license
package com.co.vectores; import java.util.Scanner; public class Practica6 { public static void main(String[] args) { // Determinar el orden de un arreglo int [] vector = new int [5]; Scanner sc = new Scanner (System.in); boolean a = false; boolean b = false; for (int i = 0; i < vector.length; i++) { System.out.println(" Ingrese valor " + ( i + 1) + " " ); vector[i] = sc.nextInt(); } for (int x = 0; x < vector.length - 1; x++) { if (vector[x] < vector[x + 1]) { a = true; }else if (vector[x] > vector[x + 1]) { b = true; } } if (a == true && b == false) { System.out.println("Numeros en Forma Ascendente"); }else if (a == false && b == true) { System.out.println("Numeros en Forma Descendente"); }else if (a && b) { System.out.println("Numeros en Forma Desordenada"); } } }
true
f69ac361eda01b6c6b6f9679af9aabc92dcd6abc
Java
prathamk22/Image-Loader-MVVM
/app/src/main/java/com/example/task2/Paging/ImagedataSourceFactory.java
UTF-8
966
2.3125
2
[]
no_license
package com.example.task2.Paging; import android.app.Application; import androidx.lifecycle.MutableLiveData; import androidx.paging.DataSource; import com.example.task2.PhotoObservable; import com.example.task2.Retrofit.RetrofitApi; public class ImagedataSourceFactory extends DataSource.Factory { private ImageDataSource dataSource; private RetrofitApi api; private Application application; private MutableLiveData<ImageDataSource> mutableLiveData; public ImagedataSourceFactory(RetrofitApi api, Application application) { this.api = api; this.application = application; mutableLiveData = new MutableLiveData<>(); } @Override public DataSource create() { dataSource = new ImageDataSource(api,application); mutableLiveData.postValue(dataSource); return dataSource; } public MutableLiveData<ImageDataSource> getMutableLiveData() { return mutableLiveData; } }
true
745d18a772cfda267920dde70e610ff0fc2410aa
Java
jongvin/werp
/werp/WEB-INF/classes/werpclass/hash/HashReturn.java
UTF-8
2,032
2.75
3
[]
no_license
package hash; import java.io.FileInputStream; import java.security.DigestInputStream; import java.security.MessageDigest; public class HashReturn { private static final char[] S_BASE64CHAR = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; private static final char S_BASE64PAD = '='; /** * Returns base64 representation of specified byte array. */ public static String encode(byte[] data, int off, int len) { if (len <= 0) return ""; char[] out = new char[len/3*4+4]; int rindex = off; int windex = 0; int rest = len-off; while (rest >= 3) { int i = ((data[rindex]&0xff)<<16) +((data[rindex+1]&0xff)<<8) +(data[rindex+2]&0xff); out[windex++] = S_BASE64CHAR[i>>18]; out[windex++] = S_BASE64CHAR[(i>>12)&0x3f]; out[windex++] = S_BASE64CHAR[(i>>6)&0x3f]; out[windex++] = S_BASE64CHAR[i&0x3f]; rindex += 3; rest -= 3; } if (rest == 1) { int i = data[rindex]&0xff; out[windex++] = S_BASE64CHAR[i>>2]; out[windex++] = S_BASE64CHAR[(i<<4)&0x3f]; out[windex++] = S_BASE64PAD; out[windex++] = S_BASE64PAD; } else if (rest == 2) { int i = ((data[rindex]&0xff)<<8)+(data[rindex+1]&0xff); out[windex++] = S_BASE64CHAR[i>>10]; out[windex++] = S_BASE64CHAR[(i>>4)&0x3f]; out[windex++] = S_BASE64CHAR[(i<<2)&0x3f]; out[windex++] = S_BASE64PAD; } return new String(out, 0, windex); } public static String getHashFile(String fileName) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA1") ; DigestInputStream in = new DigestInputStream(new FileInputStream(fileName), md) ; byte[] buffer = new byte[8192]; while ( in.read(buffer) != -1) ; byte[] raw = md.digest(); return encode(raw,0,raw.length) ; } }
true
a1844f7e256f0dfc2ec6996b17a3f2c5fca5a950
Java
team-dech/CustomCapes
/src/minecraft/dechmods/customcapes/server/CCServerHandler.java
UTF-8
1,360
2.359375
2
[]
no_license
package dechmods.customcapes.server; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.util.Arrays; import java.util.HashMap; import cpw.mods.fml.common.network.PacketDispatcher; import net.minecraft.server.MinecraftServer; public class CCServerHandler { public static HashMap<String, String> capes = new HashMap<String, String>(); public static void refreshCape(String username) { ByteArrayOutputStream outputBytes = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(outputBytes); try { outputStream.writeUTF(username); outputStream.writeUTF(capes.get(username)); PacketDispatcher.sendPacketToAllPlayers(PacketDispatcher.getPacket("REFRESHCAPE", outputBytes.toByteArray())); } catch (Exception e) { } } public static void sendAllCapes(String username) { // TODO Auto-generated method stub } public static void loadCapes() { // TODO Auto-generated method stub } public static void saveCapes() { // TODO Auto-generated method stub } public static boolean doesPlayerExist(String name) { return Arrays.asList(MinecraftServer.getServer().getAllUsernames()).contains(name); } }
true
465a03b7025f40799f5a1c1cfad22cf5e2e45b96
Java
helloconch/Android
/app/src/main/java/com/android/rxretrofit/RxRetrofitActivity.java
UTF-8
5,918
2.390625
2
[]
no_license
package com.android.rxretrofit; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import android.widget.Toast; import com.android.rxretrofit.api.HttpMethods; import com.android.rxretrofit.api.MovieService; import com.android.rxretrofit.api.ProgressSubscriber; import com.android.rxretrofit.api.SubscriberOnNextListener; import com.android.rxretrofit.entity.HttpResult; import com.android.rxretrofit.entity.Subject; import com.android.testing.R; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import rx.Observable; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Created by Administrator on 2016/9/7. */ public class RxRetrofitActivity extends AppCompatActivity { @BindView(R.id.result) TextView result; SubscriberOnNextListener<List<Subject>> subscriberOnNextListener; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rx_retrofit); ButterKnife.bind(this); } @OnClick(R.id.click) public void onClick() { // goMovieByCall(); // goMovieByObservable(); // goMovieByObservalble2(); // goMovieByObserver3(); goMovieByObserver4(); } /** * retrofit */ private void goMovieByCall() { Retrofit retrofit = new Retrofit.Builder().baseUrl(MovieService.baseUrl) .addConverterFactory(GsonConverterFactory.create()) .build(); MovieService movieService = retrofit.create(MovieService.class); Call<HttpResult<List<Subject>>> call = movieService.getTopMovieByCall(0, 10); call.enqueue(new Callback<HttpResult<List<Subject>>>() { @Override public void onResponse(Call<HttpResult<List<Subject>>> call, Response<HttpResult<List<Subject>>> response) { result.setText(response.body().toString()); } @Override public void onFailure(Call<HttpResult<List<Subject>>> call, Throwable t) { result.setText(t.getMessage()); } }); } /** * rxjava+retrofit */ private void goMovieByObservable() { Retrofit retrofit = new Retrofit.Builder().baseUrl(MovieService.baseUrl) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); MovieService movieService = retrofit.create(MovieService.class); Observable<HttpResult<List<Subject>>> observable = movieService.getTopMovieByObservable(0, 10); observable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<HttpResult<List<Subject>>>() { @Override public void onCompleted() { Toast.makeText(RxRetrofitActivity.this, "Get Top Movie Completed", Toast.LENGTH_SHORT).show(); } @Override public void onError(Throwable e) { result.setText(e.getMessage()); } @Override public void onNext(HttpResult<List<Subject>> listHttpResult) { result.setText(listHttpResult.toString()); } }); } /** * 采用单例模式访问对请求形式进行封装 */ private void goMovieByObservalble2() { Subscriber<HttpResult<List<Subject>>> subscriber = new Subscriber<HttpResult<List<Subject>>>() { @Override public void onCompleted() { Toast.makeText(RxRetrofitActivity.this, "Get Top Movie Completed", Toast.LENGTH_SHORT).show(); } @Override public void onError(Throwable e) { result.setText(e.getMessage()); } @Override public void onNext(HttpResult<List<Subject>> listHttpResult) { result.setText(listHttpResult.toString()); } }; HttpMethods.getInstance().getTopMovie(subscriber, 0, 10); } private void goMovieByObserver3() { Subscriber<List<Subject>> subscriber = new Subscriber<List<Subject>>() { @Override public void onCompleted() { Toast.makeText(RxRetrofitActivity.this, "Get Top Movie Completed", Toast.LENGTH_SHORT).show(); } @Override public void onError(Throwable e) { result.setText(e.getMessage()); } @Override public void onNext(List<Subject> subjects) { result.setText(subjects.toString()); } }; HttpMethods.getInstance().getTopMovies(subscriber, 0, 10); //解除请求 // subscriber.unsubscribe(); } /** * 添加加载进度开始 结束或者取消 */ private void goMovieByObserver4() { subscriberOnNextListener = new SubscriberOnNextListener<List<Subject>>() { @Override public void onNext(List<Subject> subjects) { //处理真正返回的数据 } }; ProgressSubscriber<List<Subject>> subscriber = new ProgressSubscriber<>(subscriberOnNextListener, this); HttpMethods.getInstance().getTopMovies(subscriber, 0, 10); } }
true
7c1addec6665d23dbc7a0e58f62777b3dac099cf
Java
surelogic/regression
/regression/TestIntrinsicLockAnalysis/src/test_selfProtected/C.java
UTF-8
157
2.140625
2
[]
no_license
package test_selfProtected; /** * Says nothing about being "self protected" (so it isn't) */ public class C { public void m() { // do nothing } }
true
149b9101d7c6a5d6711c9949752f199239fdd4f2
Java
k0bolde/Cosmic
/src/cosmic/core/CosmicScreen.java
UTF-8
5,838
2.390625
2
[]
no_license
package cosmic.core; import java.util.Random; import java.util.Vector; import com.jme3.app.Application; import com.jme3.app.SimpleApplication; import com.jme3.app.state.AbstractAppState; import com.jme3.app.state.AppStateManager; import com.jme3.input.KeyInput; import com.jme3.input.MouseInput; import com.jme3.input.controls.KeyTrigger; import com.jme3.input.controls.MouseAxisTrigger; import com.jme3.input.controls.MouseButtonTrigger; import com.jme3.math.Vector3f; import cosmic.message.CreateMessage; import cosmic.object.Builder; import cosmic.object.Delay; import cosmic.object.RelayNode; import cosmic.object.Unit; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.controls.DropDown; import de.lessvoid.nifty.controls.TextField; import de.lessvoid.nifty.elements.Element; import de.lessvoid.nifty.elements.render.TextRenderer; import de.lessvoid.nifty.screen.Screen; import de.lessvoid.nifty.screen.ScreenController; public class CosmicScreen extends AbstractAppState implements ScreenController { private Nifty nifty; private Screen screen; private SimpleApplication app; private boolean join = false; Player player; DropDown<String> players; public CosmicScreen(Player player) { /* get a reference to player */ this.player = player; } @Override public void bind(Nifty nifty, Screen screen) { this.nifty = nifty; this.screen = screen; /* populate dropdown menu */ players = screen.findNiftyControl("players", DropDown.class); players.addItem("2"); players.addItem("3"); players.addItem("4"); players.addItem("5"); players.addItem("6"); /* populate port field */ TextField port = screen.findNiftyControl("Port", TextField.class); port.setText("Default Port"); } @Override public void onEndScreen() { } @Override public void onStartScreen() { } @Override public void initialize(AppStateManager stateManager, Application app) { super.initialize(stateManager, app); this.app=(SimpleApplication)app; } @Override public void update(float tpf) { } @SuppressWarnings("deprecation") public void startGame() { /* get the player selection */ String tempPlayers = players.getSelection(); /* get the port */ TextField port = screen.findNiftyControl("Port", TextField.class); String tempPort = port.getText(); if(tempPort.contentEquals("Default Port")) { tempPort = "3333"; } /* remove the main menu and load the HUD */ nifty.gotoScreen("hud"); /* create a server */ player.startGame(tempPlayers, tempPort, true); } @SuppressWarnings("deprecation") public void joinGame() { if(!join) { /* load the join screen */ nifty.gotoScreen("join"); TextField port = screen.findNiftyControl("PortJoin", TextField.class); port.setText("Default Port"); join = true; } else { /* get the IP/Hostname and try to join */ TextField IP = screen.findNiftyControl("IPText", TextField.class); TextField port = screen.findNiftyControl("PortJoin", TextField.class); String tempPort = port.getText(); if(tempPort.contentEquals("Default Port")) { tempPort = "3333"; } nifty.gotoScreen("hud"); player.startGame(IP.getText(), tempPort, false); } } public void createUnit(String type) { /* create a single unit around the current target */ Builder u = (Builder) player.cosmicCam.curTarget; //don't create it if we can't //if(!u.canBuild) return; if(player.gameState.unitCost.get(type) != null){ player.resources -= player.gameState.unitCost.get(type); //System.out.println(player.resources); if(player.resources < 0 || u.buildQueue.size()>=6){ //set a queue limit of 5 player.resources += player.gameState.unitCost.get(type); return; } } //System.out.println(player.resources); //create a delay with {player_id, pos, creator unit, unit type} //player.sendMessage(new CreateMessage(player.player_id, id, pos)); Vector<Object> data = new Vector<Object>(); data.add(player.player_id); data.add(u); data.add(type); //u.canBuild = false; float dist = u.getWorldTranslation().distance(player.mothership.pos)/75; for(RelayNode relay : player.gameState.relays){ float d = u.getWorldTranslation().distance(relay.pos)/35; if(d<dist){ dist = d; } } Delay d = new Delay("build",player.gameState.unitTimeCost.get(type) + dist,data); //player.commands.add(d); u.buildQueue.add(d); nifty.getCurrentScreen().findElementByName("resources").getRenderer(TextRenderer.class).setText("Resources: "+player.resources); } public void createHint(String type,String unit){ //System.out.println("creating hint: " +type); nifty.getCurrentScreen().findElementByName(type).setVisible(true); } public void deactivateHint(String type){ //System.out.println("removing hint: " + type); nifty.getCurrentScreen().findElementByName(type).hide(); //System.out.println("wtf"); } public int getResources(){ return player.resources; } public int getMaxResources(){ return player.maxResources; } public void resume() { /* return to the correct HUD */ if (player.cosmicCam.mothership) { nifty.gotoScreen("mother"); }else if(player.cosmicCam.factory){ nifty.gotoScreen("factory"); } else { nifty.gotoScreen("hud"); } /* re-enable controls */ player.cosmicCam.setMappings(); player.cosmicCam.inMenu = false; } public void back() { /* return to the main menu */ join = false; nifty.exit(); nifty.fromXml("assets/Interface/screen.xml", "main", this); } public void quitGame() { /* quit */ player.stop(); } }
true
6067080a1a1a2ba54362743bbee2f32c4b1fe226
Java
CodecoolKRK20173/expert-system-selene-kuba
/src/com/codecool/expert/MultipleValue.java
UTF-8
250
2.140625
2
[]
no_license
package com.codecool.expert; import java.util.List; class MultipleValue extends Value { public MultipleValue(List<String> params, boolean selectionType) { this.selectionType = selectionType; inputPattern.addAll(params); } }
true
2bcc11b3caa7ed94003f39a9f7bb00a2ad479584
Java
debeach/STG-Hackathon-16-17
/src/main/java/com/stg/danbeach/practice/framework/page/SnowPage.java
UTF-8
681
2.25
2
[]
no_license
package com.stg.danbeach.practice.framework.page; import com.stg.danbeach.practice.framework.browser.Browser; public class SnowPage implements iPage { public static final String pageName = "Resorts & Snow"; private static final String title = "Utah Snow Report - Snow Totals at Utah Ski Resorts - Ski Utah"; private static final String idTitle = "Utah Snow Report"; private static final String url = "https://www.skiutah.com/snowreport"; @Override public void goTo() { Browser.goTo(url); } @Override public boolean isAt() { return Browser.title().equals(title); } @Override public boolean isIdTitle() { return Browser.title().indexOf(idTitle) > -1; } }
true
dbe36023d27631000679d70a2f558c21359cab67
Java
doctor-kaliy/java-advanced
/java-solutions/info/kgeorgiy/ja/kosogorov/bank/Server.java
UTF-8
2,346
2.671875
3
[]
no_license
package info.kgeorgiy.ja.kosogorov.bank; import java.rmi.*; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.*; import java.net.*; public final class Server implements RemoteServer { private final static int DEFAULT_PORT = 8888; private final int port; public Server(int port) throws RemoteException { this.port = port; LocateRegistry.createRegistry(Registry.REGISTRY_PORT); } public static void main(final String... args) { if (args == null || args.length > 2) { System.out.println("Wrong number of arguments. Expected from 0 to 2."); return; } int port = DEFAULT_PORT; if (args.length > 0) { try { port = Integer.parseInt(args[args.length - 1]); } catch (NumberFormatException exception) { System.out.println("Using default port: " + DEFAULT_PORT); } } try { final RemoteServer server = new Server(port); try { UnicastRemoteObject.exportObject(server, port); Naming.rebind("//localhost/server", server); System.out.println("Server started"); if (args.length >= 1 && "--bind-bank".equals(args[0])) { server.bindBank(); } } catch (final RemoteException e) { System.out.println("Cannot export server: " + e.getMessage()); e.printStackTrace(); System.exit(1); } catch (final MalformedURLException e) { System.out.println("Malformed URL"); } } catch (RemoteException e) { System.out.println("Cannot create RMI registry: " + e.getMessage()); } } @Override public void bindBank() throws RemoteException { try { Naming.rebind("//localhost/bank", createBank()); } catch (MalformedURLException e) { System.out.println("Malformed URL"); } } @Override public Bank createBank() throws RemoteException { final Bank bank = new RemoteBank(port); UnicastRemoteObject.exportObject(bank, port); return bank; } }
true
d2b552b2f9e442bf85862c16c33dbe658123dbfd
Java
Dennisluiten/App-lab-i-Pedometer
/iPedometer/app/src/main/java/iPedometer3/TimedMessage.java
UTF-8
610
2.5
2
[]
no_license
package iPedometer3; import android.content.Intent; import com.example.erikeppenhof.myapplication.NotificationActivity; /** * A persuasive message and the time that it needs to be send / has been send. * * Created by Hans-Christiaan on 26-5-2015. */ public class TimedMessage { private long time; private PersuasiveMessage message; public TimedMessage(long time, PersuasiveMessage message) { this.time = time; this.message = message; } public long getTime() { return time; } public PersuasiveMessage getMessage() { return message; } }
true
df26e4478cfe8d2a2736d6a9763b279566460fd5
Java
flashmonkey/flashmonkey
/java/server/core/src/org/flashmonkey/java/input/api/IInput.java
UTF-8
1,410
1.960938
2
[]
no_license
package org.flashmonkey.java.input.api; import org.red5.io.amf3.IExternalizable; public interface IInput extends IExternalizable { public boolean getMoveForward(); public void setMoveForward(boolean forward); public boolean getMoveBackward(); public void setMoveBackward(boolean backward); public boolean getMoveRight(); public void setMoveRight(boolean right); public boolean getMoveLeft(); public void setMoveLeft(boolean left); public boolean getMoveUp(); public void setMoveUp(boolean up); public boolean getMoveDown(); public void setMoveDown(boolean down); public boolean getPitchPositive(); public void setPitchPositive(boolean pitchPositive); public boolean getPitchNegative(); public void setPitchNegative(boolean pitchNegative); public boolean getRollPositive(); public void setRollPositive(boolean rollPositive); public boolean getRollNegative(); public void setRollNegative(boolean rollNegative); public boolean getYawPositive(); public void setYawPositive(boolean yawPositive); public boolean getYawNegative(); public void setYawNegative(boolean yawNegative); public boolean getFire(); public void setFire(boolean fire); public boolean getJump(); public void setJump(boolean jump); public float getMouseX(); public void setMouseX(float mouseX); public float getMouseY(); public void setMouseY(float mouseY); }
true
8547ab9fede6f36645ee6fb41fc20e1f96470e92
Java
BartekJan/Tasker
/Tasker/src/Actions.java
UTF-8
3,770
3.078125
3
[]
no_license
public class Actions { private DatabaseManager db = new DatabaseManager(); private TaskManLogin taskerLogin; private String startdate = ""; private String enddate = ""; private String status = ""; private String element = ""; private String comments = ""; /** * This method will test if the * email is a valid email address * and check if the email and password * is in the database * @param email * @param password * @return A message that says if if was succeeded or not */ public String loginTest(String email, String password) { if (checkEmail(email)) { if (db.loginDetails(email, password)) { // Valid email and password. User is now logged in return "Valid email and password"; } else { return "Wrong email or password"; } } else { // print error return "Please enter a valid email address"; } } /** * This method will check if the email * is built up as an email * * This function was not written by any of us. * The function was found at: * http://stackoverflow.com/questions/624581/what-is-the-best-java-email-address-validation-method * 28.01.2016 * Post written by Pujan Srivastava (17.04.13) * * @param email * @return true or false */ private boolean checkEmail(String email) { String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$"; java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern); java.util.regex.Matcher m = p.matcher(email); return m.matches(); } /** * Calls the database manager to get * all the info about one specific task * Puts all the information in variables * @param taskTitle */ public void getTaskInfo(String taskTitle) { String[] allInfo = db.getAllTaskInfo(taskTitle); startdate = allInfo[0]; enddate = allInfo[1]; status = allInfo[2]; element = allInfo[3]; comments = allInfo[4]; } /** * Startdate of task * @return startdate */ public String getStartDate() { return startdate; } /** * End date of task * @return enddate */ public String getEndDate() { return enddate; } /** * Status of task * @return status */ public String getStatus() { return status; } /** * Element of task * @return element */ public String getElement() { return element; } /** * Comments of task * @return comments */ public String getComments() { return comments; } /** * Returns the name of the member * when email is provided * @param memberEmail * @return Name of member */ public String getName(String memberEmail) { return db.getName(memberEmail); } /** * Gives all the titles of all the tasks * allocated to that user * @return array of titles */ public String[] getAllUserTaskTitles() { return db.getAllUserTaskTitles(); } /** * runs the login screen * @param taskObject */ public void runLogin(Tasker taskObject) { taskObject.runLogin(); } /** * Saves a comment in the database * @param taskName * @param memberEmail * @param comment */ public void saveComment(String taskName, String memberEmail, String comment) { db.saveComment(taskName, memberEmail, comment); } /** * Changes a status in the database * @param taskName * @param status */ public void changeStatus(String taskName, int status) { db.changeStatus(taskName, status+1); } /** * Liks the databasemanager to a new database * @param url * @param user * @param password * @param port * @param databaseName */ public void setNewDatabase(String url, String user, String password, String port, String databaseName) { db.setNewDatabase(url, user, password, port, databaseName); } }
true
4ea78060b4ac2f22704c076cd81f8c1ae3bb322b
Java
inoDevlog/Java
/javajungsuk3/src/ch7/InterfaceTest2.java
UTF-8
523
3.6875
4
[]
no_license
package ch7; class AA { void autoPlay(I i) { i.play(); } } interface I { public abstract void play(); } class BB implements I { public void play() { System.out.println("play in B class"); } } class CC implements I { public void play() { System.out.println("play in C class"); } } class InterfaceTest2 { public static void main(String[] args) { AA aa = new AA(); aa.autoPlay(new BB()); // void autoPlay(I i) call aa.autoPlay(new CC()); // void autoPlay(I i) call } }
true
f9378de05e01e456e3829a07232e82faa3d2d237
Java
jtrent238/jtcraft
/com.jtrent238.jtcraft/src/main/java/aek.java
UTF-8
816
1.546875
2
[]
no_license
/* */ /* */ /* */ public class aek /* */ extends abh /* */ { /* */ public aek(aji paramaji) /* */ { /* 8 */ super(paramaji); /* */ /* 10 */ f(0); /* 11 */ a(true); /* */ } /* */ /* */ public rf b_(int paramInt) /* */ { /* 16 */ return this.a.b(2, aka.b(paramInt)); /* */ } /* */ /* */ public int a(int paramInt) /* */ { /* 21 */ return paramInt; /* */ } /* */ /* */ public String a(add paramadd) /* */ { /* 26 */ return super.a() + "." + acj.a[aka.b(paramadd.k())]; /* */ } /* */ } /* Location: C:\Users\trent\.gradle\caches\minecraft\net\minecraft\minecraft\1.7.10\minecraft-1.7.10.jar!\aek.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
0664c2bf14c47c36d93731d64d27269409dea0c1
Java
raissacosa/awbd
/src/main/java/com/example/demo/repositories/MovieRepository.java
UTF-8
580
2.09375
2
[]
no_license
package com.example.demo.repositories; import com.example.demo.domain.Cinema; import com.example.demo.domain.Movie; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.query.Param; import java.util.List; public interface MovieRepository extends JpaRepository<Movie, Long> { @Query("select m from Movie m where m.name = :name") List<Movie> findByMovieName(@Param("name") String movieName); }
true
fa2eefb5c9b7340b355e40fc7472ec8a94a447b2
Java
jlsulcag/ProjectSIGA
/SIGA/src/java/org/siga/be/PedidoSeguimiento.java
UTF-8
1,980
1.890625
2
[]
no_license
package org.siga.be; // Generated 03/11/2017 11:21:41 AM by Hibernate Tools 4.3.1 import java.util.Date; import org.springframework.stereotype.Component; /** * PedidoSeguimiento generated by hbm2java */ @Component public class PedidoSeguimiento implements java.io.Serializable { private long idpedidoseguimiento; private Pedido pedido; private PedidoEstados estado; private Date fecha; private String hora; private String observacion; private int numero; private long idUser; public PedidoSeguimiento() { this.idpedidoseguimiento = 0; this.pedido = new Pedido(); this.estado = new PedidoEstados(); } public long getIdpedidoseguimiento() { return this.idpedidoseguimiento; } public void setIdpedidoseguimiento(long idpedidoseguimiento) { this.idpedidoseguimiento = idpedidoseguimiento; } public Pedido getPedido() { return this.pedido; } public void setPedido(Pedido pedido) { this.pedido = pedido; } public Date getFecha() { return this.fecha; } public void setFecha(Date fecha) { this.fecha = fecha; } public String getHora() { return this.hora; } public void setHora(String hora) { this.hora = hora; } public String getObservacion() { return this.observacion; } public void setObservacion(String observacion) { this.observacion = observacion; } public int getNumero() { return this.numero; } public void setNumero(int numero) { this.numero = numero; } public long getIdUser() { return idUser; } public void setIdUser(long idUser) { this.idUser = idUser; } public PedidoEstados getEstado() { return estado; } public void setEstado(PedidoEstados estado) { this.estado = estado; } }
true
e29e8c5b9980870a35d3c3842f8404caae2e69ba
Java
dionisius1976/java-a-to-z
/chapter_003/4_additionalTask/src/main/java/ru/dionisius/BanknoteChanger.java
UTF-8
1,007
3.59375
4
[ "Apache-2.0" ]
permissive
package ru.dionisius; /** * Created by Dionisius on 30.01.2017. */ public class BanknoteChanger { private final int[] coins = {1, 5, 10}; public void change(int banknote) { for (int tens = 0; tens <= (banknote / coins[2]); tens++) { int moneyWithoutTens = banknote - tens * coins[2]; for (int fives = 0; fives <= (moneyWithoutTens / coins[1]); fives++) { this.printCoins(coins[2], tens); this.printCoins(coins[1], fives); this.printCoins(coins[0], (moneyWithoutTens - fives * coins[1])); System.out.println(""); } } } private void printCoins(final int coin, final int amount) { if (amount != 0) { for (int index = 0; index < amount; index++) { System.out.print(coin + " "); } } } public static void main(String[] args) { BanknoteChanger bc = new BanknoteChanger(); bc.change(20); } }
true
9f8119cfd69e95c53c4145a530f21be1bf060583
Java
LionOfJah/HybridEncDec
/src/main/java/com/icicibank/apimngmnt/HybridEncDec/Decryption.java
UTF-8
12,157
2.078125
2
[]
no_license
package com.icicibank.apimngmnt.HybridEncDec; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.KeyFactory; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.util.Arrays; import java.util.Base64; import java.util.Map; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import com.apigee.flow.execution.Action; import com.apigee.flow.execution.ExecutionContext; import com.apigee.flow.execution.ExecutionResult; import com.apigee.flow.execution.spi.Execution; import com.apigee.flow.message.MessageContext; import com.google.gson.Gson; import com.icicibank.apimngmnt.HybridEncDec.model.RequestBean; public class Decryption implements Execution{ /************************** * Decryption * * @throws IOException * @throws KeyStoreException * @throws CertificateException * @throws UnrecoverableKeyException * @throws BadPaddingException * @throws IllegalBlockSizeException * @throws InvalidAlgorithmParameterException * @throws NoSuchPaddingException * @throws NoSuchAlgorithmException * @throws InvalidKeyException ***************************/ //static final String KEYSTORE_FILE = "C:\\Users\\jitendra_rawat\\Downloads\\privatePublic\\privatePublic\\privateKey.p12"; static final String KEYSTORE_PWD = "123"; static final String KEYSTORE_ALIAS = "rsa_apikey"; static final String KEYSTORE_INSTANCE = "PKCS12"; static final String ASYMM_CIPHER = "RSA/ECB/PKCS1Padding"; private Map<String, String> properties; // read-only public Decryption(Map<String, String> properties) { this.properties = properties; } public static void main(String[] args) { Decryption dec= new Decryption(); try { System.out.println(dec.DecryptData("{\r\n" + " \"requestId\": \"\",\r\n" + " \"service\": \"\",\r\n" + " \"encryptedKey\": \"SC2GO1zS7aiYYQ/2Ma6FwE+jIE6w0HzD22Ft0j8ikxw+Rn39IikSVMQTbeg0efD+pn7meIQr5YYdNdM3ptikDnaMIUF+5A36yGYqRrsP6Mpkh4xDmCJkPh4UPc3AGl/z+ff8DUr57ouaZL1O2pL/v/Ud4ltnDF53sAQLcBcYSDyY3Fi4h04IrdP4yQCjq9RvmzTf3xIA55q+hzFmvDUdHiYPqKDFZnUqbu2OR03LqOKOZ1q2GhlfI3A94PbI5tE7LuGRGfxCJNBKIH4CjHRuFxawH9XI276LnOn0dH2pQlwEEoH4Qa+K+i0rMStpMyXiISBZaxnx5rPDQg/yQvCjafwCzgl54306lmF8dWk9CiwpmrIQGfvsuxiptC/A9U18+CenKmstufYoiYEkq3vUVn9NsQ6V44i9gNl+BGZ0lNcw9TY72W1Y325fka3JI8OmtD3hK9ibBoNq5PKBDr565T99qW0YBKMOMr21vmywdZHGsFPJulcfr8AQtAaSVkFqsq+WL+uN6fv2hnRAjO2WNGHmVIiycufxbWBNP0eD7RLOhVEq355ucR89etHIwNo7iFny5GPPiXIK07BcF9ZLR4QK4ZG9LCjgZ/+o7E+ChY2agQ8MHFo1ljmxG/ViOPtiAKox7+7ATAc5Ay2ns1VJBcOC63HXQG5zd8XCmdv6M8U=\",\r\n" + " \"oaepHashingAlgorithm\": \"NONE\",\r\n" + " \"iv\": \"\",\r\n" + " \"encryptedData\": \"pnS3i/VHgbQ9PQ3dNkkqV8EwDtGpQuqt4XTFoLwOgjuiWMAb3aFSL0UmYmjpZrki\",\r\n" + " \"clientInfo\": \"\",\r\n" + " \"optionalParam\": \"\"\r\n" + "}\r\n" + "","-----BEGIN PRIVATE KEY-----\r\n" + "MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQCwjBVK1CLppIws\r\n" + "Fm7e+Fp85Hk1Mw2n5Nc/DKT/pWhpJB8OdlpJA9iF23hrxfbXkrBfCkgvV4Ek4fY1\r\n" + "byOnkA7hZq4dYTASCAm89oLwWDNm0OGNh7E6T7/JoNtjtT0Gh8lJTvpUgHFGg3ti\r\n" + "YCScAqul+fS6Rc8+5THk3L9zLzme6eqjkzwBx/ZVXBIZlAwFkVKbfLFg51LiVoOU\r\n" + "z6zXD7nAsMyNhKAgybvqulV07eGzafZ1IBgzpcw5qo0PAd1mTqfyU+CK9hVeNPPs\r\n" + "pT16qQWd5xa+fa6BEjuGCumVnFLTbSTRAF5h3QAfvMlkpLdejlXJwvTVQ79Zg5C8\r\n" + "Hu/yWB7tOJBncIKue7KSpwn+vkMws79wpAB5mL4tD3kVCDf2Og7wbtt87v5rcazx\r\n" + "F7eZFbsADzHVoSftdkw5S7iXgh82/CHbRXhzPfG8Zd2v1ksW+Bfnn3czEIMGOSJr\r\n" + "KfMbyCYtVMihoi0/L6SHA7++N9aRrQvfK9PeXnlHgf8pErGUdpjnwdV0tu5atSgf\r\n" + "/iBuRgVgUL6t6MFbnBsTQUmZYiQRcsqxOVdyyfp4DOLgFHGJ1D/isgR/ypalIXMm\r\n" + "huK8GdZ7hukEDX2Dc3js8OkPnFLq6Ps4NIGESfbZSeyINoZX5GGxdgD/GpokKMHr\r\n" + "5bsI3TQujCvzuxShPhUArzCs6TgPmwIDAQABAoICAQCmXJqD1LrBZ+keclUvjt/V\r\n" + "6IW+98jaeO3L3+JrdDabPQp22lfhjdou6Mzk4brlELlaFZpH4jEzzCnx2DTE5R7g\r\n" + "j51q2fYuR5zFj5V7XeGx9QtWDpOW2ydinE2f+1zyFmo6xk1l61LSm3tdDDPzPyD4\r\n" + "Wj2eecH9BoSpoMpXhBzL/qi4Uzmsg/1AGm6D49ogNPyewDV1lwWnetarF7dLQOpN\r\n" + "BUz73gn2W6LUYZm9gZu5MRSo8gFcSdPUUz5w8dTrXxsrYpao25LvHv7r9BmmyDce\r\n" + "wG/SOSSDQ+cLPKU38gKqcKLMv4gwt8wyG/e6+uxAEegNI8UKYbiiZTOx0YVR3G/m\r\n" + "jpRu0SGzA7BYiJ79FD61pVKHvj4y9l4hCPJArg8IvRTx2TyXHknNIxmZys4FlDYp\r\n" + "umXnUAW8Rst3GDYwJ7SOH2wyK9Xx4EMSM/21aoYKhcowb6FbhL1RU3QLeeRT3Ogp\r\n" + "qw8x53uduIQP1NZ3jihyjaAKIhLTaN2/MKkEhzsvSr8GLqnOYjL7pdizWeFzZcdF\r\n" + "5NEwi+Qu3XXO8QgGjAzjmY99rbcgW8wyljDMXsdGzuBegCR7xqfNZUUwsANuyIWs\r\n" + "DlGZzbFf0+uuYdQGqj1gdC8ohyRTNfCdyF3r+7WnWqUSJOogdO65JaWLitmw1FnF\r\n" + "0wcTtsGzrXyCxdUr0/FoAQKCAQEA7sW9Qx32lsvSbMwChGIrGiABsFz8H18ugC2n\r\n" + "/bXUVTWlc2r4xbihDvbSiGYziNj/T++rMFkPUiXLHItjy9Z+pF06v84vNeBo2JI/\r\n" + "hqlbU2hK44mANtcOZRMll4s0ACYNxUkC9q4XYjs0uIetZlRTiCNNpWMYch+behxz\r\n" + "2L98OmoKBumM2mPWrwd/e9zjOiTCHp1avM5lMmL7KdJl1sNSqQEh3lukMDZioqM3\r\n" + "pTnzeXMTl7bJMacr46jFv4WxlZhpPvb44QpDUdqGd9CvdNYwIQ3E0v734Y4efDG9\r\n" + "sHAGdylXp1i4+7W9xuTXvAHKuEh+/Zn5q00qnLChELNbXZWvAQKCAQEAvUkCVYSr\r\n" + "iQbNQafu6hcaPmhpdcciltToNj0tAKCDtQEosw05tyfdEa7z2DGkSPdvQnwtTR7f\r\n" + "JoW3PkKj5NM3gW1vfafjNCMXZgfDpextgzSJNdPRkR/uAkypFdjqtgayBvJ93F9Q\r\n" + "cVxadve+sC4fWA0hpEyz1ZAKyI925VlA6vU1dIzXHUCnkiwhJzIPomRkPlZ+6Kzl\r\n" + "D+DdtqJ2w9s//y7kWLmnwUKwcOq761jLExbF2SSXfoolAOSaB3/u7OK9HnwzAUrR\r\n" + "nGwqbPKZ5ddirXcbPcYGY0DFC/51UmVuhpZ/I+rs5m+bzlPt3/sns35Blfp2GXCz\r\n" + "EqziAWGSLNEamwKCAQBq7neSJUsXwXQdcUf3TZeL/aWD/ECVNCU5FjlTsCjFeF7+\r\n" + "T3vV4JeQgg1LNKoDsVq1y9nYrynjWjWaNPqegRL6PR5gY9BUyolp5CU7A4F42w4e\r\n" + "1Kds5+b0cRy2v4qsPl6QaeA/5TtnrKgxs+F+IGnAYD8XwEdkZK9WgoOHIEpcRrzy\r\n" + "14lTDL9KZ4s6R3Qjx+5/k2zdfXlolVdyJV2iTpsoQO+QC25+gPyvZXU4M7nMPDMc\r\n" + "EKoN6JYJQL4+xXsASd9oaWaQMe5wK/NomTbalkm7o9TvwWv1wZX5fLU83Q6oMwWk\r\n" + "VmGRqJSzDC1pb0wAN8dXf6uGgeqBfcDEH+7c/HoBAoIBABJL/2TC2U36kVa6Y/bO\r\n" + "2uOTdjZDVI2d8QBlM3dvDKwve36rVZvlx5HRBpMsYUQIXwHfPQXKaSmxHUBwcqVI\r\n" + "4YGqUW+lDepZRga/02KzkvZu2qCQZB6SJpCkVmfdOvrzdLwFLrNhp0X99mSvmAgx\r\n" + "vSfmxQy7uVp4fQJcE9MhqIvNvigRAS47tLcFewLt7OL2r1XzSHs3U0EQrH3eAHr4\r\n" + "M5x4LOyCrbuZtbKEjju2rpKezesqhVZfBiqq7lSxQig11rAes1N5pv9m2UcEwGme\r\n" + "Q1SfQcvb23w2o5WAOFkJowBxhcK0D8hKm5X7OPBAt9q65p4Xwti8syKoAYS+qMGa\r\n" + "SOcCggEBAJ/RUFUI4ukJy7Srn781ABHXwPo3QU0HdWXM5e+s2LDRjOllZGg0R4oh\r\n" + "puyS8EbmeGcfIdFfFLGxYCIFeCG4HLvciKWCSlxtGbAv61LSMtfsY3/rR0MjsMAb\r\n" + "WmLA+iqg33NuPx1QJB9HRHIskbC34zFz1THtlc4e5OeoBDgUWWb8Ev3THB5mRJVg\r\n" + "PBmgpjUM5WCgkLYFV0UO/1rTb/VsPDOEoUeot05lNwyEOBAzObh7gxiXRjA70tUe\r\n" + "VdxWgjov7X+WD6WnubLFOvd1qF3w0AyWdWa1pddz/HTO6e82dqRPEV5JN1+e6zEe\r\n" + "aKdiBykOPfhck/tXqO4R8Ezvk0eUlMU=\r\n" + "-----END PRIVATE KEY-----\r\n" + "")); } catch (UnrecoverableKeyException | InvalidKeyException | CertificateException | KeyStoreException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public ExecutionResult execute(MessageContext messageContext, ExecutionContext executionContext) { //ContentLogger contentLogger = new ContentLogger(messageContext, executionContext); try { /* * String decData = resolveVariable("decData", messageContext); String * privateKey = resolveVariable("privateKey", messageContext); * contentLogger.log("decData", decData); contentLogger.log("privateKey", * privateKey); */ String strOne = resolveVariable(this.properties.get("decData"), messageContext); String strTwo = resolveVariable(this.properties.get("privateKey"), messageContext); messageContext.setVariable("decData", strOne); messageContext.setVariable("privateKey", strTwo); String result = DecryptData(strOne,strTwo); //String mode = resolveVariable("mode", messageContext); messageContext.setVariable("decryptedData", result); //messageContext.setVariable("stage", stage); return ExecutionResult.SUCCESS; return ExecutionResult.SUCCESS; } catch (Exception ex) { ExecutionResult executionResult = new ExecutionResult(false, Action.ABORT); executionResult.setErrorResponse(ex.getMessage()); executionResult.addErrorResponseHeader("ExceptionClass", ex.getClass().getName()); //messageContext.setVariable("stage", stage); messageContext.setVariable("JAVA_ERROR", ex.getMessage()); messageContext.setVariable("JAVA_STACKTRACE", ex.getClass().getName()); return ExecutionResult.ABORT; } } private String resolveVariable(String variable, MessageContext msgContext) { if (variable.isEmpty()) return ""; if (!variable.startsWith("{") || !variable.endsWith("}")) return variable; String value = msgContext.getVariable(variable.substring(1, variable.length() - 1)).toString(); if (value.isEmpty()) return variable; return value; } public String DecryptData(String incomingData,String privateKey) throws UnrecoverableKeyException, CertificateException, KeyStoreException, IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { StringBuilder sb = new StringBuilder(); try { BufferedReader br = new BufferedReader(new StringReader(incomingData)); String line = null; while ((line = br.readLine()) != null) { sb.append(line.trim()); } } catch (Exception e) { e.printStackTrace(); } RequestBean reqData = null; reqData = new Gson().fromJson(sb.toString(), RequestBean.class); String secretKey = null; try { secretKey = decryptKey(reqData.getEncryptedKey(), privateKey); } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | UnsupportedEncodingException | IllegalBlockSizeException | BadPaddingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } byte[] ivrec = getIVSpec(reqData.getEncryptedData()); String decryptResponse = getDecryptdata(reqData.getEncryptedData(), secretKey, ivrec); decryptResponse = decryptResponse.substring(decryptResponse.indexOf("{"), decryptResponse.length()); return decryptResponse; } public String decryptKey(String b64EncryptedMsg, String privateKey) throws NoSuchAlgorithmException, NoSuchPaddingException, CertificateException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnrecoverableKeyException, KeyStoreException, IOException { Cipher cipher = Cipher.getInstance(ASYMM_CIPHER); Key key = loadPrivateKeyFromFile(privateKey); byte[] encryptedMsg = Base64.getDecoder().decode(b64EncryptedMsg); cipher.init(Cipher.DECRYPT_MODE, key); byte[] decryptedMsg = cipher.doFinal(encryptedMsg); return new String(decryptedMsg); } private PrivateKey loadPrivateKeyFromFile(String privateKey) throws CertificateException, KeyStoreException, NoSuchAlgorithmException, IOException, UnrecoverableKeyException { /* * Key key = null; KeyStore keyStore = KeyStore.getInstance(KEYSTORE_INSTANCE); * keyStore.load(this.getClass().getClassLoader().getResourceAsStream( * "privateKey.p12"), KEYSTORE_PWD.toCharArray()); */ StringBuilder pkcs8Lines = new StringBuilder(); BufferedReader rdr = new BufferedReader(new StringReader(privateKey)); String line; while ((line = rdr.readLine()) != null) { pkcs8Lines.append(line); } // Remove the "BEGIN" and "END" lines, as well as any whitespace String pkcs8Pem = pkcs8Lines.toString(); pkcs8Pem = pkcs8Pem.replace("-----BEGIN PRIVATE KEY-----", ""); pkcs8Pem = pkcs8Pem.replace("-----END PRIVATE KEY-----", ""); pkcs8Pem = pkcs8Pem.replaceAll("\\s+",""); byte [] pkcs8EncodedBytes = Base64.getDecoder().decode(pkcs8Pem); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); PrivateKey privKey=null; try { privKey = kf.generatePrivate(keySpec); } catch (InvalidKeySpecException e) { // TODO Auto-generated catch block e.printStackTrace(); } //key = keyStore.getKey(KEYSTORE_ALIAS, KEYSTORE_PWD.toCharArray()); return privKey; } // private String getDecryptedData(String secret, String strToDecrypt) // throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, // InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, IOException { // // try { // SecretKeySpec skeySpec = new SecretKeySpec(secret.getBytes("UTF-8"), "AES"); // // Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); // cipher.init(Cipher.DECRYPT_MODE, skeySpec); // byte[] original = cipher.doFinal(strToDecrypt.getBytes()); // // return new String(original, Charset.forName("UTF-8")); // // } catch (Exception ex) { // ex.printStackTrace(); // } // return null; // } // private static SecretKeySpec secretKey; // private static byte[] key; // // public static void setKey(String myKey) { // MessageDigest sha = null; // try { // key = myKey.getBytes("UTF-8"); // sha = MessageDigest.getInstance("SHA-1"); // key = sha.digest(key); // key = Arrays.copyOf(key, 16); // secretKey = new SecretKeySpec(key, "AES"); // } catch (NoSuchAlgorithmException e) { // e.printStackTrace(); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // } private byte[] getIVSpec(String encryptedData) { byte[] IV = Base64.getDecoder().decode(encryptedData.getBytes()); byte[] resbyte = new byte[16]; for (int i = 0; i < 16; i++) { resbyte[i] = IV[i]; } String result = new String(resbyte); return resbyte; } private String removeIV(String encryptedData) { byte[] IV = Base64.getDecoder().decode(encryptedData.getBytes()); byte[] filteredByteArray = Arrays.copyOfRange(IV, 16, IV.length - 16); String dataAfterIVRemove = Base64.getEncoder().encodeToString(filteredByteArray); return dataAfterIVRemove; } private String getDecryptdata(String data, String key, byte[] ivrec) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { IvParameterSpec ivspec = new IvParameterSpec(ivrec); Cipher ci = Cipher.getInstance("AES/CBC/PKCS5Padding"); byte[] actualkey = key.getBytes(); SecretKeySpec secretKeySpec = new SecretKeySpec(actualkey, "AES"); ci.init(Cipher.DECRYPT_MODE, secretKeySpec, ivspec); // ci.init(Cipher.DECRYPT_MODE,secretKeySpec); // data=removeIV(data);//remove IV data byte[] result = Base64.getDecoder().decode(data.getBytes()); String decryptedData = new String(ci.doFinal(result)); return decryptedData; } public Decryption() { super(); // TODO Auto-generated constructor stub } }
true
a25a51f3995b6b2933d28aba11ae58d42fd98b5c
Java
wnjustdoit/cache
/cache-redis-spring-boot-starter/src/test/java/com/caiya/cache/redis/spring/starter/CacheRedisAutoConfigurationTest.java
UTF-8
2,176
2.40625
2
[]
no_license
package com.caiya.cache.redis.spring.starter; import com.caiya.cache.redis.RedisTemplate; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; @RunWith(SpringRunner.class) @SpringBootTest(classes = CacheRedisApplication.class) public class CacheRedisAutoConfigurationTest { @Resource private RedisTemplate<String, Object> redisTemplate; @Resource private RedisTemplate<String, String> stringRedisTemplate; @Resource private CacheManager cacheManager; @Test public void test() { String key = "测试key"; String key2 = "测试key2"; String value = "测试value"; redisTemplate.set(key, value, 60); Assert.assertEquals(value, redisTemplate.get(key)); stringRedisTemplate.set(key2, value, 60); Assert.assertEquals(value, stringRedisTemplate.get(key2)); } @Test public void test_hash() { String key = "测试hash.key"; String key2 = "测试hash.key2"; String hkey = "测试hash.hkey"; String hvalue = "测试hash.hvalue"; redisTemplate.hSet(key, hkey, hvalue); redisTemplate.expire(key, 60); Assert.assertEquals(hvalue, redisTemplate.hGet(key, hkey)); stringRedisTemplate.hSet(key2, hkey, hvalue); stringRedisTemplate.expire(key2, 60); Assert.assertEquals(hvalue, stringRedisTemplate.hGet(key2, hkey)); } @Test public void test_cacheManager() { Cache cache = cacheManager.getCache("caiya_cache"); Assert.assertNotNull(cache); String key = "测试cacheManager"; Object value = "测试cacheManager_value"; cache.put(key, value); Cache.ValueWrapper valueWrapper = cache.get(key); Assert.assertNotNull(valueWrapper); Assert.assertEquals(value, valueWrapper.get()); cache.evict(key); Assert.assertNull(cache.get(key)); } }
true
6eaa0d2435cf32f2efe1445f6dcd9533454c3089
Java
le314u/Trabalho_SD
/src/main/java/control/ConnectControl.java
UTF-8
11,688
2.5
2
[]
no_license
package control; import org.json.JSONObject; import common.Payload; import model.Banco; import org.jgroups.*; import org.jgroups.blocks.MessageDispatcher; import org.jgroups.blocks.RequestHandler; import org.jgroups.blocks.RequestOptions; import org.jgroups.blocks.ResponseMode; import org.jgroups.util.RspList; import java.util.Collection; import java.util.Vector; public class ConnectControl extends ReceiverAdapter implements RequestHandler { // Cria os canais JChannel channelController; JChannel channelView; // Cria os despachantes para comunicar com cada canal MessageDispatcher despachanteController; MessageDispatcher despachanteView; // Variavel auxiliar para ter controle se o coordenador foi mudado ou nao Address lastCoordenador; Address accessPoint; // Banco de dados Banco banco; // Variavel usada para escolher um membro do cluster Integer balanceador; public ConnectControl() { } private void start() throws Exception { balanceador = 0; // Instancia o canal de comunicação e os integrantes do grupo channelController = new JChannel("sequencer.xml"); channelController.setReceiver(this); despachanteController = new MessageDispatcher(channelController, this, this, this); channelController.connect("control"); eventLoop(); channelController.close(); } public void newCoordenador() throws Exception { // Instanciando o coordenador if (souCoordenador(channelController) && channelView == null) { channelView = new JChannel("sequencer.xml"); channelView.setReceiver(this); despachanteView = new MessageDispatcher(channelView, this, this, this); channelView.connect("view"); setCoordenador(); //channelController.close(); } } public void setCoordenador() { // Apenas o coordenador se apresenta para o controler // E somente quando houver uma mudança de coordenador lastCoordenador = getCoordenador(channelController); JSONObject json = new JSONObject(); json.put("coordenador", channelView.getAddress()); Payload conteudo = new Payload(json, "newCoordenador", "control", false); try { Address cluster = null; Message mensagem = new Message(null, null, conteudo.toString()); channelView.send(mensagem); } catch (Exception e){ e.printStackTrace(); } } // Verifica se sou o coordenador public boolean souCoordenador(Channel canal) { // Pega o meu endereço Address meuEndereco = canal.getAddress(); // verifica se sou coordenador if (getCoordenador(canal).equals(meuEndereco)) { return true; } return false; } public Address getCoordenador(Channel canal) { Vector<Address> cluster = new Vector<Address>(canal.getView().getMembers()); // CUIDADO: o conteúdo do Vector poderá ficar desatualizado (ex.: se algum membro sair ou entrar na View) Address primeiroMembro = cluster.elementAt(0); //OBS.: 0 a N-1 return primeiroMembro; } private void eventLoop() { // Verifica com os demais se eu ja estou atualizado TODO while (true) { try { Thread.sleep(10000); } catch (InterruptedException ex) { System.out.println ("Thread awaked"); } } } // A cada iteração escolhe um membro que não seja o coordenador public Address pickMember() { int qtdMembros = channelController.getView().size() - 1; balanceador++; int escolhido = balanceador % qtdMembros; return channelController.getView().getMembers().get(escolhido + 1); } // public String typeFunc(String func) { // // String leitura[] = {"verificaCpf", "buscaConta", "saldo", "extrato", "pesquisa"}; // String escrita[] = {"cadastro", "transferencia"}; // // if (Arrays.asList(leitura).contains(func)) { // return "leitura"; // } else if (Arrays.asList(escrita).contains(func)) { // return "escrita"; // } else return "erro"; // // } public String handleControl(Payload pergunta){ Address destino = pickMember(); switch (pergunta.getFunc()){ case("cadastro"): try{ pergunta.setFunc("buscaConta"); String resultado = sendModel(pergunta); }catch (Exception e){ e.printStackTrace(); } break; } try{ return sendModel(pergunta); } catch (Exception e){ return p2str(new Payload(null, "invalido", "control", souCoordenador(channelController))); } } public String handleView(Payload pergunta){ getAccessPoint(); try{ pergunta.setChannel("control"); return this.sendCoordenador(pergunta); } catch (Exception e){ return p2str(new Payload(null, "invalido", "control", souCoordenador(channelController))); } } // responde requisições recebidas public Object handle(Message msg) throws Exception { // Extrai a mensagem e a converte para o tipo payload //String a = msg.toString(); //ObjectInputStream b = (ObjectInputStream) msg.getObject(); Payload pergunta = new Payload(msg.getObject().toString()); //Payload pergunta = (Payload) b.readObject(); switch (pergunta.getChannel()){ case "control": return handleControl(pergunta); case "view": return handleView(pergunta); } return p2str(new Payload(null, "invalido", "model", false)); } // Converte payload para string (usado no retorno das mensagens) public String p2str(Payload p){ return p.toString(); } // Recurso tecnico necessario public void saveAp(String endereco){ for (Address membro : channelController.getView().getMembers()) { if(membro.toString().equals(endereco)){ accessPoint = membro; } } } // Pergunta ao coordenador qual o ponto de acesso public void getAccessPoint(){ if (!souCoordenador(channelController)){ try{ Payload p = new Payload(null, "accessPoint", "view", souCoordenador(channelView)); Payload resultado = new Payload(sendCoordenador(p)); String endereco = resultado.getJson().getString("accessPoint"); saveAp(endereco); } catch (Exception e){ e.printStackTrace(); } } } public void receive(Message msg) { // fixa o ponto de accesso para o outro canal Payload pergunta = new Payload(msg.getObject().toString()); if (pergunta.getFunc().equals("newCoordenador")) { accessPoint = msg.getSrc(); } } public String debug(View new_view){ if (channelController.getView().equals(new_view)){ Address meuEndereco = channelController.getAddress(); return "control -"+meuEndereco.toString(); } else if (channelView.getView().equals(new_view)){ Address meuEndereco = channelView.getAddress(); return "view -"+meuEndereco.toString(); } return "Não sei"; } public void viewAccepted(View new_view) { System.out.println(debug(new_view) + new_view.toString()); try{ if(souCoordenador(channelView)){ if(channelView.getView().getMembers().size() > 1){ System.out.println("Resete conexão"); channelView.close(); channelView = null; newCoordenador(); } } } catch(Exception e){ System.out.println("Exception"); } // Apenas o coordenador se apresenta para o controler // E somente quando houver uma mudança de coordenador if (souCoordenador(channelController) && (!getCoordenador(channelController).equals(lastCoordenador)) && channelView == null) { try { newCoordenador(); } catch (Exception e) { System.out.println("Erro ao definir um novo coordenador"); e.printStackTrace(); } } lastCoordenador = getCoordenador(channelController); } private RspList enviaMulticast(MessageDispatcher despachante, Payload conteudo) throws Exception { System.out.println("\nENVIEI a pergunta: " + conteudo); Address cluster = null; //OBS.: não definir um destinatário significa enviar a TODOS os membros do cluster Message mensagem = new Message(cluster, conteudo.toString()); RequestOptions opcoes = new RequestOptions(); opcoes.setMode(ResponseMode.GET_ALL); // ESPERA receber a resposta da MAIORIA dos membros (MAJORITY) // Outras opções: ALL, FIRST, NONE opcoes.setAnycasting(false); RspList respList = despachante.castMessage(null, mensagem, opcoes); //envia o MULTICAST System.out.println("==> Respostas do cluster ao MULTICAST:\n" + respList + "\n"); return respList; } private RspList enviaAnycast(MessageDispatcher despachante, Collection<Address> subgrupo, Object conteudo) throws Exception { Message mensagem = new Message(null, conteudo); //apesar do endereço ser null, se as opcoes contiverem anycasting==true enviará somente aos destinos listados RequestOptions opcoes = new RequestOptions(); opcoes.setMode(ResponseMode.GET_FIRST); // só ESPERA receber a primeira resposta do subgrupo (FIRST) // Outras opções: ALL, MAJORITY, NONE opcoes.setAnycasting(true); RspList respList = despachante.castMessage(subgrupo, mensagem, opcoes); //envia o ANYCAST return respList; } private String sendCoordenador(Payload conteudo) throws Exception { MessageDispatcher despachante = despachanteController; Address destino = getCoordenador(channelController); Message mensagem = new Message(destino, conteudo.toString()); RequestOptions opcoes = new RequestOptions(); opcoes.setMode(ResponseMode.GET_FIRST); // ESPERA receber a resposta do destino // Outras opções: ALL, MAJORITY, FIRST, NONE // opcoes.setMode(ResponseMode.GET_NONE); // não ESPERA receber a resposta do destino // Outras opções: ALL, MAJORITY, FIRST return despachante.sendMessage(mensagem, opcoes); //envia o UNICAST } public String sendModel(Payload conteudo) throws Exception { MessageDispatcher despachante = despachanteController; if (accessPoint == null){ getAccessPoint(); } Address destino = accessPoint; Message mensagem = new Message(destino, conteudo.toString()); RequestOptions opcoes = new RequestOptions(); opcoes.setMode(ResponseMode.GET_FIRST); // ESPERA receber a resposta do destino // Outras opções: ALL, MAJORITY, FIRST, NONE // opcoes.setMode(ResponseMode.GET_NONE); // não ESPERA receber a resposta do destino // Outras opções: ALL, MAJORITY, FIRST return despachante.sendMessage(mensagem, opcoes); //envia o UNICAST } public static void main(String[] args) throws Exception { new ConnectControl().start(); } }
true
f0a58ad7b1e42849c08eb0ad769b20888d940a77
Java
matvapps/OBDProject
/app/src/main/java/com/carzis/main/fragment/DashboardFragment.java
UTF-8
7,946
1.875
2
[]
no_license
package com.carzis.main.fragment; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.carzis.R; import com.carzis.additionalscreen.AdditionalActivity; import com.carzis.base.BaseFragment; import com.carzis.main.MainActivity; import com.carzis.main.adapter.DashboardItemsAdapter; import com.carzis.main.listener.ActivityToDashboardCallbackListener; import com.carzis.main.listener.DashboardToActivityCallbackListener; import com.carzis.model.DashboardItem; import com.carzis.repository.local.database.LocalRepository; import com.carzis.repository.local.prefs.KeyValueStorage; import com.github.matvapps.dashboarddevices.Speedometer; import com.github.matvapps.dashboarddevices.Tachometer; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Objects; public class DashboardFragment extends BaseFragment implements ActivityToDashboardCallbackListener { private static final String TAG = DashboardFragment.class.getSimpleName(); private DashboardItemsAdapter dashboardItemsAdapter; private KeyValueStorage keyValueStorage; private LocalRepository localRepository; private ArrayList<String> supportedDevices; private DashboardToActivityCallbackListener dashboardToActivityCallbackListener; private Speedometer speedometer; private Tachometer tachometer; private RecyclerView deviceList; // private ImageView backround; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_dashboard, container, false); speedometer = rootView.findViewById(R.id.pointerSpeedometer); tachometer = rootView.findViewById(R.id.pointerTachometer); deviceList = rootView.findViewById(R.id.devices_list); // backround = rootView.findViewById(R.id.background); dashboardItemsAdapter = new DashboardItemsAdapter(); keyValueStorage = new KeyValueStorage(Objects.requireNonNull(getContext())); supportedDevices = new ArrayList<>(); setupDevices(keyValueStorage.getUserDashboardDevices()); deviceList.setAdapter(dashboardItemsAdapter); // reset gauges on dashboard start resetgauges(); Log.d(TAG, "onCreateView: user token: " + keyValueStorage.getUserToken()); return rootView; } // lets start animate gauges public void resetgauges() { speedometer.moveTo(240, 1300); // move to max speed, duration 1300 tachometer.moveTo(7000, 1300); // move to max turnovers, duration 1300 new Thread(() -> { try { Thread.sleep(1500); } catch (InterruptedException ex) { ex.printStackTrace(); } if (getActivity() != null) { getActivity().runOnUiThread(() -> { // uncomment this to enable revert action speedometer.moveTo(0, 1000); tachometer.moveTo(0, 1000); }); } }).start(); } private void setupDevices(String devices) { String devicesStr = devices.replaceAll("\\s+", ""); dashboardItemsAdapter.setItems(new ArrayList<>()); Log.d(TAG, "setupDevices: " + devicesStr + " length " + devicesStr.length()); for (int i = 0; i < devicesStr.length(); i += 4) { String pidStr = devicesStr.substring(i, i + 4); // if (PidItem.contains(pidStr)) { // PID pid = PID.getEnumByString(pidStr); // Log.d(TAG, "setupDevices: supportedPIDS: " + supportedDevices); // Log.d(TAG, "setupDevices: supportedPIDS preaddDashboardItem" + pid.getCommand()); // Log.d(TAG, "setupDevices: supportedPIDS pids" + supportedDevices); // if (isInSupportedPids(pid.getCommand())) { // Log.d(TAG, "setupDevices: supportedPIDS addDashboardItem" + pid.getCommand()); dashboardItemsAdapter.addItem(new DashboardItem("-", pidStr)); // } // else { // keyValueStorage.removeDeviceFromDashboard(pid); // } // } } } private boolean isInSupportedPids(String pid) { return supportedDevices.contains(pid); } @Override public void onAttach(Context context) { super.onAttach(context); dashboardToActivityCallbackListener = (DashboardToActivityCallbackListener) context; ((MainActivity) context).activityToDashboardCallbackListener = this; } @Override public void onResume() { super.onResume(); Log.d(TAG, "onResume: supportedPIDS" + keyValueStorage.getUserDashboardDevices()); setupDevices(keyValueStorage.getUserDashboardDevices()); } // @Override // public void onPassRealDataToFragment(PID pid, String value) { // Log.d(TAG, "onPassRealDataToFragment: PID: " + pid + ", value=" + value); // // switch (pid) { // case ENGINE_RPM: // float turnovers = Float.parseFloat(value); // tachometer.moveTo(turnovers); // break; // case VEHICLE_SPEED: // float speed = Float.parseFloat(value); // if (!Locale.getDefault().getLanguage().equals("ru")) // speed = speed / 1.609344f; // speedometer.moveTo(speed); // break; // default: // dashboardItemsAdapter.updateItem(new DashboardItem(value, pid)); // break; // } // // } @Override public void onPassRealDataToFragment(String pid, String value) { Log.d(TAG, "onPassRealDataToFragment: PID: " + pid + ", value=" + value); switch (pid) { case "010C": float turnovers = Float.parseFloat(value); tachometer.moveTo(turnovers); break; case "010D": float speed = Float.parseFloat(value); if (!Locale.getDefault().getLanguage().equals("ru")) speed = speed / 1.609344f; speedometer.moveTo(speed); break; default: dashboardItemsAdapter.updateItem(new DashboardItem(value, pid)); break; } } @Override public void onAddNewDevice(List<String> supportedPIDS) { // Log.d(TAG, "onAddNewDevice: supportedPIDS" + supportedPIDS); setSupportedDevices(supportedDevices); AdditionalActivity.start(getActivity(), AdditionalActivity.ADD_DEVICE_FRAGMENT, (ArrayList<String>) supportedPIDS); } public ArrayList<String> getSupportedDevices() { return supportedDevices; } public void setSupportedDevices(ArrayList<String> supportedDevices) { this.supportedDevices = supportedDevices; setupDevices(keyValueStorage.getUserDashboardDevices()); // Log.d(TAG, "setSupportedDevices: supportedPIDS " + this.supportedDevices); } private void setSpeed(float speed) { if (!Locale.getDefault().getLanguage().equals("ru")) speed = speed / 1.609344f; speedometer.moveTo(speed); } private void setSpeed(float speed, long duration) { if (!Locale.getDefault().getLanguage().equals("ru")) speed = speed / 1.609344f; speedometer.moveTo(speed, duration); } private void setTurnovers(float turnovers) { tachometer.moveTo(turnovers); } private void setTurnovers(float turnovers, long duration) { tachometer.moveTo(turnovers, duration); } }
true
74585e2f03802f5fc9e43deb791e07687ffe28e2
Java
Tavio/BetterPlace
/beckend/src/main/java/br/com/betterplace/security/SecurityException.java
UTF-8
692
2.28125
2
[]
no_license
package br.com.betterplace.security; public class SecurityException extends RuntimeException { private static final long serialVersionUID = -3172761390154852429L; public SecurityException() { super(); } public SecurityException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } public SecurityException(String message, Throwable cause) { super(message, cause); } public SecurityException(String message) { super(message); } public SecurityException(Throwable cause) { super(cause); } }
true
d267b622d0c94486fd6b97b1d23eb6ce74ecc401
Java
mehdihasheminia/ShootingGallery
/borna2d/src/main/java/com/bornaapp/borna2d/components/PointLightComponent.java
UTF-8
1,340
2.828125
3
[]
no_license
package com.bornaapp.borna2d.components; import com.badlogic.ashley.core.Component; import com.badlogic.gdx.graphics.Color; import com.bornaapp.borna2d.game.levels.Engine; import box2dLight.PointLight; /** * Created by Mehdi on 11/18/2016. */ //<-----should rayHandler(currently in LevelBase) become a system?or go inside rendering system? //Right now, light doesn't need a system & thus,it's not even necessary that be a component!!!! public class PointLightComponent extends Component { public PointLight pointLight; //region Methods //private constructor, as components must be created //using Ashley Engine and initialize afterwards. private PointLightComponent(){}; public void Init(Color color, int rays, float distance,float x,float y){ pointLight = new PointLight(Engine.getInstance().getCurrentLevel().getRayHandler(), rays, color, distance, PixeltoMeters(x), PixeltoMeters(y)); } //Box2D units are different from LibGdx rendering units // private float PixeltoMeters(float distanceInPixels){ int ppm = Engine.getInstance().getConfig().ppm; return distanceInPixels/ppm; } private float MetertoPixels(float distanceInMeters){ int ppm = Engine.getInstance().getConfig().ppm; return distanceInMeters*ppm; } //endregion }
true
e5bba7f554e71375ed980c8e33cacc800c5c7e2e
Java
jvanderhoeght/springMavenAngular5
/backend/src/test/java/be/peeterst/tester/TesterIntegrationTest.java
UTF-8
11,165
1.828125
2
[]
no_license
package be.peeterst.tester; import be.peeterst.tester.builder.CalendarItemBuilder; import be.peeterst.tester.builder.CheckListBuilder; import be.peeterst.tester.builder.ChecklistItemBuilder; import be.peeterst.tester.model.CheckList; import be.peeterst.tester.repository.CheckListRepository; import org.apache.commons.lang3.time.DateUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.context.annotation.Profile; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.jdbc.Sql; import org.springframework.test.context.junit4.SpringRunner; import javax.ws.rs.NotAuthorizedException; import java.time.Duration; import java.time.Instant; import java.util.*; import java.util.stream.Collectors; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; //import org.jooq.DSLContext; /** * Created with IntelliJ IDEA. * User: Thomas * Date: 9/09/2018 * Time: 16:43 */ @Profile("test") @SpringBootTest(webEnvironment = RANDOM_PORT) @RunWith(SpringRunner.class) @TestPropertySource({"classpath:application-test.properties"}) @Sql(scripts = "/sql/cleanup.sql",executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD) //@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class TesterIntegrationTest { @Autowired private TestRestTemplate testRestTemplate; // @Autowired // private DSLContext dsl; @Autowired private CheckListRepository checkListRepository; @Autowired private KeycloakSecurityContextClientRequestInterceptor keycloakSecurityContextClientRequestInterceptor; @Before public void setUp() { testRestTemplate.getRestTemplate().getInterceptors().add(keycloakSecurityContextClientRequestInterceptor); Date calendarStartDate = DateUtils.truncate(Date.from(Instant.now()), Calendar.SECOND); Date calendarEndDate = DateUtils.truncate(Date.from(Instant.now().plus(Duration.ofDays(1))),Calendar.SECOND); CheckList oneChecklist = CheckListTestUtils.createOneChecklist(calendarStartDate, calendarEndDate); checkListRepository.save(oneChecklist); } @Test public void overviewTest(){ ResponseEntity<CheckList[]> checkListResponse = testRestTemplate.getForEntity("/overview",CheckList[].class); assertThat(checkListResponse.getStatusCode()).isEqualTo(HttpStatus.OK); List<CheckList> checkLists = Arrays.stream(checkListResponse.getBody()).collect(Collectors.toList()); assertThat(checkLists.size()).isEqualTo(1); } @Test public void overviewTest_one(){ ResponseEntity<CheckList[]> checkListResponse = testRestTemplate.getForEntity("/overview/find/Work",CheckList[].class); assertThat(checkListResponse.getStatusCode()).isEqualTo(HttpStatus.OK); CheckList[] checkLists = checkListResponse.getBody(); assertThat(checkLists).isNotNull(); assertThat(checkLists.length).isEqualTo(1); Optional<CheckList> checkListOptional = Arrays.stream(checkLists).findFirst(); CheckList checkList = checkListOptional.orElseThrow(IllegalStateException::new); assertThat(checkList.getTitle()).isEqualTo("Work"); } @Test public void checkListAddTest(){ String checkListTitle = "ADDED"; Date calendarStartDate = new Date(); String calendarDescription = "calendarDescription"; Date calendarEndDate = new Date(); String calendarTitle = "calendarTitle"; String itemBulletName = "bulletName"; CheckList checkList = CheckListBuilder.aCheckList() .withTitle(checkListTitle) // .withCreationDateStamp(System.currentTimeMillis()) .withCalendarItem(CalendarItemBuilder.aCalendarItem() .withDescription(calendarDescription) .withStartDate(calendarStartDate) .withEndDate(calendarEndDate) .withTitle(calendarTitle) .build()) .addChecklistItem(ChecklistItemBuilder.aChecklistItem() .withBulletName(itemBulletName) .withCheck(true) .build()) .build(); keycloakSecurityContextClientRequestInterceptor.setKeycloakTestUser("moduser"); keycloakSecurityContextClientRequestInterceptor.setKeycloakTestPassword("moduser"); ResponseEntity<Void> addResponseEntity = testRestTemplate.postForEntity("/overview/write", checkList, Void.class); assertThat(addResponseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); ResponseEntity<CheckList[]> checkListResponse = testRestTemplate.getForEntity("/overview",CheckList[].class); assertThat(checkListResponse.getStatusCode()).isEqualTo(HttpStatus.OK); List<CheckList> checkLists = Arrays.stream(checkListResponse.getBody()).collect(Collectors.toList()); assertThat(checkLists.size()).isEqualTo(2); CheckList checkListToCheck = checkLists.stream().filter(checkListFound -> checkListFound.getTitle().equals(checkListTitle)).findFirst().orElse(null); assertThat(checkListToCheck).isNotNull(); keycloakSecurityContextClientRequestInterceptor.setKeycloakTestUser("user"); try { addResponseEntity = testRestTemplate.postForEntity("/overview/write", checkList, Void.class); fail("Should not reach this"); }catch (NotAuthorizedException fourOhOne){ assertThat(fourOhOne.getResponse().getStatusInfo().getReasonPhrase()).isEqualTo(HttpStatus.UNAUTHORIZED.getReasonPhrase()); } keycloakSecurityContextClientRequestInterceptor.setKeycloakTestPassword("useruser"); addResponseEntity = testRestTemplate.postForEntity("/overview/write", checkList, Void.class); assertThat(addResponseEntity.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } @Test public void checkListUpdateTest(){ keycloakSecurityContextClientRequestInterceptor.setKeycloakTestUser("moduser"); keycloakSecurityContextClientRequestInterceptor.setKeycloakTestPassword("moduser"); String updated_description = "updated description"; String bulletName = "added-bullet-name"; ResponseEntity<CheckList[]> checkListResponse = testRestTemplate.getForEntity("/overview",CheckList[].class); assertThat(checkListResponse.getStatusCode()).isEqualTo(HttpStatus.OK); List<CheckList> checkLists = Arrays.stream(checkListResponse.getBody()).collect(Collectors.toList()); CheckList checkList = checkLists.get(0); checkList.getCalendarItem().setDescription(updated_description); checkList.getItems().add(ChecklistItemBuilder.aChecklistItem() .withBulletName(bulletName) .withCheck(true) .build()); HttpEntity<CheckList> entity = new HttpEntity<>(checkList); ResponseEntity<CheckList> updateResponse = testRestTemplate.exchange("/overview/write", HttpMethod.PUT, entity, CheckList.class, ""); assertThat(updateResponse.getStatusCode()).isEqualTo(HttpStatus.OK); ResponseEntity<CheckList> updatedEntityResponse = testRestTemplate.getForEntity("/overview/" + checkList.getCreationDatestamp(), CheckList.class); assertThat(updatedEntityResponse.getStatusCode()).isEqualTo(HttpStatus.OK); CheckList updatedCheckListFromService = updatedEntityResponse.getBody(); assertThat(updatedCheckListFromService).isEqualToComparingFieldByField(checkList); keycloakSecurityContextClientRequestInterceptor.setKeycloakTestUser("user"); try { updateResponse = testRestTemplate.exchange("/overview/write", HttpMethod.PUT, entity, CheckList.class, ""); fail("Should not reach this"); }catch (NotAuthorizedException fourOhOne){ assertThat(fourOhOne.getResponse().getStatusInfo().getReasonPhrase()).isEqualTo(HttpStatus.UNAUTHORIZED.getReasonPhrase()); } keycloakSecurityContextClientRequestInterceptor.setKeycloakTestPassword("useruser"); updateResponse = testRestTemplate.exchange("/overview/write", HttpMethod.PUT, entity, CheckList.class, ""); assertThat(updateResponse.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } @Test public void deleteTest(){ keycloakSecurityContextClientRequestInterceptor.setKeycloakTestUser("moduser"); keycloakSecurityContextClientRequestInterceptor.setKeycloakTestPassword("moduser"); ResponseEntity<CheckList[]> checkListResponse = testRestTemplate.getForEntity("/overview/find/Work",CheckList[].class); assertThat(checkListResponse.getStatusCode()).isEqualTo(HttpStatus.OK); CheckList[] checkLists = checkListResponse.getBody(); assertThat(checkLists).isNotNull(); assertThat(checkLists.length).isEqualTo(1); Optional<CheckList> checkListOptional = Arrays.stream(checkLists).findFirst(); CheckList checkList = checkListOptional.orElseThrow(IllegalStateException::new); ResponseEntity<Integer> deleteResponse = testRestTemplate.exchange("/overview/write/" + checkList.getCreationDatestamp(), HttpMethod.DELETE, null, Integer.class, ""); assertThat(deleteResponse.getStatusCode()).isEqualTo(HttpStatus.OK); checkListResponse = testRestTemplate.getForEntity("/overview/find/Work",CheckList[].class); assertThat(checkListResponse.getStatusCode()).isEqualTo(HttpStatus.OK); checkLists = checkListResponse.getBody(); assertThat(checkLists).isNotNull(); assertThat(checkLists.length).isEqualTo(0); keycloakSecurityContextClientRequestInterceptor.setKeycloakTestUser("user"); try { testRestTemplate.exchange("/overview/write/" + checkList.getCreationDatestamp(), HttpMethod.DELETE, null, Integer.class, ""); fail("Should not reach this"); }catch (NotAuthorizedException fourOhOne){ assertThat(fourOhOne.getResponse().getStatusInfo().getReasonPhrase()).isEqualTo(HttpStatus.UNAUTHORIZED.getReasonPhrase()); } keycloakSecurityContextClientRequestInterceptor.setKeycloakTestPassword("useruser"); ResponseEntity<Void> deleteAttempt = testRestTemplate.exchange("/overview/write/" + checkList.getCreationDatestamp(), HttpMethod.DELETE, null, Void.class, ""); assertThat(deleteAttempt.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); } }
true
d16897114b11d57eebe7af38f5cc968d574d4440
Java
KouyouX/BlossomScriptBlock
/src/main/java/me/koneko/scriptblock/ScriptTrigger.java
UTF-8
706
2.296875
2
[ "MIT" ]
permissive
package me.koneko.scriptblock; import org.bukkit.Location; import org.bukkit.entity.Player; import org.antlr.v4.runtime.*; import me.koneko.blossom.parse.*; import me.koneko.blossom.run.InterpreterVisitor; public class ScriptTrigger { private ScriptTrigger(){} /** * 尝试触发一个脚本 * @param type 动作类型 * @param p 玩家 */ public static void trigger(int type, Location loc, Player p){ String code; if ((code = BlockManager.get(loc, type)) != null){ new BlossomParser(new CommonTokenStream(new BlossomLexer( CharStreams.fromString(ScriptManager.get(code))))) .file().accept(new InterpreterVisitor(p, loc)); } } }
true
37eb9385b8ba79988cb3902a844974babaf656fe
Java
Masoume/CoordinateBoat
/sami-crw/src/crw/uilanguage/message/fromui/MethodOptionSelectedMessage.java
UTF-8
946
1.960938
2
[]
no_license
/* * 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 crw.uilanguage.message.fromui; import crw.Coordinator; import java.util.UUID; import sami.uilanguage.fromui.FromUiMessage; /** * * @author Nicolò Marchi <marchi.nicolo@gmail.com> */ public class MethodOptionSelectedMessage extends FromUiMessage{ protected Coordinator.Method method = Coordinator.Method.COST; public MethodOptionSelectedMessage(UUID relevantToUiMessageId, UUID relevantOutputEventId, UUID missionId, Coordinator.Method method) { super(relevantToUiMessageId, relevantOutputEventId, missionId); this.method = method; } public Coordinator.Method getMethod() { return method; } @Override public UUID getRelevantOutputEventId() { return relevantOutputEventId; } }
true
9dfbb3097e58e6d17ee75675ed512c7759a62bbb
Java
Eanilsen/Group-1.2
/SLIT_v02-lib/src/DTOs/ModuleDTO.java
UTF-8
409
1.773438
2
[]
no_license
/* * 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 DTOs; import java.io.Serializable; /** * * @author Jons * @author Even */ public class ModuleDTO extends DTO{ public ModuleDTO(int id, String name){ super(id,name); } }
true
d4caf5634d8fa2b034a81e0669120ba073766355
Java
maky1984/samples
/maky/Project/src/com/maky/game/lines/view/menu/LinesGameMenu.java
UTF-8
334
1.648438
2
[]
no_license
package com.maky.game.lines.view.menu; import com.maky.environment.AppGraphics; import com.maky.environment.IPaintable; public class LinesGameMenu implements IPaintable { //private AppImage menuImage public LinesGameMenu() { } @Override public void paint(AppGraphics gr) { // TODO Auto-generated method stub } }
true
65a5d63351010931f4feb771e9ecbdbdc60999f6
Java
ics-team18/ICS_FormManagement
/MyApplication/app/src/main/java/com/example/kyle/myapplication/Database/Role/Tbl_Role.java
UTF-8
1,193
2.859375
3
[]
no_license
package com.example.kyle.myapplication.Database.Role; import com.example.kyle.myapplication.Database.Abstract.Abstract_Table; /** * Created by Kyle on 1/31/2016. */ public class Tbl_Role extends Abstract_Table { public long roleID = -1; public String title = ""; public Tbl_Role() { } public Tbl_Role(long roleID) { this.roleID = roleID; } public Tbl_Role( String title) { this.title = title; } @Override public String isValidRecord() { String anyErrors = ""; if (title.isEmpty()) { anyErrors += "\nTitle is a required field"; } if (!anyErrors.isEmpty()) { anyErrors = "Please fix the following errors:" + anyErrors; } return anyErrors; } @Override public String getDataGridDisplayValue() { return this.roleID + " - " + this.title; } @Override public String toString() { return this.title; } @Override public String getDataGridPopupMessageValue() { return "ID: " + Long.toString(this.roleID) + "\n" + "Title: " + this.title; } }
true
070177ca02f12e5d4860705c5fd8aef4374727ab
Java
Baltan/leetcode
/src/leetcode/interview/TranslateNum.java
UTF-8
1,594
4.0625
4
[]
no_license
package leetcode.interview; /** * Description: 面试题46. 把数字翻译成字符串 * * @author Baltan * @date 2020-06-09 08:56 */ public class TranslateNum { public static void main(String[] args) { System.out.println(translateNum(12258)); System.out.println(translateNum(425534453)); System.out.println(translateNum(989723846)); System.out.println(translateNum(2130093939)); } public static int translateNum(int num) { /** * 如果num只有一位,则只有一种翻译方法 */ if (num < 10) { return 1; } char[] charArray = String.valueOf(num).toCharArray(); int length = charArray.length; /** * dp[i]表示num前i+1位数字的翻译方法种类数 */ int[] dp = new int[length]; dp[0] = 1; /** * 如果前两位数字在[10,25]范围内,则前两位数字有两种翻译方法(两个数字拆开和不拆开),否则只有一种翻译 * 方法(拆开) */ dp[1] = charArray[0] - '0' != 0 && (charArray[0] - '0') * 10 + (charArray[1] - '0') <= 25 ? 2 : 1; for (int i = 2; i < length; i++) { /** * 逐一判断每一位数字能否和前一位数字合并翻译 */ dp[i] = charArray[i - 1] - '0' != 0 && (charArray[i - 1] - '0') * 10 + (charArray[i] - '0') <= 25 ? dp[i - 2] + dp[i - 1] : dp[i - 1]; } return dp[length - 1]; } }
true
229af7656d49f43a76432ee07a214c6c7907a716
Java
iav0207/lt-iam
/src/test/java/task/lt/db/TestDbInitializer.java
UTF-8
1,989
1.96875
2
[]
no_license
package task.lt.db; import javax.annotation.ParametersAreNonnullByDefault; import com.codahale.metrics.MetricRegistry; import io.dropwizard.db.DataSourceFactory; import io.dropwizard.jackson.Jackson; import io.dropwizard.jdbi.DBIFactory; import io.dropwizard.setup.Environment; import org.skife.jdbi.v2.DBI; @ParametersAreNonnullByDefault public class TestDbInitializer { private static final String DRIVER = "org.h2.Driver"; private static final String URL = "jdbc:h2:mem:testDb"; private static final Environment env = new Environment("test-env", Jackson.newObjectMapper(), null, new MetricRegistry(), null); private static final DataSourceFactory dataSourceFactory = createDataSourceFactory(); private static final DBI dbi = new DBIFactory().build(env, dataSourceFactory, "test"); static { OrgTypesDao orgTypesDao = dbi.onDemand(OrgTypesDao.class); OrganizationsDao organizationsDao = dbi.onDemand(OrganizationsDao.class); UsersDao usersDao = dbi.onDemand(UsersDao.class); EmploymentDao employmentDao = dbi.onDemand(EmploymentDao.class); SessionsDao sessionsDao = dbi.onDemand(SessionsDao.class); orgTypesDao.createTableIfNotExists(); organizationsDao.createTableIfNotExists(); usersDao.createTableIfNotExists(); employmentDao.createTableIfNotExists(); sessionsDao.createTableIfNotExists(); new OrgTypesInitializer(orgTypesDao).populateOrgTypes(); dbi.registerMapper(new OrganizationMapper()); dbi.registerMapper(new UserMapper()); } private static DataSourceFactory createDataSourceFactory() { DataSourceFactory dataSourceFactory = new DataSourceFactory(); dataSourceFactory.setDriverClass(DRIVER); dataSourceFactory.setUrl(URL); return dataSourceFactory; } public static DBI getDbi() { return dbi; } private TestDbInitializer() { // no instantiation } }
true
4d50ecc4ffbf0627f79e34df509dd579082f9af4
Java
tpm520/cloud-demo
/cloud-provider-payment/src/main/java/com/tpblog/springcloud/handler/CommonBlockHandler.java
UTF-8
526
1.96875
2
[]
no_license
package com.tpblog.springcloudOrder.handler; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.tpblog.common.entity.Order; import com.tpblog.common.response.Result; import com.tpblog.common.response.ResultGenerate; public class CommonBlockHandler { public static Result error(Order order,BlockException e){ System.out.println("error----哈哈哈"+e+"---"+order); return ResultGenerate.success(200, "warning", "系统繁忙"); //return "服务繁忙。。。。。"; } }
true
ca4178a0aae0c5137c0429d5de38641ccef3885b
Java
ShivaKumar2014/CodeAssignment_Java_Singtel
/codeassignment/src/main/java/com/java/cd/test/codeassignment/model/SwimIF.java
UTF-8
102
1.75
2
[]
no_license
package com.java.cd.test.codeassignment.model; public interface SwimIF { public void swim(); }
true
c4192817135a4d48e82c281435429da6a6c92508
Java
jybyun9533/Study05_SpringMVC_And_SpringBoot
/sp05_Products/src/main/java/com/encore/spring/model/ProductCatalog.java
UTF-8
390
1.914063
2
[]
no_license
package com.encore.spring.model; import java.util.List; import java.util.Map; import com.encore.spring.domain.MyProduct; public interface ProductCatalog { public List<MyProduct> getProductList(); public List<MyProduct> findProducts(Map map); public void enrollProduct(MyProduct product); public void deleteProduct(String name); public void updateProduct(MyProduct product); }
true