text stringlengths 10 2.72M |
|---|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int board[][] = new int[9][9];
for(int i = 0; i < 9; i++){
for(int j = 0; j < 9; j++){
board[i][j] = s.nextInt();
}
}
System.out.println(Solution.sudokuSolver(board));
}
}
|
/* CSUN CS110 header
student: Rafael Almazar
date: 10 April 20 19
file: Lab7.java
Lab 7: Cryptography
*/
import java.util.*;
import javax.swing.*;
import java.io.*;
public class Lab7 {
static final int[] key1 = {5, 2, 1, 7, 0, 9, 8, 3};
static final int[] key2 = {14, 27, 33, 2, 9, 25, 10, 51};
static final String keyBinStr = "11010100";
static final int key3 = Integer.parseInt(keyBinStr);
static final int keyLen = key1.length;
public static void main(String[] args) {
String input;
input = JOptionPane.showInputDialog(null, "Enter message: ");
System.out.println("Input message: " + input);
// Print encrypted
System.out.println();
System.out.println("Encrypted");
System.out.print("Key 1 / Alg 1: ");
System.out.println(encrypt1(input, key1));
System.out.print("Key 2 / Alg 1: ");
System.out.println(encrypt1(input, key2));
System.out.print("Key 3 / Alg 2: ");
System.out.println(encrypt2(input, key3));
// Print decrypted
System.out.println();
System.out.println("Decrypted");
System.out.print("Key 1 / Alg 1: ");
System.out.println(decrypt1(encrypt1(input, key1), key1));
System.out.print("Key 2 / Alg 1: ");
System.out.println(decrypt1(encrypt1(input, key2), key2));
System.out.print("Key 3 / Alg 2: ");
System.out.println(decrypt2(encrypt2(input, key3), key3));
// Print hash
System.out.println();
System.out.println("Hash");
System.out.println("Hash 1: " + hash(input, key1));
System.out.println("Hash 2: " + hash(input, key2));
} // End main
static char[] encrypt1 (String msg, int[] key) {
char[] cyph = msg.toCharArray();
int k = 0;
for (int i = 0; i < msg.length(); i++) {
char x = cyph[i];
if (Character.isLetter(x)) {
boolean Lcase = Character.isLowerCase(x);
boolean Ucase = Character.isUpperCase(x);
x += (key[k]);
if (Lcase && x > 'z') {
x = (char) ('a' + (x - 'z') - 1);
}
else if (Ucase && (x > 'Z')) {
x = (char) ('A' + (x - 'Z') - 1);
}
k = k++ % keyLen;
}
//x = (char) ('a' + i++);
cyph[i] = x;
}
return cyph;
} // End encrypt1
static char[] encrypt2 (String msg, int key) {
char[] cyph = msg.toCharArray();
int k = 0;
for (int i = 0; i < msg.length(); i++) {
char x = cyph[i];
x ^= key;
cyph[i] = x;
} // End loop
return cyph;
} // End encrypt2
static char[] decrypt1 (char[] xcyf, int[] key) {
int k = 0;
for (int i = 0; i < xcyf.length; i++) {
char x = xcyf[i];
if (Character.isLetter(x)) {
boolean Lcase = Character.isLowerCase(x);
boolean Ucase = Character.isUpperCase(x);
x -= (key[k]);
if (Lcase && x < 'a') x = (char) ('z'-('a'-x)+1);
else if (Ucase && (x<'A')) x = (char)('Z'-('A'-x)+1);
k = k++ % keyLen;
}
xcyf[i] = x;
}
return xcyf;
}
static char[] decrypt2 (char[] xycf, int key) {
int k = 0;
for (int i =0; i < xycf.length; i++) {
char x = xycf[i];
x ^= key;
xycf[i] = x;
}
return xycf;
} // End decrypt2
static long hash (String msg, int[] key) {
long hashVal = 0;
char[] hashArr = msg.toCharArray();
int k = 0;
for (int i = 0; i < msg.length(); i++) {
hashVal += hashArr[i] * key[k];
k = k++ % keyLen;
}
return hashVal;
}
} // End class |
package application;
import java.util.HashMap;
import java.util.HashSet;
import org.w3c.dom.UserDataHandler;
public class DataBase {
HashMap<Environment, HashSet<String>> envirUsers = new HashMap<Environment, HashSet<String>>();
HashMap<String, String> userPassword = new HashMap<String, String>();
public DataBase() {
User user1 = new User("Adam Adamski", "Adam");
User user2 = new User("Bogdan Bog", "Bogdan");
User user3 = new User("Cezary Cez", "Cezary");
User user4 = new User("Dariusz Dar", "Dariusz");
User user5 = new User("Emilia Emilska", "Emilia");
User user6 = new User("Franciszek Fran", "Franciszek");
User user7 = new User("Grzegorz Grzeg", "Grzegorz");
HashSet<String> testList = new HashSet<String>();
testList.add(user1.getName());
testList.add(user2.getName());
HashSet<String> prodList = new HashSet<String>();
prodList.add(user3.getName());
prodList.add(user4.getName());
HashSet<String> dewList = new HashSet<String>();
dewList.add(user5.getName());
dewList.add(user6.getName());
dewList.add(user7.getName());
envirUsers.put(Environment.Testowe, testList);
envirUsers.put(Environment.Produkcyjne, prodList);
envirUsers.put(Environment.Deweloperskie, dewList);
userPassword.put(user1.getName(), user1.getPassword());
userPassword.put(user2.getName(), user2.getPassword());
userPassword.put(user3.getName(), user3.getPassword());
userPassword.put(user4.getName(), user4.getPassword());
userPassword.put(user5.getName(), user5.getPassword());
userPassword.put(user6.getName(), user6.getPassword());
userPassword.put(user7.getName(), user7.getPassword());
}
// Zwraca listę użytkowników dla podanego środowiska
public HashSet<String> getEnvirUsers(Environment envir) {
return envirUsers.get(envir);
}
// Sprawdza czy istnieje taki użytkownik i weryfikuje hasło
public int passwordCheck(String name, String password) {
if (!userPassword.containsKey(name)) {
return -1;
} else if (userPassword.get(name).equals(password)) {
return 1;
} else if (!userPassword.get(name).equals(password)) {
return 0;
} else
return -1;
}
} |
package tema11;
import java.util.Random;
public class D6 implements Dado {
@Override
public boolean estaViciado() {
return false;
}
@Override
public int getNumeroLados() {
return 6;
}
@Override
public int rolaDados(int quantidade) {
Random random = new Random();
int resultado = 0;
for (int i=0; i<quantidade; i++) {
int dadoRolado = random.nextInt(getNumeroLados()-1) + 1;
resultado += dadoRolado;
}
return resultado;
}
}
|
package com.cg.ibs.spmgmt.bean;
import java.io.Serializable;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.Arrays;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
@Entity
@Table(uniqueConstraints= @UniqueConstraint(columnNames= {"nameOfCompany","category"}), name = "Service_providers" )
public class ServiceProvider implements Serializable {
private BigInteger accountNumber;
private byte[] addressProofUpload;
private String bankName;
private String category;
private String companyAddress;
private String gstin;
private String IFSC;
private BigInteger mobileNumber;
private String nameOfCompany;
private byte[] panCardUpload;
private String panNumber;
private String password;
public String getIFSC() {
return IFSC;
}
public void setIFSC(String iFSC) {
IFSC = iFSC;
}
private String remarks = "None";
private LocalDateTime requestDate;
private BigInteger spi = BigInteger.valueOf(-1);
private String status = "Pending";
@Id
private String userId;
public ServiceProvider() {
super();
}
public BigInteger getAccountNumber() {
return accountNumber;
}
public byte[] getAddressProofUpload() {
return addressProofUpload;
}
public String getBankName() {
return bankName;
}
public String getCategory() {
return category;
}
public String getCompanyAddress() {
return companyAddress;
}
public String getGstin() {
return gstin;
}
public BigInteger getMobileNumber() {
return mobileNumber;
}
public String getNameOfCompany() {
return nameOfCompany;
}
public byte[] getPanCardUpload() {
return panCardUpload;
}
public String getPanNumber() {
return panNumber;
}
public String getPassword() {
return password;
}
public String getRemarks() {
return remarks;
}
public LocalDateTime getRequestDate() {
return requestDate;
}
public BigInteger getSpi() {
return spi;
}
public String getStatus() {
return status;
}
public String getUserId() {
return userId;
}
public void setAccountNumber(BigInteger accountNumber) {
this.accountNumber = accountNumber;
}
public void setAddressProofUpload(byte[] addressProofUpload) {
this.addressProofUpload = addressProofUpload;
}
public void setBankName(String bankName) {
this.bankName = bankName;
}
public void setCategory(String category) {
this.category = category;
}
public void setCompanyAddress(String companyAddress) {
this.companyAddress = companyAddress;
}
public void setGstin(String gstin) {
this.gstin = gstin;
}
public void setMobileNumber(BigInteger mobileNumber) {
this.mobileNumber = mobileNumber;
}
public void setNameOfCompany(String nameOfCompany) {
this.nameOfCompany = nameOfCompany;
}
public void setPanCardUpload(byte[] panCardUpload) {
this.panCardUpload = panCardUpload;
}
public void setPanNumber(String panNumber) {
this.panNumber = panNumber;
}
public void setPassword(String password) {
this.password = password;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public void setRequestDate(LocalDateTime requestDate) {
this.requestDate = requestDate;
}
public void setSpi(BigInteger spi) {
this.spi = spi;
}
public void setStatus(String status) {
this.status = status;
}
public void setUserId(String userId) {
this.userId = userId;
}
@Override
public String toString() {
return "ServiceProvider [userId=" + userId + ", category=" + category + ", nameOfCompany=" + nameOfCompany
+ ", gstin=" + gstin + ", panNumber=" + panNumber + ", panCardUpload=" + Arrays.toString(panCardUpload)
+ ", accountNumber=" + accountNumber + ", bankName=" + bankName + ", IFSC=" + IFSC + ",addressProofUpload="
+ Arrays.toString(addressProofUpload) + ", companyAddress=" + companyAddress + ", mobileNumber="
+ mobileNumber + ", password=" + password + ", spi=" + spi + ", status=" + status + ", requestDate="
+ requestDate + ", remarks=" + remarks + "]";
}
}
|
package com.learn.grpc.server;
import com.learn.grpc.service.GreetingServiceImpl;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import java.io.IOException;
public class Application {
public static void main(String[] args) throws InterruptedException, IOException {
Server server = ServerBuilder.forPort(50051)
.addService(new GreetingServiceImpl())
.build();
server.start();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
server.shutdown();
}));
server.awaitTermination();
}
}
|
package com.company;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Writer {
public static void main(String[] args) throws IOException {
List<List<String>> lists = new ArrayList<>();
FileWriter fW = new FileWriter("output.txt");
for (int i = 0; i < lists.size(); i++){
for (int j = 0; j < lists.get(i).size(); j++){
fW.write(lists.get(i).get(j));
}
fW.write("\n");
}
fW.close();
}
} |
package com.pawi.project.analyzer.test;
import static org.testng.AssertJUnit.assertEquals;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.testng.annotations.Test;
import com.pawi.analyzer.DiffToolAnalyzer;
import com.pawi.data.ContentFile;
import com.pawi.data.ExtractedContent;
import com.pawi.data.Result;
import com.pawi.data.TestCase;
import com.pawi.data.enums.ExtractorName;
import com.pawi.data.enums.ResultType;
public class DiffToolWordAnalyzerTest {
@Test
public void easySentenceTest() {
DiffToolAnalyzer dta = new DiffToolAnalyzer();
String content = "ich heisse joel";
String extractedText = "ich heisse joel";
TestCase testCase = setupTestCase(ExtractorName.boilerpipe, content, extractedText, 3);
testCase = dta.evaluateResults(testCase);
List<ExtractedContent> ec = testCase.getExtractionResultList();
Result result = ec.get(0).getResult(ResultType.TRUE_POSITIVE_WORDS);
assertEquals("3", result.getValue());
}
@Test
public void easySentenceTestTooMuchWords() {
DiffToolAnalyzer dta = new DiffToolAnalyzer();
String content = "ich heisse";
String extractedText = "ich heisse joel";
TestCase testCase = setupTestCase(ExtractorName.boilerpipe, content, extractedText, 2);
testCase = dta.evaluateResults(testCase);
List<ExtractedContent> ec = testCase.getExtractionResultList();
Result result = ec.get(0).getResult(ResultType.TRUE_POSITIVE_WORDS);
assertEquals("2", result.getValue());
}
@Test
public void easySentenceTestTooLessWords() {
DiffToolAnalyzer dta = new DiffToolAnalyzer();
String content = "ich heisse joel";
String extractedText = "ich heisse";
TestCase testCase = setupTestCase(ExtractorName.boilerpipe, content, extractedText, 3);
testCase = dta.evaluateResults(testCase);
List<ExtractedContent> ec = testCase.getExtractionResultList();
Result result = ec.get(0).getResult(ResultType.TRUE_POSITIVE_WORDS);
assertEquals("2", result.getValue());
}
@Test
public void easySentenceTestWrongWords() {
DiffToolAnalyzer dta = new DiffToolAnalyzer();
String content = "ich heisse joel";
String extractedText = "dieser text is über etwas anderes";
TestCase testCase = setupTestCase(ExtractorName.boilerpipe, content, extractedText, 3);
testCase = dta.evaluateResults(testCase);
List<ExtractedContent> ec = testCase.getExtractionResultList();
Result result = ec.get(0).getResult(ResultType.TRUE_POSITIVE_WORDS);
assertEquals("0", result.getValue());
}
@Test
public void easySentenceTestComercial() {
DiffToolAnalyzer dta = new DiffToolAnalyzer();
String content = "das ist ein wichtiger artikel über Kleider";
String extractedText = "YOLOOOO kaufe Kleider bei Zalando super günstig!!!!";
TestCase testCase = setupTestCase(ExtractorName.boilerpipe, content, extractedText, 7);
testCase = dta.evaluateResults(testCase);
List<ExtractedContent> ec = testCase.getExtractionResultList();
Result result = ec.get(0).getResult(ResultType.TRUE_POSITIVE_WORDS);
assertEquals("0", result.getValue());
}
@Test
public void realArticleNotPerfectExtractionTest() throws IOException {
String content = "poems from prison by raegan butcher this is the inaugural book in the CrimethInc. Letters series This is not the third 'CrimethInc. book,' rather, it is the first CrimethInc. Letters book. This is not direct propaganda, nor is it similar in most regards to previous CrimethInc. publications. This is a new voice, a new form, a new idea, but born of the same fires. These are our letters--to the universe. To each other. This is where we re-write our histories and create our own cultures without the mediation of corporations. When we are too far away from one another for campfire storytelling, we use our own voices here, and we use them to call out across the distance. Authors in the Letters series receive 10-20% (a sliding scale based on their financial situation) of the gross revenue for the book as payment: this is our effort to actually build sustainability into our pricing structure rather than nurture yet another generation of victimized, starving artists";
String extractedText = "poems from prison by raegan butcher this is the inaugural book in the CrimethInc. Letters series This is not the third 'CrimethInc. book,' rather, it is the first CrimethInc. Letters book. This is not direct propaganda, nor is it similar in most regards to previous CrimethInc. publications. This is a new voice, a new form, a new idea, but born of the same fires. These are our letters--to the universe. To each other. This is where we re-write our histories and create our own cultures without the mediation of corporations. When we are too far away from one another for campfire storytelling, we use our own voices here, and we use them to call out across the distance. Purity is the opposite of integrity—the cruelest thing you can do to a person is make her ashamed of her own complexity";
extractedText = extractedText.replace(" .", ".");
TestCase testCase = setupTestCase(ExtractorName.boilerpipe, content, extractedText, 200);
DiffToolAnalyzer dta = new DiffToolAnalyzer();
testCase = dta.evaluateResults(testCase);
ExtractedContent ec = testCase.getExtractedContentByExtractor(ExtractorName.boilerpipe);
Result tp = ec.getResult(ResultType.TRUE_POSITIVE_WORDS);
Result tn = ec.getResult(ResultType.TRUE_NEGATIVE_WORDS);
Result fp = ec.getResult(ResultType.FALSE_POSITIVE_WORDS);
Result fn = ec.getResult(ResultType.FALSE_NEGATIVE_WORDS);
assertEquals("118", tp.getValue());
assertEquals("14", tn.getValue());
assertEquals("46", fn.getValue());
assertEquals("22", fp.getValue());
}
private TestCase setupTestCase(ExtractorName extractorName, String content, String extraction, int allWords) {
TestCase tc = new TestCase();
ContentFile contentFile = new ContentFile();
contentFile.setContent(content);
Result allWordsResult = new Result();
allWordsResult.setKey(ResultType.ALL_WORDS_COUNT);
allWordsResult.setValue(Integer.toString(allWords));
tc.addResult(allWordsResult);
ExtractedContent extractionResult = new ExtractedContent();
extractionResult.setExtractedText(extraction);
extractionResult.setExtractorName(extractorName);
List<ExtractedContent> results = new ArrayList<ExtractedContent>();
results.add(extractionResult);
tc.setContentFile(contentFile);
tc.setExtractionResultList(results);
return tc;
}
}
|
package pro.eddiecache.kits.lateral.tcp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import pro.eddiecache.core.CacheElement;
import pro.eddiecache.core.CacheInfo;
import pro.eddiecache.core.model.ICacheElement;
import pro.eddiecache.core.model.ICacheServiceRemote;
import pro.eddiecache.kits.lateral.LateralCommand;
import pro.eddiecache.kits.lateral.LateralElementDescriptor;
/**
* @author eddie
*/
public class LateralTCPService<K, V> implements ICacheServiceRemote<K, V>
{
private static final Log log = LogFactory.getLog(LateralTCPService.class);
private boolean allowPut;
private boolean allowGet;
private boolean allowRemoveOnPut;
private LateralTCPSender sender;
private long listenerId = CacheInfo.listenerId;
public LateralTCPService(ITCPLateralCacheAttributes attr) throws IOException
{
this.allowGet = attr.isAllowGet();
this.allowPut = attr.isAllowPut();
this.allowRemoveOnPut = attr.isAllowRemoveOnPut();
try
{
sender = new LateralTCPSender(attr);
if (log.isInfoEnabled())
{
log.debug("Create sender to [" + attr.getTcpServer() + "]");
}
}
catch (IOException e)
{
log.error("Could not create sender to [" + attr.getTcpServer() + "] -- " + e.getMessage());
throw e;
}
}
@Override
public void update(ICacheElement<K, V> item) throws IOException
{
update(item, getListenerId());
}
/**
* 更新 remote-service 缓存实例
* @param item 缓存对象
* @param requesterId 请求id
*/
@Override
public void update(ICacheElement<K, V> item, long requesterId) throws IOException
{
if (!this.allowPut && !this.allowRemoveOnPut)
{
return;
}
if (!this.allowRemoveOnPut)
{
LateralElementDescriptor<K, V> led = new LateralElementDescriptor<K, V>(item);
led.requesterId = requesterId;
led.command = LateralCommand.UPDATE;
sender.send(led);
}
else
{
CacheElement<K, V> ce = new CacheElement<K, V>(item.getCacheName(), item.getKey(), null);
LateralElementDescriptor<K, V> led = new LateralElementDescriptor<K, V>(ce);
led.requesterId = requesterId;
led.command = LateralCommand.REMOVE;
led.valHashCode = item.getVal().hashCode();
sender.send(led);
}
}
@Override
public void remove(String cacheName, K key) throws IOException
{
remove(cacheName, key, getListenerId());
}
@Override
public void remove(String cacheName, K key, long requesterId) throws IOException
{
CacheElement<K, V> ce = new CacheElement<K, V>(cacheName, key, null);
LateralElementDescriptor<K, V> led = new LateralElementDescriptor<K, V>(ce);
led.requesterId = requesterId;
led.command = LateralCommand.REMOVE;
sender.send(led);
}
@Override
public void release() throws IOException
{
}
@Override
public void dispose(String cacheName) throws IOException
{
sender.dispose();
}
@Override
public ICacheElement<K, V> get(String cacheName, K key) throws IOException
{
return get(cacheName, key, getListenerId());
}
@Override
public ICacheElement<K, V> get(String cacheName, K key, long requesterId) throws IOException
{
if (this.allowGet)
{
CacheElement<K, V> ce = new CacheElement<K, V>(cacheName, key, null);
LateralElementDescriptor<K, V> led = new LateralElementDescriptor<K, V>(ce);
led.command = LateralCommand.GET;
@SuppressWarnings("unchecked")
ICacheElement<K, V> response = (ICacheElement<K, V>) sender.sendAndReceive(led);
if (response != null)
{
return response;
}
return null;
}
else
{
return null;
}
}
@Override
public Map<K, ICacheElement<K, V>> getMatching(String cacheName, String pattern) throws IOException
{
return getMatching(cacheName, pattern, getListenerId());
}
@Override
@SuppressWarnings("unchecked")
public Map<K, ICacheElement<K, V>> getMatching(String cacheName, String pattern, long requesterId)
throws IOException
{
if (this.allowGet)
{
CacheElement<String, String> ce = new CacheElement<String, String>(cacheName, pattern, null);
LateralElementDescriptor<String, String> led = new LateralElementDescriptor<String, String>(ce);
led.requesterId = requesterId;
led.command = LateralCommand.GET_MATCHING;
Object response = sender.sendAndReceive(led);
if (response != null)
{
return (Map<K, ICacheElement<K, V>>) response;
}
return Collections.emptyMap();
}
else
{
return null;
}
}
@Override
public Map<K, ICacheElement<K, V>> getMultiple(String cacheName, Set<K> keys) throws IOException
{
return getMultiple(cacheName, keys, getListenerId());
}
@Override
public Map<K, ICacheElement<K, V>> getMultiple(String cacheName, Set<K> keys, long requesterId) throws IOException
{
Map<K, ICacheElement<K, V>> elements = new HashMap<K, ICacheElement<K, V>>();
if (keys != null && !keys.isEmpty())
{
for (K key : keys)
{
ICacheElement<K, V> element = get(cacheName, key);
if (element != null)
{
elements.put(key, element);
}
}
}
return elements;
}
@Override
@SuppressWarnings("unchecked")
public Set<K> getKeySet(String cacheName) throws IOException
{
CacheElement<String, String> ce = new CacheElement<String, String>(cacheName, null, null);
LateralElementDescriptor<String, String> led = new LateralElementDescriptor<String, String>(ce);
led.command = LateralCommand.GET_KEYSET;
Object response = sender.sendAndReceive(led);
if (response != null)
{
return (Set<K>) response;
}
return null;
}
@Override
public void removeAll(String cacheName) throws IOException
{
removeAll(cacheName, getListenerId());
}
@Override
public void removeAll(String cacheName, long requesterId) throws IOException
{
CacheElement<String, String> ce = new CacheElement<String, String>(cacheName, "ALL", null);
LateralElementDescriptor<String, String> led = new LateralElementDescriptor<String, String>(ce);
led.requesterId = requesterId;
led.command = LateralCommand.REMOVEALL;
sender.send(led);
}
protected void setListenerId(long listernId)
{
this.listenerId = listernId;
}
protected long getListenerId()
{
return listenerId;
}
}
|
package net.razorvine.pyro.serializer;
import java.io.IOException;
import java.io.OutputStream;
import net.razorvine.pickle.IObjectPickler;
import net.razorvine.pickle.Opcodes;
import net.razorvine.pickle.PickleException;
import net.razorvine.pickle.Pickler;
import net.razorvine.pyro.PyroURI;
/**
* Pickler extension to be able to pickle Pyro URI objects.
*
* @author Irmen de Jong (irmen@razorvine.net)
*/
public class PyroUriPickler implements IObjectPickler {
public void pickle(Object o, OutputStream out, Pickler currentPickler) throws PickleException, IOException {
PyroURI uri = (PyroURI) o;
out.write(Opcodes.GLOBAL);
out.write("Pyro4.core\nURI\n".getBytes());
out.write(Opcodes.EMPTY_TUPLE);
out.write(Opcodes.NEWOBJ);
out.write(Opcodes.MARK);
currentPickler.save(uri.protocol);
currentPickler.save(uri.objectid);
currentPickler.save(null);
currentPickler.save(uri.host);
currentPickler.save(uri.port);
out.write(Opcodes.TUPLE);
out.write(Opcodes.BUILD);
}
}
|
package com.syla.application;
public class AppConstants {
public static final String USER_ID = "userId";
public static final String CURRENT_ROOM_ID = "currentRoomId";
public static final String USER_NAME = "userName";
public static final String IS_LOGIN = "idLogin";
public static final String IS_GUEST = "isGuest";
}
|
/*
* 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 com.forsrc.aop;
import com.forsrc.constant.KeyConstants;
import com.forsrc.utils.WebUtils;
//import com.opensymphony.xwork2.ActionContext;
import org.apache.log4j.Logger;
//import org.apache.struts2.ServletActionContext;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* The type Log tracing.
*/
public final class LogTracing {
private static final Logger LOGGER = Logger.getLogger(LogTracing.class);
private LogTracing() {
}
/**
* Do after.
*
* @param joinPoint the join point
*/
public void doAfter(JoinPoint joinPoint) {
StringBuilder msg = new StringBuilder("[END] method: ")
.append(joinPoint.getSignature().getName()).append("() @ ")
.append(joinPoint.getTarget().getClass().getName()).append(".");
this.appendMessage(msg);
LOGGER.info(msg);
}
/**
* Do around object.
*
* @param proceedingJoinPoint the proceeding join point
* @return the object
* @throws Throwable the throwable
*/
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
long ms = System.currentTimeMillis();
long time = System.nanoTime();
Object retVal = proceedingJoinPoint.proceed();
time = System.nanoTime() - time;
ms = System.currentTimeMillis() - ms;
StringBuilder msg = new StringBuilder("[TIME] method: ")
.append(proceedingJoinPoint.getSignature().getName()).append("() -> ")
.append(new Double(1.0d * time / (1000000000d)).toString()).append(" s (")
.append(ms).append(" ms) --> ")
.append(proceedingJoinPoint.getTarget().getClass());
this.appendMessage(msg);
LOGGER.info(msg);
return retVal;
}
/**
* Do before.
*
* @param joinPoint the join point
*/
public void doBefore(JoinPoint joinPoint) {
StringBuilder msg = new StringBuilder("[START] method: ")
.append(joinPoint.getSignature().getName()).append("() @ ")
.append(joinPoint.getTarget().getClass().getName());
this.appendMessage(msg);
LOGGER.info(msg);
}
/**
* Do after throwing.
*
* @param joinPoint the join point
* @param throwable the throwable
*/
public void doAfterThrowing(JoinPoint joinPoint, Throwable throwable) {
StringBuilder msg = new StringBuilder("[THROW] method: ")
.append(joinPoint.getSignature().getName()).append(" : ").append(throwable.getMessage()).append("() @ ")
.append(joinPoint.getTarget().getClass().getName());
this.appendMessage(msg);
LOGGER.info(msg);
}
private void appendMessage(StringBuilder msg) {
if (//ActionContext.getContext() == null &&
RequestContextHolder.getRequestAttributes() == null) {
return;
}
HttpServletRequest request =
//ActionContext.getContext() != null
//? (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST)
//:
((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
if (request == null) {
return;
}
/*HttpServletResponse response = ActionContext.getContext() != null
? (HttpServletResponse) ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE)
: ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();*/
msg.append("; ip -> ").append(WebUtils.getIp(request));
HttpSession session = request.getSession();
if (session == null) {
return;
}
String username = (String) session.getAttribute(KeyConstants.USERNAME.getKey());
msg.append("; user -> ").append(username);
}
}
|
package org.buaa.ly.MyCar.exception;
import org.buaa.ly.MyCar.http.ResponseStatusMsg;
public class DuplicateError extends BaseError {
public DuplicateError(String msg) {
super(ResponseStatusMsg.DUPLICATE_ERROR.getStatus(), msg);
}
public DuplicateError() {
super(ResponseStatusMsg.DUPLICATE_ERROR);
}
}
|
package eg.edu.alexu.csd.oop.db;
public interface Command {
public Boolean execute(String column , String value);
}
|
package com.vilio.nlbs.util;
import org.apache.commons.compress.archivers.zip.Zip64Mode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.log4j.Logger;
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* Created by xingwei on 2017/2/21.
*/
public class CompressUtil {
private Logger logger = Logger.getLogger(CompressUtil.class);
static final int BUFFER = 8192;
private File zipFile;
/**
* 压缩文件构造函数
* @param pathName 压缩的文件存放目录
*/
public CompressUtil(String pathName) {
zipFile = new File(pathName);
}
/**
* 执行压缩操作
* @param srcPathName 被压缩的文件/文件夹
*/
public void compressExe(String srcPathName) {
File file = new File(srcPathName);
if (!file.exists()){
throw new RuntimeException(srcPathName + "不存在!");
}
try {
ZipArchiveOutputStream out = new ZipArchiveOutputStream(zipFile);
String basedir = "";
compressByType(file, out, basedir);
out.finish();
out.close();
} catch (Exception e) {
e.printStackTrace();
logger.error("执行压缩操作时发生异常:"+e);
throw new RuntimeException(e);
}
}
public void compressExe(String srcPathName,ZipArchiveOutputStream out,String fileName) {
File file = new File(srcPathName);
if (!file.exists()){
throw new RuntimeException(srcPathName + "不存在!");
}
try {
compressFiles2Zip(file, out, fileName);
} catch (Exception e) {
e.printStackTrace();
logger.error("执行压缩操作时发生异常:"+e);
throw new RuntimeException(e);
}
}
/**
* 执行压缩操作 仅针对输入流
*
*/
// public void compressExe(OutputStream os,InputStream is,String fileName) {
// try {
// String basedir = "";
//// compressByType(file, out, basedir);
// compressFiles2Zip(is,os,fileName);
// } catch (Exception e) {
// e.printStackTrace();
// logger.error("执行压缩操作时发生异常:"+e);
// throw new RuntimeException(e);
// }
// }
/**
* 判断是目录还是文件,根据类型(文件/文件夹)执行不同的压缩方法
* @param file
* @param out
* @param basedir
*/
private void compressByType(File file, ZipArchiveOutputStream out, String basedir) {
/* 判断是目录还是文件 */
if (file.isDirectory()) {
logger.info("压缩:" + basedir + file.getName());
this.compressDirectory(file, out, basedir);
} else {
logger.info("压缩:" + basedir + file.getName());
this.compressFiles2Zip(file, out, basedir);
}
}
/**
* 压缩一个目录
* @param dir
* @param out
* @param basedir
*/
private void compressDirectory(File dir, ZipArchiveOutputStream out, String basedir) {
if (!dir.exists()){
return;
}
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
/* 递归 */
compressByType(files[i], out, basedir + dir.getName() + "/");
}
}
/**
* 压缩一个文件流
* @param fileIs 文件的输入流
* @param fileName 待压缩文件的名字
* @param out
* @param basedir
*/
private void compressFile(InputStream fileIs, String fileName , ZipOutputStream out, String basedir) {
try {
BufferedInputStream bis = new BufferedInputStream(fileIs);
ZipEntry entry = new ZipEntry(basedir + fileName);
out.putNextEntry(entry);
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
bis.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 压缩一个文件
* @param file
* @param out
* @param basedir
*/
private void compressFile(File file, ZipOutputStream out, String basedir) {
if (!file.exists()) {
return;
}
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
ZipEntry entry = new ZipEntry(basedir + file.getName());
out.putNextEntry(entry);
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
bis.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void compressFiles2Zip(File file, ZipArchiveOutputStream zaos, String fileName) {
try {
//Use Zip64 extensions for all entries where they are required
zaos.setUseZip64(Zip64Mode.AsNeeded);
//将每个文件用ZipArchiveEntry封装
//再用ZipArchiveOutputStream写到压缩文件中
if (file != null) {
ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(file, fileName);
zaos.putArchiveEntry(zipArchiveEntry);
InputStream is = null;
try {
if (!fileName.endsWith("\\")) {
is = new FileInputStream(file);
byte[] buffer = new byte[1024 * 5];
int len = -1;
while ((len = is.read(buffer)) != -1) {
//把缓冲区的字节写入到ZipArchiveEntry
zaos.write(buffer, 0, len);
}
}
//Writes all necessary data for this entry.
zaos.closeArchiveEntry();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (is != null)
is.close();
}
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
}
}
}
|
package edu.northwestern.u.andrewacomb2021.kevinproto;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Results extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
Button btnReturn = (Button)findViewById(R.id.btnReturn);
btnReturn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Results.this, Preview.class);
startActivity(intent);
}
});
}
}
|
/* */ package de.stuuupiiid.dungeonpack;
/* */
/* */ import java.util.Random;
import net.minecraft.util.ResourceLocation;
/* */
/* */
/* */
/* */
/* */ public class DungeonGeneratorSpiderBox
/* */ extends DungeonGenerator
/* */ {
/* */ public boolean generate(Random random, int par1, int par2, int par3)
/* */ {
/* 13 */ for (int v1 = -4; v1 < 5; v1++) {
/* 14 */ for (int v2 = -4; v2 < 5; v2++) {
/* 15 */ addBlock(par1 + v1, par2 - 1, par3 + v2, 2);
/* */
/* 17 */ for (int v3 = -7; v3 < -1; v3++) {
/* 18 */ if (isAir(par1 + v1, par2 + v3, par3 + v2)) {
/* 19 */ addBlock(par1 + v1, par2 + v3, par3 + v2, 3);
/* */ }
/* */ }
/* */ }
/* */ }
/* */
/* 25 */ for (int v1 = -3; v1 < 4; v1++) {
/* 26 */ for (int v2 = -3; v2 < 4; v2++) {
/* 27 */ for (int v3 = -5; v3 < -2; v3++) {
/* 28 */ addAir(par1 + v1, par2 + v3, par3 + v2);
/* 29 */ addAir(par1, par2 + v1, par3);
/* 30 */ if ((isAir(par1 + v1, par2 + v3, par3 + v2)) && (random.nextInt(4) == 0)) {
/* 31 */ addBlock(par1 + v1, par2 + v3, par3 + v2, 30);
/* */ }
/* */ }
/* */ }
/* */ }
/* */
/* 37 */ for (int v1 = -1; v1 < 2; v1++) {
/* 38 */ addBlock(par1 + v1, par2, par3 + 1, 4);
/* 39 */ addBlock(par1 + v1, par2, par3 - 1, 4);
/* 40 */ addBlock(par1 + 1, par2, par3 + v1, 4);
/* 41 */ addBlock(par1 - 1, par2, par3 + v1, 4);
/* 42 */ addBlock(par1 + v1, par2 + 1, par3 + 1, 4);
/* 43 */ addBlock(par1 + v1, par2 + 1, par3 - 1, 4);
/* 44 */ addBlock(par1 + 1, par2 + 1, par3 + v1, 4);
/* 45 */ addBlock(par1 - 1, par2 + 1, par3 + v1, 4);
/* */ }
/* */
/* 48 */ addBlock(par1 + 1, par2 + 2, par3, 4);
/* 49 */ addBlock(par1 - 1, par2 + 2, par3, 4);
/* 50 */ addBlock(par1, par2 + 2, par3 + 1, 4);
/* 51 */ addBlock(par1, par2 + 2, par3 - 1, 4);
/* 52 */ addBlock(par1 + 1, par2, par3 + 2, 4);
/* 53 */ addBlock(par1 + 1, par2, par3 - 2, 4);
/* 54 */ addBlock(par1 - 1, par2, par3 + 2, 4);
/* 55 */ addBlock(par1 - 1, par2, par3 - 2, 4);
/* 56 */ addBlock(par1 + 2, par2, par3 + 1, 4);
/* 57 */ addBlock(par1 - 2, par2, par3 + 1, 4);
/* 58 */ addBlock(par1 + 2, par2, par3 - 1, 4);
/* 59 */ addBlock(par1 - 2, par2, par3 - 1, 4);
/* 60 */ addMobSpawner(par1 - 3, par2 - 5, par3 + 3, new ResourceLocation("CaveSpider"));
/* 61 */ addMobSpawner(par1 + 3, par2 - 5, par3 - 3, new ResourceLocation("CaveSpider"));
/* 62 */ addChestWithDefaultLoot(random, par1 + 3, par2 - 5, par3 + 3);
/* 63 */ addChestWithDefaultLoot(random, par1 - 3, par2 - 5, par3 - 3);
/* 64 */ return true;
/* */ }
/* */ }
/* Location: C:\Users\IyadE\Desktop\Mod Porting Tools\dungeonpack-1.8.jar!\de\stuuupiiid\dungeonpack\DungeonGeneratorSpiderBox.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ |
package javaFile;
import java.io.*;
import javaFile.bean.QuizItem;
import javaFile.mapper.QuizItemMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class Generator {
public void operateDirectory(final File directory) {
if (directory.exists() && directory.isDirectory()) {
System.out.println("this is an existing directory");
}
}
public void checkJson(final File directory) throws IOException, ParseException {
File[] fList = directory.listFiles();
for (int i = 0; i < 10; i++) {
String fileName = fList[i].getName();
if (fList[i].isFile() && (fileName.substring(fileName.lastIndexOf(".") + 1)).equals("json")) {
this.readJson(fList[i], fList[i + 1]);
System.out.println("this is a json file");
}
}
}
public void readJson(File jsonFile, File pictureFile) throws IOException, ParseException{
JSONParser parser = new JSONParser();
JSONObject logicPuzzle = (JSONObject)parser.parse(new FileReader(jsonFile));
QuizItem quizItem = new QuizItem();
String stepsString = (String) logicPuzzle.get("steps_string");
int count = Integer.parseInt(String.valueOf(logicPuzzle.get("count")));
String questionZh = (String) logicPuzzle.get("question_zh");
int stepsLength = Integer.parseInt(String.valueOf(logicPuzzle.get("steps_length")));
int maxUpdateTimes = Integer.parseInt(String.valueOf(logicPuzzle.get("max_update_times")));
String answer = String.valueOf(logicPuzzle.get("answer"));
String descZh = logicPuzzle.get("desc_zh").toString();
String chartPath = pictureFile.getPath();
String infoPath = jsonFile.getPath();
quizItem.setAnswer(answer);
quizItem.setChartPath(chartPath);
quizItem.setCount(count);
quizItem.setDescriptionZh(descZh);
quizItem.setInfoPath(infoPath);
quizItem.setMaxUpdateTimes(maxUpdateTimes);
quizItem.setQuestionZh(questionZh);
quizItem.setStepsLength(stepsLength);
quizItem.setStepsString(stepsString);
this.insertJsonToDatabase(quizItem);
}
public void insertJsonToDatabase(QuizItem quizItem) throws IOException{
String resource = "resources/mybatis/config_mybatis.xml";
Reader reader = Resources.getResourceAsReader(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sqlSessionFactory.openSession();
final QuizItemMapper quizItemMapper = sqlSession
.getMapper(QuizItemMapper.class);
quizItemMapper.insertQuizItem(quizItem);
sqlSession.commit();
sqlSession.close();
}
public static void main(String[] args) throws IOException, ParseException {
Generator generator = new Generator();
File directory = new File("/Users/twer/works/generate-logic-puzzle/logic-puzzle");
generator.operateDirectory(directory);
generator.checkJson(directory);
}
}
|
package com.excilys.formation.cdb.core.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Classe représentant une company avec ses différentes valeurs.
*
* @author kylian
*
*/
@Entity
@Table(name = "company")
public class Company {
/**
* L'id de la company.
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
/**
* Le nom de la company.
*/
@Column(name = "name")
private String name;
/**
* Constructeur vide d'une company.
*/
private Company() {
}
private Company(Company company) {
this.id = company.getId();
this.name = company.getName();
}
public static class CompanyBuilder {
private Long id;
private String name;
public CompanyBuilder(Long id) {
this.id = id;
}
public CompanyBuilder withName(String name) {
this.name = name;
return this;
}
public Company build() {
Company company = new Company();
company.id = this.id;
company.name = this.name;
return company;
}
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return "Company index : " + id + " , name " + name + "\n";
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
try {
if (!Class.forName(this.getClass().getName()).isInstance(obj)) {
return false;
}
} catch (ClassNotFoundException e) {
return false;
}
Company other = (Company) obj;
if (this.id != other.getId()) {
return false;
}
if ((this.name == null && other.getName() != null)
|| (this.name != null && !this.name.equals(other.getName()))) {
return false;
}
return true;
}
@Override
public int hashCode() {
int value = 17;
int result = 1;
result = value * result + ((this.getId() == null) ? 0 : this.getId().hashCode());
result = value * result + ((this.getName() == null) ? 0 : this.getName().hashCode());
return result;
}
}
|
package web.services;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import web.models.User;
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserService userService;
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
User user = userService.getUserByName(s);
UserDetails userDetails = new org.springframework.security.core.userdetails
.User(user.getName(), user.getPassword(), user.getAuthorities());
return userDetails;
}
}
|
package com.company;
import java.util.ArrayList;
import java.util.HashMap;
public class Floor {
private int level;
private String descr;
private ArrayList<Room> rooms;
private HashMap<String, Double> optionCost = new HashMap<>();
private HashMap<String, Integer> selection = new HashMap<>();
public Integer chooseFloor(String fl) {
selection.put("carpet", 0);
selection.put("tile", 1);
selection.put("wood", 2);
return selection.get(fl);
}
public Double getOptionCost(String str) {
optionCost.put("carpet", 0.0);
optionCost.put("tile", 50.0);
optionCost.put("wood", 75.0);
return optionCost.get(str);
}
// Constructors
public Floor() {
int level = -1;
String descr = "";
rooms = new ArrayList<Room>();
}
public Floor(int level, String descr, ArrayList<Room> rooms) {
this.level = level;
this.descr = descr;
this.rooms = rooms;
}
public Floor(int level, String descr) {
this.level = level;
this.descr = descr;
}
public Room createRoom() {
Room room = new Room();
return room;
}
public Room createRoom(String type, String floor, ArrayList<Window> win, ArrayList<Door> door, int sqFt ) {
Room room = new Room(type, floor, win, door, sqFt);
return room;
}
public void addRoom(Room room) {
rooms.add(room);
}
}
|
package com.example.postgresdemo.model.AutoData;
public enum DataEntityStatusEnum {
PENDENTE(1),
EXECUTADO(2),
ERRO(3);
private final Integer status;
private DataEntityStatusEnum(Integer status) {
this.status = status;
}
public int getStatus() {
return this.status;
}
}
|
package top.zeroyiq.master_help_me.adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import top.zeroyiq.master_help_me.R;
import top.zeroyiq.master_help_me.models.MessageBody;
/**
* 消息适配器
* Created by ZeroyiQ on 2017/9/12.
*/
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {
private List<MessageBody> bodyList;
public MessageAdapter(List<MessageBody> bodyList) {
this.bodyList = bodyList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_message, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
MessageBody body = bodyList.get(position);
holder.tvMessageTitle.setText(body.getTitle()); // 标题
holder.tvMessageAnswerer.setText(body.getAnswerer()); // 回答者
holder.tvContent.setText(body.getContent()); // 内容
holder.tvMessageDate.setText(body.getDate()); // 时间
}
@Override
public int getItemCount() {
return bodyList.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.tv_message_title)
TextView tvMessageTitle;
@BindView(R.id.tv_message_answerer)
TextView tvMessageAnswerer;
@BindView(R.id.tv_message_content)
TextView tvContent;
@BindView(R.id.tv_message_date)
TextView tvMessageDate;
public ViewHolder(View view) {
super(view);
ButterKnife.bind(this, view);
}
}
}
|
package StockMarket;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ShareTest {
Share share;
@Test
void testSetAndGetSharePrice() {
Share share = new Share("Test Company Name", "Test Commodity", (double)1.23);
share.setSharePrice((double)1.23);
assertTrue(share.getSharePrice() == (double)1.23);
}
@Test
void testSetAndGetCompanyName() {
Share share = new Share("Test Company Name", "Test Commodity", (double)1.23);
share.setCompanyName("Test");
assertTrue(share.getCompanyName().equals("Test"));
}
@Test
void testSetAndGetCommodity() {
Share share = new Share("Test Company Name", "Test Commodity", (double)1.23);
share.setCommodity("Test");
assertTrue(share.getCommodity().equals("Test"));
}
}
|
package com.tencent.mm.protocal;
import com.tencent.mm.protocal.c.g;
public class c$fz extends g {
public c$fz() {
super("pauseDownloadTask", "cancel_download_task", 239, false);
}
}
|
package com.jc.databinding.module.listview;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.jc.databinding.R;
import com.jc.databinding.module.listview.bean.ItemBean;
import com.jc.databinding.module.listview.bean.ItemHeaderBean;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jktaihe on 14/6/17.
* blog: blog.jktaihe.com
*/
public class RecyclerViewPage extends Activity {
RecyclerView recyclerView;
RecyclerAdapter mAdapter;
public static final String avter = "http://img.tupianzj.com/uploads/allimg/160403/9-160403122105.jpg";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_recyclerview);
recyclerView = (RecyclerView) findViewById(R.id.rv);
mAdapter = new RecyclerViewAdapter();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(mAdapter);
addData();
}
private void addData() {
List<Object> list = new ArrayList<>();
list.add(new ItemHeaderBean("this is header",20));
list.add(new ItemBean("sala",21,avter));
list.add(new ItemBean("toom",20,avter));
list.add(new ItemBean("to2",20,avter));
list.add(new ItemBean("sls",20,avter));
list.add(new ItemBean("dfjk",20,avter));
list.add(new ItemBean("sfs",20,avter));
list.add(new ItemBean("sfd",20,avter));
list.add(new ItemBean("sff",20,avter));
list.add(new ItemBean("fsd",20,avter));
list.add(new ItemBean("sea",20,avter));
mAdapter.setList(list);
}
}
|
package com.company.carseller.database;
import com.company.carseller.entity.User;
import org.apache.log4j.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class UserDAO {
final static Logger logger = Logger.getLogger(UserDAO.class);
public static final String SELECT_ALL_USER = "SELECT * FROM User";
public static final String SELECT_USER_BY_USERNAME = "SELECT * FROM User WHERE username = ?";
public static final String UPDATE_USER = "UPDATE User SET username = ?, password = ?, first_name = ?, second_name = ?, phone_number = ?, role = ? WHERE user_id = ?";
public static final String DELETE_USER = "DELETE FROM Uses WHERE user_id = ?";
public static final String INSERT_USER = "INSERT INTO User(username, password, first_name, second_name, phone_number, role) VALUES (?,?,?,?,?,?)";
public List<User> getAll() {
List<User> list = new ArrayList<>();
ConnectionPool pool = null;
Connection connection = null;
try {
ConnectionPool.init();
pool = ConnectionPool.getInstance();
connection = pool.takeConnection();
try (PreparedStatement preparedStatement = connection.prepareStatement(SELECT_ALL_USER)){
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
User user = new User();
user.setUserId(resultSet.getInt(1));
user.setUsername(resultSet.getString(2));
user.setPassword(resultSet.getString(3));
user.setFirstName(resultSet.getString(4));
user.setSecondName(resultSet.getString(5));
user.setPhoneNumber(resultSet.getString(6));
user.setRole(resultSet.getString(7));
list.add(user);
}
}
pool.returnConnection(connection);
} catch (SQLException e) {
logger.error(e);
}
return list;
}
public User getUserByUsername(String username) {
User user = new User();
ConnectionPool pool = null;
Connection connection = null;
try {
ConnectionPool.init();
pool = ConnectionPool.getInstance();
connection = pool.takeConnection();
try (PreparedStatement preparedStatement = connection.prepareStatement(SELECT_USER_BY_USERNAME)) {
preparedStatement.setString(1, username);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
user.setUserId(resultSet.getInt(1));
user.setUsername(resultSet.getString(2));
user.setPassword(resultSet.getString(3));
user.setFirstName(resultSet.getString(4));
user.setSecondName(resultSet.getString(5));
user.setPhoneNumber(resultSet.getString(6));
user.setRole(resultSet.getString(7));
}
}
pool.returnConnection(connection);
} catch (SQLException e) {
logger.error(e);
}
return user;
}
public void update(User user) {
ConnectionPool pool = null;
Connection connection = null;
try {
ConnectionPool.init();
pool = ConnectionPool.getInstance();
connection = pool.takeConnection();
try(PreparedStatement preparedStatement = connection.prepareStatement(UPDATE_USER)) {
preparedStatement.setString(1,user.getUsername());
preparedStatement.setString(2, user.getPassword());
preparedStatement.setString(3, user.getFirstName());
preparedStatement.setString(4, user.getSecondName());
preparedStatement.setString(5, user.getPhoneNumber());
preparedStatement.setString(6, user.getRole());
preparedStatement.setInt(7, user.getUserId());
preparedStatement.executeUpdate();
}
pool.returnConnection(connection);
} catch (SQLException e) {
logger.error(e);
}
}
public void delete(int id) {
ConnectionPool pool = null;
Connection connection = null;
try {
ConnectionPool.init();
pool = ConnectionPool.getInstance();
connection = pool.takeConnection();
try (PreparedStatement preparedStatement = connection.prepareStatement(DELETE_USER)){
preparedStatement.setInt(1, id);
preparedStatement.executeUpdate();
}
pool.returnConnection(connection);
} catch (SQLException e) {
logger.error(e);
}
}
public void insert(User user) {
ConnectionPool pool = null;
Connection connection = null;
try {
ConnectionPool.init();
pool = ConnectionPool.getInstance();
connection = pool.takeConnection();
try (PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USER)) {
preparedStatement.setString(1, user.getUsername());
preparedStatement.setString(2, user.getPassword());
preparedStatement.setString(3, user.getFirstName());
preparedStatement.setString(4, user.getSecondName());
preparedStatement.setString(5, user.getPhoneNumber());
preparedStatement.setString(6, user.getRole());
preparedStatement.executeUpdate();
}
pool.returnConnection(connection);
} catch (SQLException e) {
logger.error(e);
}
}
}
|
package view;
import view.validators.ValidSSN;
import controller.Controller;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.inject.Inject;
import javax.inject.Named;
import view.validators.ValidEmail;
/**
* Klassen behandlar alla registreringar som görs via vyn.
*/
@Named("registerManager")
@ConversationScoped
public class RegisterManager implements Serializable
{
private static final long serialVersionUID = 16247164405L;
@EJB
Controller controller;
private String name;
private String surname;
@ValidSSN
private String ssn;
@ValidEmail
private String email;
private String username;
private String password;
private String repeatPassword;
private Boolean registerSuccess = false;
private Boolean showPasswordMessage;
private Boolean showMessage;
private Boolean registrationFailed = false;
@Inject
private Conversation conversation;
/**
* Conversation scoped bean start.
* Alla värden sparas.
*/
private void startConversation() {
if (conversation.isTransient()) {
conversation.begin();
}
}
/**
* Conversation scoped bean stop.
* Alla sparade värden tas bort.
*/
private void stopConversation() {
if (!conversation.isTransient()) {
conversation.end();
}
}
/**
* Conversation scoped bean end.
* Anropar stopConversation och avbryter registreringen.
*/
public void endConversation()
{
stopConversation();
registrationFailed = false;
}
/**
* Skriver in användarens förnamn.
* @param name Namn
*/
public void setName(String name){
this.name = name;
}
/**
* Returnerar användarens förnamn.
* @return Namn
*/
public String getName(){
return name;
}
/**
* Skriver in användarens efternamn.
* @param surname Efternamn
*/
public void setSurname(String surname){
this.surname = surname;
}
/**
* Returnerar användarens efternamn.
* @return Efternamn
*/
public String getSurname(){
return surname;
}
/**
* Skriver in användarens personnummer.
* @param ssn Personnummer
*/
public void setSsn(String ssn){
this.ssn = ssn;
}
/**
* Returnerar användarens personnummer.
* @return Personnummer
*/
public String getSsn(){
return ssn;
}
/**
* Skriver in användarens E-post adress.
* @param email E-post adress
*/
public void setEmail(String email){
this.email = email;
}
/**
* Returnerar användarens E-post adress.
* @return E-post adress
*/
public String getEmail(){
return email;
}
/**
* Skriver in användarens användarnamn.
* @param username Användarnamn
*/
public void setUsername(String username){
this.username = username;
}
/**
* Returnerar användarens användarnamn.
* @return Användarnamn
*/
public String getUsername(){
return username;
}
/**
* Skriver in användarens lösenord.
* @param password Lösenord
*/
public void setPassword(String password){
this.password = password;
}
/**
* Returnerar användarens lösenord.
* @return Lösenord
*/
public String getPassword(){
return password;
}
/**
* Skriver in användarens verifiering av lösenord.
* @param repeatPassword Verifiera lösenord
*/
public void setRepeatPassword(String repeatPassword){
this.repeatPassword = repeatPassword;
}
/**
* Returnerar användarens verifierade lösenord.
* @return Verifierat lösenord
*/
public String getRepeatPassword(){
return repeatPassword;
}
/**
* Skriver in en typ av meddelande. Parametern är en boolean.
* @param show Meddelande
*/
public void setShowMessage(Boolean show){
this.showMessage = show;
}
/**
* Är av typen boolean. Returnerar ett meddelande om True.
* @return TrueOrFalse
*/
public Boolean getShowMessage(){
return showMessage;
}
/**
* Är av typen boolean. Returnerar True om registreringen är godkänd.
* @return TrueOrFalse
*/
public Boolean getRegisterSuccess(){
return registerSuccess;
}
/**
* Skriver in lösenordsmeddelande. Parametern är av typen boolean.
* @param show TrueOrFalse
*/
public void setShowPasswordMessage(Boolean show){
this.showPasswordMessage = show;
}
/**
* Är av typen boolean. Returnerar True om meddelande ska visas om
* lösenordet gått igenom.
* @return TrueOrFalse
*/
public Boolean getShowPasswordMessage(){
return showPasswordMessage;
}
/**
* Checkar om det inskrivna lösenordet i första lösenords boxen
* matchar med det andra lösenordet i den andra lösenords boxen.
* Om båda _inte_ matchar skrivs lösenordsmeddelande ut.
* @return JSF version 2.2 bug - Returnerar tom sträng
*/
public String register()
{
if(!(password.equals(repeatPassword)))
{
showPasswordMessage = true;
return "";
}
try
{
controller.register(name, surname, ssn, email, username, password);
registerSuccess = true;
registrationFailed = false;
}
catch(Exception e)
{
startConversation();
name = null;
surname = null;
username = null;
email = null;
ssn = null;
registrationFailed = true;
registerSuccess = false;
}
return "";
}
/**
* Meddelar om registreringen lyckades eller inte.
* @return true om registreringen lyckades, annars false
*/
public Boolean getRegistrationFailed()
{
return registrationFailed;
}
/**
* Anger om registreringen lyckades eller inte.
* @param regFailed true om registreringen lyckades, annars false
*/
public void setRegistrationFailed(Boolean regFailed)
{
this.registrationFailed = regFailed;
}
}
|
package test.android.kubra.com.kubraandroidtest.network;
/**
* This helps to maintain single WebService client instance across the application
*/
public class RestClientManager {
private WebServices mWebServiceClient;
private static RestClientManager mRestClientManager;
public static RestClientManager getInstance() {
if(mRestClientManager==null){
mRestClientManager = new RestClientManager();
}
return mRestClientManager;
}
private RestClientManager() {
}
/**
* Get instance of web service client
* @return
*/
public WebServices getWebServiceClient(){
if(mWebServiceClient==null){
mWebServiceClient=RestClient.createService(WebServices.class);
}
return mWebServiceClient;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lappa.smsbanking.web.Beans;
import com.douwe.generic.dao.DataAccessException;
import java.io.InputStream;
import javax.persistence.NoResultException;
import java.lang.NullPointerException;
import java.io.Serializable;
import java.io.StringWriter;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import lappa.smsbanking.Entities.Adresse;
import lappa.smsbanking.Entities.Agence;
import lappa.smsbanking.Entities.Chequier;
import lappa.smsbanking.Entities.Compte;
import lappa.smsbanking.Entities.Emploi;
import lappa.smsbanking.Entities.OffreSpeciale;
import lappa.smsbanking.Entities.Operation;
import lappa.smsbanking.Entities.Personne;
import lappa.smsbanking.Entities.PersonneMorale;
import lappa.smsbanking.Entities.PersonnePhysique;
import lappa.smsbanking.Entities.Sms;
import lappa.smsbanking.Entities.SmsCompte;
import lappa.smsbanking.Entities.Virement;
import IServiceSupport.IServiceAdresse;
import IServiceSupport.IServiceAgence;
import IServiceSupport.IServiceChequier;
import IServiceSupport.IServiceCompte;
import IServiceSupport.IServiceEmploi;
import IServiceSupport.IServiceOffreSpeciale;
import IServiceSupport.IServiceOperation;
import IServiceSupport.IServicePersonne;
import IServiceSupport.IServicePersonneMoral;
import IServiceSupport.IServicePersonnePhys;
import IServiceSupport.IServiceVirement;
import lappa.smsbanking.Entities.CompteParent;
import lappa.smsbanking.IService.IServiceCompteParent;
import lappa.smsbanking.IService.IServiceSms;
import lappa.smsbanking.IService.IServiceSmsCompte;
import org.apache.commons.io.IOUtils;
/**
*
* @author lappa
*/
@ManagedBean
@SessionScoped
public class SearchBean implements Serializable {
@ManagedProperty(value = "#{serviceOperation}")
private IServiceOperation serviceOperation;
@ManagedProperty(value = "#{servicePersonne}")
private IServicePersonne servicePersonne;
@ManagedProperty(value = "#{serviceCompte}")
private IServiceCompte serviceCmpte;
@ManagedProperty(value = "#{serviceAgence}")
private IServiceAgence serviceAgence;
@ManagedProperty(value = "#{serviceAdresse}")
private IServiceAdresse serviceAdresse;
@ManagedProperty(value = "#{serviceSmsCompte}")
private IServiceSmsCompte serviceSmsCompte;
@ManagedProperty(value = "#{serviceSms}")
private IServiceSms serviceSms;
@ManagedProperty(value = "#{servicePersonnePhysique}")
private IServicePersonnePhys servicePersonnePhys;
@ManagedProperty(value = "#{servicePersonneMorale}")
private IServicePersonneMoral servicePersonneMoral;
@ManagedProperty(value = "#{serviceEmploi}")
private IServiceEmploi serviceEmploi;
@ManagedProperty(value = "#{serviceChequier}")
private IServiceChequier serviceChequier;
@ManagedProperty(value = "#{serviceOffreSpeciale}")
private IServiceOffreSpeciale serviceOffreSpeciale;
@ManagedProperty(value = "#{serviceVirement}")
private IServiceVirement serviceVirement;
@ManagedProperty(value = "#{serviceCompteParent}")
private IServiceCompteParent serviceCompteParent;
private List<Operation> operations;
private List<Operation> opers;
private Operation operation;
private SmsBean sm;
private CompteParent compteParent;
private List<Adresse> adresses;
private Adresse adresse;
private List<Agence> agences;
private Agence agence;
private List<Chequier> chequiers;
private Chequier cheque;
private List<Emploi> emplois;
private Emploi emploi;
private List<OffreSpeciale> offreSpeciales;
private OffreSpeciale offreSpeciale;
private List<Compte> comptes;
private Compte compte;
private Compte compteSrc;
private Compte compteDest;
private Long idClient;
private String code;
private Long idAgence;
private Chequier chequier;
private String numR;
private String numSrc;
private String numCmpte;
private String numDest;
private Date dateDebut;
private Date dateFin;
private PersonnePhysique personnePhysique;
private PersonneMorale personneMorale;
private Personne personne;
private List<PersonnePhysique> personnePhysiques;
private List<PersonneMorale> personneMorales;
private Long idPersPhys;
private Long idPersMorale;
private SmsCompte smsCompte;
private Sms sms;
private List<SmsCompte> smsComptes;
private List<CompteParent> compteParents;
private Virement virement;
private List<Virement> virements;
private Personne current;
private String passerelle = "localhost";
private String receip;
private String text;
private String username = "lappa";
private String nomAgence;
private String passwd = "lappa";
public SearchBean() {
chequier = new Chequier();
virement = new Virement();
sms = new Sms();
operation = new Operation();
personne = new Personne();
current = new Personne();
compte = new Compte();
compteSrc = new Compte();
compteDest = new Compte();
opers = new ArrayList<Operation>();
offreSpeciale = new OffreSpeciale();
smsCompte = new SmsCompte();
sm = new SmsBean();
}
public void updateAdresse(ActionEvent actionEven) throws DataAccessException {
int i = 0;
try {
current = servicePersonne.findByIdClient(personne.getIdClient());
if (current != null) {
Personne ps = servicePersonne.findByIdClient(personne.getIdClient());
adresse.setIdPersonne(ps);
adresse.setId(adresse.getId());
serviceAdresse.update(adresse);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "mise à jour avec succés", ""));
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, current.getNomClient() + " " + current.getIdClient() + " 'cette personne n'exite pas'", ""));
}
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "'ID Du Client' n'existe pas", ""));
}
}
public void updateUser(ActionEvent actionEven) throws DataAccessException {
int i = 0, j = 0;
try {
Agence a = serviceAgence.findByCodeAgence(personne.getCodeAgence());
try {
Personne p = servicePersonne.findByIdClient(personne.getIdClient());
if (a != null) {
if (p.getTypePersonne().equals("Physique") && p.getTypePersonne().equals(personne.getTypePersonne())) {
personne.setId(p.getId());
personne.setIdClient(p.getIdClient());
servicePersonne.update(personne);
Personne ps = servicePersonne.findByIdClient(personne.getIdClient());
personnePhysique.setIdPersonne(ps);
PersonnePhysique ph = servicePersonnePhys.findByCni(personnePhysique.getCni());
personnePhysique.setId(ph.getId());
servicePersonnePhys.update(personnePhysique);
j = 1;
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "mise à jour avec succés", ""));
} else {
i = 1;
}
if (p.getTypePersonne().equals("Morale") && p.getTypePersonne().equals(personne.getTypePersonne())) {
personne.setId(p.getId());
personne.setIdClient(p.getIdClient());
servicePersonne.update(personne);
Personne ps = servicePersonne.findByIdClient(personne.getIdClient());
personneMorale.setIdPersonne(ps);
PersonneMorale pm = servicePersonneMoral.findByNumEnregistrement(personneMorale.getNumEnregistrement());
personneMorale.setId(pm.getId());
servicePersonneMoral.update(personneMorale);
j = 2;
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "mise à jour réalisée avec succées", ""));
} else {
i = 2;
}
if (i == 1 && j == 0) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, " ce ID Client " + personne.getIdClient() + " appartient à une personne morale ou n'existe pas", ""));
}
if (i == 2 && j == 0) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "ce ID Client " + personne.getIdClient() + " appartient à une personne physique ou n'existe pas", ""));
}
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "code agence inexistant", ""));
}
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, personne.getNomClient() + " " + personne.getIdClient() + " 'cette personne n'exite pas'", ""));
}
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "code agence " + personne.getCodeAgence() + " inexistant", ""));
}
}
public String afficher() {
code = null;
numCmpte = null;
smsCompte = new SmsCompte();
compteParent=new CompteParent();
return "Search";
}
public void updateOffreSpeciale(ActionEvent actionEven) throws DataAccessException {
int i = 0;
try {
current = servicePersonne.findByIdClient(personne.getIdClient());
if (current != null) {
Personne ps = servicePersonne.findByIdClient(personne.getIdClient());
offreSpeciale.setIdPersonne(ps);
OffreSpeciale s = serviceOffreSpeciale.findByIdO(offreSpeciale.getId());
offreSpeciale.setId(offreSpeciale.getId());
serviceOffreSpeciale.update(offreSpeciale);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "mise à jour avec succés", ""));
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, current.getNomClient() + " " + current.getIdClient() + " 'cette personne n'exite pas'", ""));
}
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "'ID Du Client' n'existe pas", ""));
}
}
public void updateAgence(ActionEvent actionEven) throws DataAccessException {
int i = 0;
try {
Agence a = serviceAgence.findByCodeAgence(agence.getCodeAgence());
if (agence != null) {
agence.setId(a.getId());
serviceAgence.update(agence);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "mise à jour avec succés", ""));
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, current.getNomClient() + " " + current.getIdClient() + " 'cette personne n'exite pas'", ""));
}
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "'code agence' n'existe pas", ""));
}
}
public void updateEmploi(ActionEvent actionEven) throws DataAccessException {
int i = 0;
try {
current = servicePersonne.findByIdClient(personne.getIdClient());
if (current != null) {
Personne ps = servicePersonne.findByIdClient(personne.getIdClient());
emploi.setIdPersonne(ps);
emploi.setId(emploi.getId());
serviceEmploi.update(emploi);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "mise à jour avec succés", ""));
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, current.getNomClient() + " " + current.getIdClient() + " 'cette personne n'exite pas'", ""));
}
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "'ID Du Client' n'existe pas", ""));
}
}
public void updateCompte(ActionEvent actionEven) throws DataAccessException {
try {
Compte cmpte = serviceCmpte.findById(compte.getId());
compte.setId(cmpte.getId());
serviceCmpte.update(compte);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "mise à jour reussit", ""));
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "compte introuvable", ""));
}
}
public String updateSmsCompte(ActionEvent actionEven) throws DataAccessException, Exception {
int pin = sm.generCodePin();
SmsCompte s = serviceSmsCompte.findByIdClient((smsCompte.getIdClient()));
receip = smsCompte.getMobile();
smsCompte.setId(s.getId());
smsCompte.setPin(pin);
text = "Le+CREDIT+du+SAHEL+vous+informe+que+votre+compte+SMS,+votre+nouveau+code+PIN+est:+" + pin + "+.+Merci";
sendsms();
serviceSmsCompte.update(smsCompte);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "mise à jour avec succés", ""));
return "create";
}
public void updateVirement(ActionEvent actionEven) throws DataAccessException {
try {
personne = servicePersonne.findByCode(virement.getNumCompte());
compte = serviceCmpte.findById(personne.getId());
Virement s = serviceVirement.findByNumCompte(virement.getNumCompte());
virement.setId(s.getId());
virement.setIdCompte(compte);
serviceVirement.update(virement);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "mise à jour avec succés", ""));
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "'Numéro compte' n'existe pas", ""));
}
}
public void updateCheque(ActionEvent actionEven) throws DataAccessException {
try {
Agence a = serviceAgence.findByCodeAgence(personne.getCodeAgence());
try {
personne = servicePersonne.findByCode(personne.getCodeProduit());
cheque.setId(personne.getId());
serviceChequier.update(cheque);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, " mise à jour réalisée avec succées", ""));
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, " Code Client'" + personne.getCodeProduit() + "' introuvable", ""));
}
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "code agence " + personne.getCodeAgence() + " inexistant", ""));
}
}
public String searchOperation() throws DataAccessException {
int test = 0;
int i = 0;
int j = 0;
int k = 0;
opers = new ArrayList<Operation>();
try {
Agence a = serviceAgence.findByCodeAgence(code);
try {
personne = servicePersonne.findByCode(numCmpte);
SimpleDateFormat tmp = new SimpleDateFormat("dd/MM/yyyy");
String s1 = tmp.format(dateDebut);
String tm1 = s1.substring(6, 10);
String s2 = tmp.format(dateFin);
String tm2 = s2.substring(6, 10);
operations = getOperations();
for (Operation operation1 : operations) {
String s3 = tmp.format(operation1.getDateJour());
String tm3 = s3.substring(6, 10);
if (tm3.equals(tm2)) {
if (operation1.getIdPersonnePhysique() != null) {
if (operation1.getIdPersonnePhysique().getIdPersonne().getCodeProduit().equals(numCmpte)) {
opers.add(operation1);
j = 1;
}
}
if (operation1.getIdPersonneMoral() != null) {
if (operation1.getIdPersonneMoral().getIdPersonne().getCodeProduit().equals(numCmpte)) {
opers.add(operation1);
j = 1;
}
}
}
if (i == 0 && k == 0 && j == 0) {
opers.add(operation1);
test = 1;
}
if (j == 1) {
k = 1;
}
}
return "Search";
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "numéro compte '" + numCmpte + "' inexistant", ""));
}
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "code agence " + code + " inexistant", ""));
}
return null;
}
public String searchAdresse() throws DataAccessException {
try {
personne = servicePersonne.findByIdClient(code);
adresses = getAdresses();
if (!adresses.isEmpty()) {
for (Adresse adresse1 : adresses) {
if (adresse1.getIdPersonne().getId().equals(personne.getId())) {
adresse = serviceAdresse.findByIdA(adresse1.getId());
return "EditAdresse";
}
}
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Adresse inexistant", ""));
}
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Code " + code + " inexistant", ""));
}
return null;
}
public String searchCordonne() throws DataAccessException {
try {
Agence a = serviceAgence.findByCodeAgence(code);
try {
personne = servicePersonne.findByIdClient(smsCompte.getIdClient());
smsComptes = getSmsComptes();
if (!smsComptes.isEmpty()) {
for (SmsCompte smsCompte1 : smsComptes) {
if (smsCompte1.getIdClient().equals(smsCompte.getIdClient())) {
smsCompte = serviceSmsCompte.findByIdS(smsCompte1.getId());
return "search";
}
}
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Compte SMS " + smsCompte.getIdClient() + " inexistant", ""));
}
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, smsCompte.getIdClient() + " 'cette personne n'exite pas'", ""));
}
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Code " + code + " inexistant", ""));
}
return null;
}
public String searchCordonneCompteParent() throws DataAccessException {
try {
Agence a = serviceAgence.findByCodeAgence(code);
try {
personne = servicePersonne.findByIdClient(compteParent.getIdClient());
compteParents = getCompteParents();
if (!compteParents.isEmpty()) {
for (CompteParent compteParent1 : compteParents) {
if (compteParent1.getIdClient().equals(compteParent.getIdClient())) {
compteParent = serviceCompteParent.findById(compteParent1.getId());
return "search";
}
}
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Compte " + smsCompte.getIdClient() + " inexistant", ""));
}
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, smsCompte.getIdClient() + " 'cette personne n'exite pas'", ""));
}
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Code " + code + " inexistant", ""));
}
return null;
}
public String searchCheque() throws DataAccessException {
try {
personne = servicePersonne.findByIdClient(code);
try {
Chequier c = serviceChequier.findByNumReference(numR);
chequiers = getChequiers();
if (!chequiers.isEmpty()) {
for (Chequier chequier1 : chequiers) {
if (chequier1.getIdCompte().getIdPersonnePhysique().getIdPersonne().getId().equals(personne.getId())) {
cheque = serviceChequier.findByIdC(chequier1.getId());
compte = serviceCmpte.findById(cheque.getIdCompte().getId());
return "EditCheque";
}
if (chequier1.getIdCompte().getIdPersonneMoral().getIdPersonne().getId().equals(personne.getId())) {
chequier = serviceChequier.findByIdC(chequier1.getId());
compte = serviceCmpte.findByNumeroCompte(numR);
return "EditCheque";
}
}
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Numero Chèquier inexistant", ""));
}
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Numéro Chèquier Introuvable", ""));
}
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Code " + code + " inexistant", ""));
}
return null;
}
public String searchCompte() throws DataAccessException {
try {
personne = servicePersonne.findByCode(numCmpte);
comptes = getComptes();
if (!comptes.isEmpty()) {
for (Compte compte1 : comptes) {
if (compte1.getIdPersonnePhysique() != null) {
if (compte1.getIdPersonnePhysique().getIdPersonne().getId().equals(personne.getId())) {
compte = serviceCmpte.findById(compte1.getId());
return "EditCompte";
}
}
if (compte1.getIdPersonneMoral() != null) {
if (compte1.getIdPersonneMoral().getIdPersonne().getId().equals(personne.getId())) {
compte = serviceCmpte.findById(compte1.getId());
return "EditCompte";
}
}
}
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "aucun compte existant", ""));
}
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Numéro Compte '" + numCmpte + "' inexistant", ""));
}
return null;
}
public String searchEmploi() throws DataAccessException {
try {
personne = servicePersonne.findByIdClient(code);
emplois = getEmplois();
if (!emplois.isEmpty()) {
for (Emploi emploi1 : emplois) {
if (emploi1.getIdPersonne().getId().equals(personne.getId())) {
emploi = serviceEmploi.findByIdE(emploi1.getId());
return "EditEmploi";
}
}
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Emploi inexistant", ""));
}
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Code " + code + " inexistant", ""));
}
return null;
}
public String searchAgence() throws DataAccessException {
try {
agence = serviceAgence.findByCodeAgence(code);
return "EditAgence";
} catch (NullPointerException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Code " + code + " inexistant", ""));
}
return null;
}
public String searchOffre() throws DataAccessException {
try {
personne = servicePersonne.findByIdClient(code);
offreSpeciales = getOffreSpeciales();
if (!offreSpeciales.isEmpty()) {
for (OffreSpeciale offreSpeciale1 : offreSpeciales) {
if (offreSpeciale1.getIdPersonne().getId().equals(personne.getId())) {
offreSpeciale = serviceOffreSpeciale.findByIdO(offreSpeciale1.getId());
return "EditOffre";
}
}
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Offre inexistant", ""));
}
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Code " + code + " inexistant", ""));
}
return null;
}
public String searchUser() throws DataAccessException {
try {
Personne p = servicePersonne.findByIdClient(code);
if (p.getTypePersonne().equals("Physique")) {
personnePhysiques = getPersonnePhysiques();
if (!personnePhysiques.isEmpty()) {
for (PersonnePhysique personnePhysique1 : personnePhysiques) {
if (personnePhysique1.getIdPersonne().getId().equals(p.getId())) {
personne = servicePersonne.findByIdClient(code);
personnePhysique = servicePersonnePhys.findByIdP(personnePhysique1.getId());
return "EditPersPhys";
}
}
} else {
personne = servicePersonne.findByIdClient(code);
personnePhysique = servicePersonnePhys.findByIdP(personnePhysique.getId());
return "EditPersPhys";
}
} else {
personneMorales = getPersonneMorales();
if (!personneMorales.isEmpty()) {
for (PersonneMorale personneMorale1 : personneMorales) {
if (personneMorale1.getIdPersonne().getId().equals(p.getId())) {
personne = servicePersonne.findByIdClient(code);
personneMorale = servicePersonneMoral.findByIdP(personneMorale1.getId());
return "EditPersMorale";
}
}
} else {
personne = servicePersonne.findByIdClient(code);
personneMorale = servicePersonneMoral.findByIdP(personneMorale.getId());
return "EditPersMorale";
}
}
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Code " + code + " inexistant", ""));
}
return null;
}
public String searchSmsCompte() throws DataAccessException {
try {
Agence a = serviceAgence.findByCodeAgence(code);
try {
personne = servicePersonne.findByIdClient(smsCompte.getIdClient());
smsComptes = getSmsComptes();
if (!smsComptes.isEmpty()) {
for (SmsCompte smsCompte1 : smsComptes) {
if (smsCompte1.getIdClient().equals(smsCompte.getIdClient())) {
smsCompte = serviceSmsCompte.findByIdS(smsCompte1.getId());
return "EditSmsCompte";
}
}
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Compte SMS " + smsCompte.getIdClient() + " inexistant", ""));
}
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, smsCompte.getIdClient() + " 'cette personne n'exite pas'", ""));
}
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Code " + code + " inexistant", ""));
}
return null;
}
public String searchVirement() throws DataAccessException {
try {
compte = serviceCmpte.findByNumeroCompte(virement.getNumControle());
try {
virement = serviceVirement.findByCodeFichier(virement.getCodeFichier());
virements = getVirements();
if (!virements.isEmpty()) {
for (Virement virement1 : virements) {
if (virement1.getCodeDocument().equals(virement.getCodeDocument())) {
virement = serviceVirement.findByIdV(virement1.getId());
return "EditVirement";
}
}
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Compte SMS " + smsCompte.getIdClient() + " inexistant", ""));
}
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Code fichier n'exite pas'", ""));
}
} catch (NoResultException ex) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "Numéro compte " + virement.getNumCompte() + " introuvable", ""));
}
return null;
}
public IServicePersonne getServicePersonne() {
return servicePersonne;
}
public void delete() throws DataAccessException {
Operation o = serviceOperation.findById(operation.getId());
serviceOperation.delete(o.getId());
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "suppréssion réalisée avec succés", ""));
}
public void sendsms() throws Exception {
String theUrl = "http://" + passerelle + ":14000/cgi-bin/sendsms?username=" + username + "&password=" + passwd + "&to=" + receip + "&text=" + text + "";
InputStream inputStream = null;
StringWriter stringWriter = null;
URL url = new URL(theUrl);
inputStream = url.openStream();
stringWriter = new StringWriter();
IOUtils.copy(inputStream, stringWriter);
stringWriter.toString();
}
public List<Virement> getVirements() throws DataAccessException {
virements = serviceVirement.findAll();
return virements;
}
public void setVirements(List<Virement> virements) {
this.virements = virements;
}
public String getPasserelle() {
return passerelle;
}
public void setPasserelle(String passerelle) {
this.passerelle = passerelle;
}
public String getReceip() {
return receip;
}
public void setReceip(String receip) {
this.receip = receip;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getNomAgence() {
return nomAgence;
}
public void setNomAgence(String nomAgence) {
this.nomAgence = nomAgence;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public IServiceCompteParent getServiceCompteParent() {
return serviceCompteParent;
}
public void setServiceCompteParent(IServiceCompteParent serviceCompteParent) {
this.serviceCompteParent = serviceCompteParent;
}
public CompteParent getCompteParent() {
return compteParent;
}
public void setCompteParent(CompteParent compteParent) {
this.compteParent = compteParent;
}
public List<Operation> getOperations() throws DataAccessException {
operations = serviceOperation.findAll();
return operations;
}
public void setOperations(List<Operation> operations) {
this.operations = operations;
}
public List<Adresse> getAdresses() throws DataAccessException {
adresses = serviceAdresse.findAll();
return adresses;
}
public void setAdresses(List<Adresse> adresses) {
this.adresses = adresses;
}
public List<Chequier> getChequiers() throws DataAccessException {
chequiers = serviceChequier.findAll();
return chequiers;
}
public void setChequiers(List<Chequier> chequiers) {
this.chequiers = chequiers;
}
public List<Compte> getComptes() throws DataAccessException {
comptes = serviceCmpte.findAll();
return comptes;
}
public void setComptes(List<Compte> comptes) {
this.comptes = comptes;
}
public List<Emploi> getEmplois() throws DataAccessException {
emplois = serviceEmploi.findAll();
return emplois;
}
public void setEmplois(List<Emploi> emplois) {
this.emplois = emplois;
}
public List<CompteParent> getCompteParents() throws DataAccessException {
compteParents=serviceCompteParent.findAll();
return compteParents;
}
public void setCompteParents(List<CompteParent> compteParents) {
this.compteParents = compteParents;
}
public List<OffreSpeciale> getOffreSpeciales() throws DataAccessException {
offreSpeciales = serviceOffreSpeciale.findAll();
return offreSpeciales;
}
public void setOffreSpeciales(List<OffreSpeciale> offreSpeciales) {
this.offreSpeciales = offreSpeciales;
}
public List<PersonnePhysique> getPersonnePhysiques() throws DataAccessException {
personnePhysiques = servicePersonnePhys.findAll();
return personnePhysiques;
}
public void setPersonnePhysiques(List<PersonnePhysique> personnePhysiques) {
this.personnePhysiques = personnePhysiques;
}
public List<PersonneMorale> getPersonneMorales() throws DataAccessException {
personneMorales = servicePersonneMoral.findAll();
return personneMorales;
}
public void setPersonneMorales(List<PersonneMorale> personneMorales) {
this.personneMorales = personneMorales;
}
public List<SmsCompte> getSmsComptes() throws DataAccessException {
smsComptes = serviceSmsCompte.findAll();
return smsComptes;
}
public void setSmsComptes(List<SmsCompte> smsComptes) {
this.smsComptes = smsComptes;
}
public IServiceOperation getServiceOperation() {
return serviceOperation;
}
public void setServiceOperation(IServiceOperation serviceOperation) {
this.serviceOperation = serviceOperation;
}
public IServiceVirement getServiceVirement() {
return serviceVirement;
}
public void setServiceVirement(IServiceVirement serviceVirement) {
this.serviceVirement = serviceVirement;
}
public Personne getCurrent() {
return current;
}
public void setCurrent(Personne current) {
this.current = current;
}
public void setServicePersonne(IServicePersonne servicePersonne) {
this.servicePersonne = servicePersonne;
}
public IServiceCompte getServiceCmpte() {
return serviceCmpte;
}
public void setServiceCmpte(IServiceCompte serviceCmpte) {
this.serviceCmpte = serviceCmpte;
}
public IServiceAgence getServiceAgence() {
return serviceAgence;
}
public void setServiceAgence(IServiceAgence serviceAgence) {
this.serviceAgence = serviceAgence;
}
public IServiceAdresse getServiceAdresse() {
return serviceAdresse;
}
public void setServiceAdresse(IServiceAdresse serviceAdresse) {
this.serviceAdresse = serviceAdresse;
}
public IServiceSmsCompte getServiceSmsCompte() {
return serviceSmsCompte;
}
public void setServiceSmsCompte(IServiceSmsCompte serviceSmsCompte) {
this.serviceSmsCompte = serviceSmsCompte;
}
public IServiceSms getServiceSms() {
return serviceSms;
}
public void setServiceSms(IServiceSms serviceSms) {
this.serviceSms = serviceSms;
}
public IServicePersonnePhys getServicePersonnePhys() {
return servicePersonnePhys;
}
public void setServicePersonnePhys(IServicePersonnePhys servicePersonnePhys) {
this.servicePersonnePhys = servicePersonnePhys;
}
public IServicePersonneMoral getServicePersonneMoral() {
return servicePersonneMoral;
}
public void setServicePersonneMoral(IServicePersonneMoral servicePersonneMoral) {
this.servicePersonneMoral = servicePersonneMoral;
}
public IServiceEmploi getServiceEmploi() {
return serviceEmploi;
}
public void setServiceEmploi(IServiceEmploi serviceEmploi) {
this.serviceEmploi = serviceEmploi;
}
public IServiceChequier getServiceChequier() {
return serviceChequier;
}
public void setServiceChequier(IServiceChequier serviceChequier) {
this.serviceChequier = serviceChequier;
}
public IServiceOffreSpeciale getServiceOffreSpeciale() {
return serviceOffreSpeciale;
}
public void setServiceOffreSpeciale(IServiceOffreSpeciale serviceOffreSpeciale) {
this.serviceOffreSpeciale = serviceOffreSpeciale;
}
public List<Operation> getOpers() {
return opers;
}
public void setOpers(List<Operation> opers) {
this.opers = opers;
}
public Operation getOperation() {
return operation;
}
public void setOperation(Operation operation) {
this.operation = operation;
}
public Adresse getAdresse() {
return adresse;
}
public void setAdresse(Adresse adresse) {
this.adresse = adresse;
}
public List<Agence> getAgences() {
return agences;
}
public void setAgences(List<Agence> agences) {
this.agences = agences;
}
public Agence getAgence() {
return agence;
}
public void setAgence(Agence agence) {
this.agence = agence;
}
public Chequier getCheque() {
return cheque;
}
public void setCheque(Chequier cheque) {
this.cheque = cheque;
}
public Emploi getEmploi() {
return emploi;
}
public void setEmploi(Emploi emploi) {
this.emploi = emploi;
}
public SmsBean getSm() {
return sm;
}
public void setSm(SmsBean sm) {
this.sm = sm;
}
public OffreSpeciale getOffreSpeciale() {
return offreSpeciale;
}
public void setOffreSpeciale(OffreSpeciale offreSpeciale) {
this.offreSpeciale = offreSpeciale;
}
public Compte getCompte() {
return compte;
}
public void setCompte(Compte compte) {
this.compte = compte;
}
public Compte getCompteSrc() {
return compteSrc;
}
public void setCompteSrc(Compte compteSrc) {
this.compteSrc = compteSrc;
}
public Compte getCompteDest() {
return compteDest;
}
public void setCompteDest(Compte compteDest) {
this.compteDest = compteDest;
}
public Long getIdClient() {
return idClient;
}
public void setIdClient(Long idClient) {
this.idClient = idClient;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Long getIdAgence() {
return idAgence;
}
public void setIdAgence(Long idAgence) {
this.idAgence = idAgence;
}
public Chequier getChequier() {
return chequier;
}
public void setChequier(Chequier chequier) {
this.chequier = chequier;
}
public String getNumR() {
return numR;
}
public void setNumR(String numR) {
this.numR = numR;
}
public String getNumSrc() {
return numSrc;
}
public void setNumSrc(String numSrc) {
this.numSrc = numSrc;
}
public String getNumCmpte() {
return numCmpte;
}
public void setNumCmpte(String numCmpte) {
this.numCmpte = numCmpte;
}
public String getNumDest() {
return numDest;
}
public void setNumDest(String numDest) {
this.numDest = numDest;
}
public Date getDateDebut() {
return dateDebut;
}
public void setDateDebut(Date dateDebut) {
this.dateDebut = dateDebut;
}
public Date getDateFin() {
return dateFin;
}
public void setDateFin(Date dateFin) {
this.dateFin = dateFin;
}
public PersonnePhysique getPersonnePhysique() {
return personnePhysique;
}
public void setPersonnePhysique(PersonnePhysique personnePhysique) {
this.personnePhysique = personnePhysique;
}
public PersonneMorale getPersonneMorale() {
return personneMorale;
}
public void setPersonneMorale(PersonneMorale personneMorale) {
this.personneMorale = personneMorale;
}
public Personne getPersonne() {
return personne;
}
public void setPersonne(Personne personne) {
this.personne = personne;
}
public Long getIdPersPhys() {
return idPersPhys;
}
public void setIdPersPhys(Long idPersPhys) {
this.idPersPhys = idPersPhys;
}
public Long getIdPersMorale() {
return idPersMorale;
}
public void setIdPersMorale(Long idPersMorale) {
this.idPersMorale = idPersMorale;
}
public SmsCompte getSmsCompte() {
return smsCompte;
}
public void setSmsCompte(SmsCompte smsCompte) {
this.smsCompte = smsCompte;
}
public Sms getSms() {
return sms;
}
public void setSms(Sms sms) {
this.sms = sms;
}
public Virement getVirement() {
return virement;
}
public void setVirement(Virement virement) {
this.virement = virement;
}
}
|
package com.spring.domain;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import com.spring.util.Utils;
public class LoanBookReport {
private static final Logger LOG = LogManager.getLogger(LoanBookReport.class.getName());
private String invoiceNumber;
private int buyerId;
private String buyerName;
//private long accountNumber;
//private long loanNumber;
private int sellerId;
private String sellerName;
private String invoiceAmount;
private String actualDeliveryDate;
private String deliveryChallanUpdated;
//private String chargeSlipCpllected;
//private String pdcCollected;
//private String NACHAvailable;
private String loanBookApprovalCode;
private String lenderName;
private int tenureInDays;
private String interestRate;
private String interestAmount;
private float tax;
private double sbstAmount;
private double repaymentAmount;
//private String repaymentDate;
private String transactionTimeStamp;
private String tid;
// private int mid;
private String rrn;
public LoanBookReport(Object [] report) {
this.invoiceNumber= (String) report[0];
this.buyerId = (int)report[1];
this.buyerName = (String) report[2];
this.sellerId = (int) report[3];
this.sellerName = (String) report[4];
this.invoiceAmount = Utils.getAmountWithDecimal((String) report[5]);
this.actualDeliveryDate = (String)report[6];
this.deliveryChallanUpdated = (String)report[7];
this.loanBookApprovalCode = (String)report[8];
this.lenderName = (String)report[9];
this.tenureInDays= (int)report[10];
this.interestRate = String.valueOf(report[11]);
this.interestAmount =Utils.getAmountWithDecimal((String)report[12]);
try {
double interestamt=Double.parseDouble(interestAmount);
//DecimalFormat df = new DecimalFormat("###.##");
//LOG.info("kilobytes (DecimalFormat) : " + df.format(SBSTAmount));
double taxAmt = (double)report[13]*interestamt/100;
this.sbstAmount = Math.round(taxAmt*100.0)/100.0;
double repaymentAmt = (sbstAmount)+Double.parseDouble(invoiceAmount)+interestamt;
this.repaymentAmount = Math.round(repaymentAmt*100.0)/100.0;
} catch (Exception e) {
LOG.error("exception occured",e);
}
this.transactionTimeStamp = (String)report[14];
this.tid = (String)report[15];
this.rrn = (String)report[16];
}
public String getInvoiceNumber() {
return invoiceNumber;
}
public void setInvoiceNumber(String invoiceNumber) {
this.invoiceNumber = invoiceNumber;
}
public int getBuyerId() {
return buyerId;
}
public void setBuyerId(int buyerId) {
this.buyerId = buyerId;
}
public String getBuyerName() {
return buyerName;
}
public void setBuyerName(String buyerName) {
this.buyerName = buyerName;
}
public int getSellerId() {
return sellerId;
}
public void setSellerId(int sellerId) {
this.sellerId = sellerId;
}
public String getSellerName() {
return sellerName;
}
public void setSellerName(String sellerName) {
this.sellerName = sellerName;
}
public String getInvoiceAmount() {
return invoiceAmount;
}
public void setInvoiceAmount(String invoiceAmount) {
this.invoiceAmount = invoiceAmount;
}
public String getActualDeliveryDate() {
return actualDeliveryDate;
}
public void setActualDeliveryDate(String actualDeliveryDate) {
this.actualDeliveryDate = actualDeliveryDate;
}
public String getDeliveryChallanUpdated() {
return deliveryChallanUpdated;
}
public void setDeliveryChallanUpdated(String deliveryChallanUpdated) {
this.deliveryChallanUpdated = deliveryChallanUpdated;
}
public String getLoanBookApprovalCode() {
return loanBookApprovalCode;
}
public void setLoanBookApprovalCode(String loanBookApprovalCode) {
this.loanBookApprovalCode = loanBookApprovalCode;
}
public String getLenderName() {
return lenderName;
}
public void setLenderName(String lenderName) {
this.lenderName = lenderName;
}
public int getTenureInDays() {
return tenureInDays;
}
public void setTenureInDays(int tenureInDays) {
this.tenureInDays = tenureInDays;
}
public String getInterestRate() {
return interestRate;
}
public void setInterestRate(String interestRate) {
this.interestRate = interestRate;
}
public String getInterestAmount() {
return interestAmount;
}
public void setInterestAmount(String interestAmount) {
this.interestAmount = interestAmount;
}
public float getTax() {
return tax;
}
public void setTax(float tax) {
this.tax = tax;
}
public double getSbstAmount() {
return sbstAmount;
}
public void setSbstAmount(double sbstAmount) {
this.sbstAmount = sbstAmount;
}
public double getRepaymentAmount() {
return repaymentAmount;
}
public void setRepaymentAmount(double repaymentAmount) {
this.repaymentAmount = repaymentAmount;
}
public String getTransactionTimeStamp() {
return transactionTimeStamp;
}
public void setTransactionTimeStamp(String transactionTimeStamp) {
this.transactionTimeStamp = transactionTimeStamp;
}
public String getTid() {
return tid;
}
public void setTid(String tid) {
this.tid = tid;
}
public String getRrn() {
return rrn;
}
public void setRrn(String rrn) {
this.rrn = rrn;
}
}
|
package com.github.baloise.rocketchatrestclient.model;
import com.fasterxml.jackson.annotation.JsonGetter;
import com.fasterxml.jackson.annotation.JsonSetter;
public class ServerInfo {
private String version;
private ServerBuildInfo buildInfo;
private ServerCommitInfo commitInfo;
public void setVersion(String version) {
this.version = version;
}
public String getVersion() {
return this.version;
}
@JsonSetter("build")
public void setBuildInfo(ServerBuildInfo info) {
this.buildInfo = info;
}
@JsonGetter("build")
public ServerBuildInfo getBuildInfo() {
return this.buildInfo;
}
@JsonSetter("commit")
public void setCommitInfo(ServerCommitInfo info) {
this.commitInfo = info;
}
@JsonSetter("commit")
public ServerCommitInfo getCommitInfo() {
return this.commitInfo;
}
}
|
package com.codegym.checkinhotel.repository;
import com.codegym.checkinhotel.model.HotelDetails;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface IHotelDetailRepository extends PagingAndSortingRepository<HotelDetails,Long> {
}
|
/*
* Sonar, open source software quality management tool.
* Copyright (C) 2009 SonarSource
* mailto:contact AT sonarsource DOT com
*
* Sonar is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* Sonar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugins.technicaldebt.axis;
import org.apache.commons.configuration.Configuration;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.batch.DecoratorContext;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.Measure;
import org.sonar.plugins.technicaldebt.TechnicalDebtPlugin;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.anyDouble;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ViolationsDebtCalculatorTest {
private DecoratorContext context;
private ViolationsDebtCalculator calculator;
@Before
public void setUp() throws Exception {
Configuration configuration = mock(Configuration.class);
when(configuration.getDouble(anyString(), anyDouble())).thenReturn(TechnicalDebtPlugin.COST_VIOLATION_DEFVAL);
calculator = new ViolationsDebtCalculator(configuration);
context = mock(DecoratorContext.class);
}
@Test
public void testCalculateAbsoluteDebt() {
when(context.getMeasure(CoreMetrics.VIOLATIONS)).
thenReturn(null);
when(context.getMeasure(CoreMetrics.INFO_VIOLATIONS)).
thenReturn(null);
assertEquals(0d, calculator.calculateAbsoluteDebt(context), 0);
when(context.getMeasure(CoreMetrics.VIOLATIONS)).
thenReturn(new Measure(CoreMetrics.VIOLATIONS, 160.0));
when(context.getMeasure(CoreMetrics.INFO_VIOLATIONS)).
thenReturn(null);
assertEquals(2d, calculator.calculateAbsoluteDebt(context), 0);
when(context.getMeasure(CoreMetrics.VIOLATIONS)).
thenReturn(new Measure(CoreMetrics.VIOLATIONS, 160.0));
when(context.getMeasure(CoreMetrics.INFO_VIOLATIONS)).
thenReturn(new Measure(CoreMetrics.VIOLATIONS, 40.0));
assertEquals(1.5d, calculator.calculateAbsoluteDebt(context), 0);
}
@Test
public void testCalculateTotalDebtNoLines() {
when(context.getMeasure(CoreMetrics.LINES)).
thenReturn(null);
assertEquals(0d, calculator.calculateTotalPossibleDebt(context), 0);
}
@Test
public void testCalculateTotalDebtNoWeightedViolations() {
when(context.getMeasure(CoreMetrics.WEIGHTED_VIOLATIONS)).
thenReturn(null);
when(context.getMeasure(CoreMetrics.VIOLATIONS)).
thenReturn(new Measure(CoreMetrics.VIOLATIONS, 300.0));
when(context.getMeasure(CoreMetrics.NCLOC)).
thenReturn(new Measure(CoreMetrics.NCLOC, 300.0));
assertEquals(1.25d, calculator.calculateTotalPossibleDebt(context), 0);
}
@Test
public void testCalculateTotalDebtNoViolations() {
when(context.getMeasure(CoreMetrics.VIOLATIONS)).
thenReturn(null);
when(context.getMeasure(CoreMetrics.WEIGHTED_VIOLATIONS)).
thenReturn(new Measure(CoreMetrics.WEIGHTED_VIOLATIONS, 300.0));
when(context.getMeasure(CoreMetrics.NCLOC)).
thenReturn(new Measure(CoreMetrics.NCLOC, 300.0));
assertEquals(1.25d, calculator.calculateTotalPossibleDebt(context), 0);
}
@Test
public void testCalculateTotalDebt() {
when(context.getMeasure(CoreMetrics.VIOLATIONS)).
thenReturn(new Measure(CoreMetrics.VIOLATIONS, 40.0));
when(context.getMeasure(CoreMetrics.WEIGHTED_VIOLATIONS)).
thenReturn(new Measure(CoreMetrics.WEIGHTED_VIOLATIONS, 130.0));
when(context.getMeasure(CoreMetrics.NCLOC)).
thenReturn(new Measure(CoreMetrics.NCLOC, 600.0));
assertEquals(2.3d, calculator.calculateTotalPossibleDebt(context), 0.01);
}
@Test
public void testDependsOn() {
assertThat(calculator.dependsOn().size(), is(4));
}
}
|
package lin.pattern.Creational.abstractfactory;
public class Summary {
/**
* 由于工厂模式中每个工厂只负责生产一类产品,导致系统中存在大量的工厂类,增加系统的开销,
* 此时可以考虑将一些相关的产品组成一个“产品族”,由同一个工厂来生产
*/
/**
* 产品等级结构 产品族
* 产品等级结构:产品等级结构即产品的继承结构,如抽象类是电视机,子类有海尔电视机、海信电视机、小米电视机,
* 则抽象电视机与具体品牌的电视机之间构成一个产品等级结构,抽象电视机是父类,而具体品牌的电视机是子类。
* 产品族: 在抽象工厂模式中,产品族是指由同一个工厂生产的,位于不同产品等级结构中的一组产品。
* 如海尔电器厂生产的海尔电视机、海尔电冰箱、海尔洗衣机构成一个产品族。
*
* 当系统所提供的工厂生产的具体产品并不是一个简单的对象,而是多个位于不同产品等级结构、属于不同类型的具体产品时,
* 就可以使用抽象工厂模式。
* 抽象工厂模式是所有形式的工厂模式中最为抽象和最具一般性的一种形式。抽象工厂模式与工厂模式的最大区别在于,
* 工厂模式是针对一个产品等级结构,而抽象工厂模式需要面对多个产品等级结构,一个工厂等级机构可以负责多个不同产品等级结构中
* 的产品对象的创建。
*
* 当一个工厂等级结构可以创建出属于不同产品等级结构的一个产品族中的所有对象时,抽象工厂模式比工厂模式更为简单和高效。
*/
/**
* 抽象工厂模式 Abstract Factory Pattern:提供了一个创建一系列相关或相互依赖对象的接口,而无须指定他们具体的类。
*/
}
|
/*
* Copyright (c) 2011-2016 Pivotal Software Inc, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package reactor.aeron.processor;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import reactor.Processors;
import reactor.aeron.Context;
import reactor.aeron.support.AeronTestUtils;
import reactor.aeron.support.ThreadSnapshot;
import reactor.core.processor.BaseProcessor;
import reactor.core.subscriber.test.DataTestSubscriber;
import reactor.io.IO;
import reactor.io.buffer.Buffer;
import reactor.rx.Stream;
import reactor.rx.Streams;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* @author Anatoly Kadyshev
*/
public abstract class CommonAeronProcessorTest {
protected static final int TIMEOUT_SECS = 5;
private ThreadSnapshot threadSnapshot;
@Before
public void doSetup() {
threadSnapshot = new ThreadSnapshot().take();
AeronTestUtils.setAeronEnvProps();
}
@After
public void doTeardown() throws InterruptedException {
AeronTestUtils.awaitMediaDriverIsTerminated(TIMEOUT_SECS);
assertTrue(threadSnapshot.takeAndCompare(new String[] {"hash", "global"},
TimeUnit.SECONDS.toMillis(TIMEOUT_SECS)));
}
protected Context createContext() {
return new Context()
.autoCancel(false)
.publicationRetryMillis(1000)
.errorConsumer(Throwable::printStackTrace);
}
protected DataTestSubscriber<String> createTestSubscriber() {
return DataTestSubscriber.createWithTimeoutSecs(TIMEOUT_SECS);
}
@Test
public void testNextSignalIsReceived() throws InterruptedException {
AeronProcessor processor = AeronProcessor.create(createContext());
DataTestSubscriber<String> subscriber = createTestSubscriber();
IO.bufferToString(processor).subscribe(subscriber);
subscriber.request(4);
Streams.just(Buffer.wrap("Live"),
Buffer.wrap("Hard"),
Buffer.wrap("Die"),
Buffer.wrap("Harder"),
Buffer.wrap("Extra")).subscribe(processor);
subscriber.assertNextSignals("Live", "Hard", "Die", "Harder");
subscriber.request(1);
subscriber.assertNextSignals("Extra");
//FIXME: Remove this work-around for bounded Streams.just not sending Complete signal
subscriber.request(1);
}
@Test
public void testCompleteSignalIsReceived() throws InterruptedException {
AeronProcessor processor = AeronProcessor.create(createContext());
Streams.just(
Buffer.wrap("One"),
Buffer.wrap("Two"),
Buffer.wrap("Three"))
.subscribe(processor);
DataTestSubscriber<String> subscriber = createTestSubscriber();
IO.bufferToString(processor).subscribe(subscriber);
subscriber.request(1);
subscriber.assertNextSignals("One");
subscriber.request(1);
subscriber.assertNextSignals("Two");
subscriber.request(1);
subscriber.assertNextSignals("Three");
//FIXME: Remove this work-around for bounded Streams.just not sending Complete signal
subscriber.request(1);
subscriber.assertCompleteReceived();
}
@Test
@Ignore
public void testCompleteShutdownsProcessorWithNoSubscribers() {
AeronProcessor processor = AeronProcessor.create(createContext());
Publisher<Buffer> publisher = Subscriber::onComplete;
publisher.subscribe(processor);
}
@Test
public void testWorksWithTwoSubscribersViaEmitter() throws InterruptedException {
AeronProcessor processor = AeronProcessor.create(createContext());
Streams.just(Buffer.wrap("Live"),
Buffer.wrap("Hard"),
Buffer.wrap("Die"),
Buffer.wrap("Harder")).subscribe(processor);
BaseProcessor<Buffer, Buffer> emitter = Processors.emitter();
processor.subscribe(emitter);
DataTestSubscriber<String> subscriber1 = createTestSubscriber();
IO.bufferToString(emitter).subscribe(subscriber1);
DataTestSubscriber<String> subscriber2 = createTestSubscriber();
IO.bufferToString(emitter).subscribe(subscriber2);
subscriber1.requestUnboundedWithTimeout();
subscriber2.requestUnboundedWithTimeout();
subscriber1.assertNextSignals("Live", "Hard", "Die", "Harder");
subscriber2.assertNextSignals("Live", "Hard", "Die", "Harder");
subscriber1.assertCompleteReceived();
subscriber2.assertCompleteReceived();
}
@Test
public void testClientReceivesException() throws InterruptedException {
AeronProcessor processor = AeronProcessor.create(createContext());
// as error is delivered on a different channelId compared to signal
// its delivery could shutdown the processor before the processor subscriber
// receives signal
Streams.concat(Streams.just(Buffer.wrap("Item")),
Streams.fail(new RuntimeException("Something went wrong")))
.subscribe(processor);
DataTestSubscriber<String> subscriber = createTestSubscriber();
IO.bufferToString(processor).subscribe(subscriber);
subscriber.requestUnboundedWithTimeout();
subscriber.assertErrorReceived();
Throwable throwable = subscriber.getLastErrorSignal();
assertThat(throwable.getMessage(), is("Something went wrong"));
}
@Test
public void testExceptionWithNullMessageIsHandled() throws InterruptedException {
AeronProcessor processor = AeronProcessor.create(createContext());
DataTestSubscriber<String> subscriber = createTestSubscriber();
IO.bufferToString(processor).subscribe(subscriber);
subscriber.requestUnboundedWithTimeout();
Stream<Buffer> sourceStream = Streams.fail(new RuntimeException());
sourceStream.subscribe(processor);
subscriber.assertErrorReceived();
Throwable throwable = subscriber.getLastErrorSignal();
assertThat(throwable.getMessage(), is(""));
}
@Test
public void testCancelsUpstreamSubscriptionWhenLastSubscriptionIsCancelledAndAutoCancel()
throws InterruptedException {
AeronProcessor processor = AeronProcessor.create(createContext().autoCancel(true));
final CountDownLatch subscriptionCancelledLatch = new CountDownLatch(1);
Publisher<Buffer> dataPublisher = new Publisher<Buffer>() {
@Override
public void subscribe(Subscriber<? super Buffer> subscriber) {
subscriber.onSubscribe(new Subscription() {
@Override
public void request(long n) {
System.out.println("Requested: " + n);
}
@Override
public void cancel() {
System.out.println("Upstream subscription cancelled");
subscriptionCancelledLatch.countDown();
}
});
}
};
dataPublisher.subscribe(processor);
DataTestSubscriber<String> client = createTestSubscriber();
IO.bufferToString(processor).subscribe(client);
client.requestUnboundedWithTimeout();
processor.onNext(Buffer.wrap("Hello"));
client.assertNextSignals("Hello");
client.cancelSubscription();
assertTrue("Subscription wasn't cancelled",
subscriptionCancelledLatch.await(TIMEOUT_SECS, TimeUnit.SECONDS));
}
}
|
package com.coinhunter.web.user;
import com.coinhunter.core.domain.user.User;
import com.coinhunter.core.dto.user.UserDto;
import com.coinhunter.core.service.message.MessageSourceService;
import com.coinhunter.core.service.user.UserDetailsServiceImpl;
import com.coinhunter.core.service.user.UserService;
import com.coinhunter.utils.mapper.ModelMapperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/users")
public class UserController {
private UserService userService;
private UserDetailsServiceImpl userDetailsService;
private MessageSourceService messageSourceService;
private ModelMapperUtils modelMapperUtils;
@Autowired
public UserController(UserService userService,
UserDetailsServiceImpl userDetailsService,
MessageSourceService messageSourceService,
ModelMapperUtils modelMapperUtils) {
this.userService = userService;
this.userDetailsService = userDetailsService;
this.messageSourceService = messageSourceService;
this.modelMapperUtils = modelMapperUtils;
}
@GetMapping(value = "/details")
UserDto findUserDetails() {
User user = userService.findByName(userDetailsService.getUsername());
return modelMapperUtils.convertToDto(user, UserDto.class);
}
@PostMapping(value = "/register")
UserDto register(@RequestBody UserDto userDto) {
User user = modelMapperUtils.convertToEntity(userDto, User.class);
userService.register(user);
return userDto;
}
@PutMapping(value = "/reset-password")
String resetPassword(@RequestParam("name") String name, @RequestParam("email") String email) {
return userService.resetPassword(name, email);
}
}
|
package com.example.httpclient.demohttpclient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoHttpclientApplication {
public static void main(String[] args) {
SpringApplication.run(DemoHttpclientApplication.class, args);
}
}
|
import cucumber.api.PendingException;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class MyStepdefs {
@Given("^website https://www\\.phptravels\\.net/ is open$")
public void websiteHttpsWwwPhptravelsNetIsOpen() {
}
@When("^I click on \"([^\"]*)\"$")
public void iClickOn(String arg0) throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
@And("^I choose date$")
public void iChooseDate() {
}
@And("^I choose number of guests$")
public void iChooseNumberOfGuests() {
}
@And("^I click \"([^\"]*)\"$")
public void iClick(String arg0) throws Throwable {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
@Then("^I see list of all Tours available in chosen date for two people$")
public void iSeeListOfAllToursAvailableInChosenDateForTwoPeople() {
}
}
|
package vehicle;
import enums.Condition;
import enums.Origin;
import enums.TrailerType;
import enums.TruckType;
import trailer.Trailer;
import vehicle.Vehicle;
public class Truck extends Vehicle {
// variaveis de instancia de truck
private int length;
private int load;
private TruckType truckType;
private TrailerType trailerType = null;
// construtor default de truck
public Truck() {
}
// construtor de truck
public Truck(int id, int vin, String brand, String model, String manufacturingDate, Origin origin, int kms, Condition condition, int price, int length, int load, TruckType truckType, TrailerType trailerType) {
super(id, vin, brand, model, manufacturingDate, origin, kms, condition, price);
this.length = length;
this.load = load;
this.truckType = truckType;
this.trailerType = trailerType;
}
// TODOS GETTERS E SETTERS
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getLoad() {
return load;
}
public void setLoad(int load) {
this.load = load;
}
public TruckType getTruckType() {
return truckType;
}
public void setTruckType(TruckType truckType) {
this.truckType = truckType;
}
public TrailerType getTrailerType() {
return trailerType;
}
public void setTrailerType(TrailerType trailerType) {
this.trailerType = trailerType;
}
public int getPrice() {
if (this.trailerType != null && this.getCondition() == Condition.NEW) {
return (int) (super.getPrice() * 0.95);
} else if (this.trailerType == null && this.getCondition() == Condition.NEW) {
return super.getPrice();
} else {
return (int) (super.getPrice() * 0.85);
}
}
// metodo toString para imprimir
public String toString() {
System.out.println("This is a Truck ");
System.out.print(super.toString());
String text = "Comprimento : " + length + "\n"
+ "Carga útil : " + load + "\n"
+ "Tipologia : " + truckType + "\n"
+ "Atrelado : " + trailerType + "\n"
+ "Desconto (se aplicavel) : " + (super.getPrice() - getPrice()) + "\n";
return text;
}
public String printTruck() {
return super.toString();
}
}
|
package org.pan.transport;
/**
* Created by xiaopan on 2015-12-31.
*/
public abstract class AbstractMessageTransport {
protected final String address;
public AbstractMessageTransport(String address) {
this.address = address;
}
}
|
package com.valleskeyp.data;
import java.util.HashMap;
public enum enumData {
TIMES1(1),
TIMES2(2),
TIMES4(4);
// not sure what to do with the enum data...
// this was an attempt at returning a number that gets multiplied by the TIMES enumData
// in the end i was not able to return the data properly, the return is for a HashMap but my
// result was an integer. perhaps as the app progresses i can properly use this feature.
private final int multiplier;
enumData(int multiplier) {
this.multiplier = multiplier;
}
public static HashMap<enumData, Integer> getModifier(int amount) {
HashMap<enumData, Integer> total = new HashMap<enumData, Integer>();
int randomNum = 3 + (int)(Math.random() * ((3 - 1) + 1));
enumData[] times = {TIMES1,TIMES2,TIMES4};
enumData num1 = times[randomNum];
//total = (int) amount * num1.multiplier;
return total;
}
}
|
package test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import annotation.Bar;
import annotation.Manager;
import annotation.Restaurant;
import annotation.School;
public class TestCase {
@Test
//测试采用@Autowored(set方式注入)
public void test1() {
ApplicationContext ac =
new ClassPathXmlApplicationContext("annotation.xml");
Restaurant rest = ac.getBean("rest", Restaurant.class);
System.out.println(rest);
}
@Test
//测试@Autowired(构造器注入)
public void test2() {
ApplicationContext ac =
new ClassPathXmlApplicationContext("annotation.xml");
School rest = ac.getBean("school", School.class);
System.out.println(rest);
}
@Test
//测试@Resource(只能set方式注入)
public void test3() {
ApplicationContext ac =
new ClassPathXmlApplicationContext("annotation.xml");
Bar bar = ac.getBean("bar", Bar.class);
System.out.println(bar);
}
@Test
//测试@Value
public void test4() {
ApplicationContext ac =
new ClassPathXmlApplicationContext("annotation.xml");
Manager mg = ac.getBean("mg", Manager.class);
System.out.println(mg);
}
}
|
package com.tt.miniapp.process.handler;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Parcelable;
import android.text.TextUtils;
import com.a;
import com.bytedance.sandboxapp.protocol.service.request.entity.HttpRequest;
import com.storage.async.Action;
import com.storage.async.Observable;
import com.storage.async.Scheduler;
import com.storage.async.Schedulers;
import com.tt.frontendapiinterface.b;
import com.tt.miniapp.audio.background.BgAudioCallExtra;
import com.tt.miniapp.audio.background.BgAudioCommand;
import com.tt.miniapp.audio.background.BgAudioManagerServiceNative;
import com.tt.miniapp.audio.background.BgAudioModel;
import com.tt.miniapp.audio.background.BgAudioPlayStateListener;
import com.tt.miniapp.audio.background.BgAudioState;
import com.tt.miniapp.base.netrequest.RequestManagerV2;
import com.tt.miniapp.entity.AppJumpListManager;
import com.tt.miniapp.event.remedy.InnerMiniProcessLogHelper;
import com.tt.miniapp.launchcache.LaunchCacheDAO;
import com.tt.miniapp.locate.LocateCrossProcessHandler;
import com.tt.miniapp.manager.HostActivityManager;
import com.tt.miniapp.mmkv.KVUtil;
import com.tt.miniapp.offlinezip.OfflineZipManager;
import com.tt.miniapp.offlinezip.OnOfflineZipCheckUpdateResultListener;
import com.tt.miniapp.process.AppProcessManager;
import com.tt.miniapp.process.extra.CrossProcessOperatorScheduler;
import com.tt.miniapp.service.ServiceProvider;
import com.tt.miniapp.service.hostevent.HostEventService;
import com.tt.miniapp.service.hostevent.HostEventServiceInterface;
import com.tt.miniapp.settings.data.SettingsDAO;
import com.tt.miniapp.settings.keys.Settings;
import com.tt.miniapp.thread.ThreadPools;
import com.tt.miniapp.thread.ThreadUtil;
import com.tt.miniapp.titlemenu.item.FavoriteMiniAppMenuItem;
import com.tt.miniapp.util.ActivityUtil;
import com.tt.miniapp.util.ChannelUtil;
import com.tt.miniapphost.AppBrandLogger;
import com.tt.miniapphost.AppbrandConstants;
import com.tt.miniapphost.AppbrandContext;
import com.tt.miniapphost.AppbrandSupport;
import com.tt.miniapphost.LaunchThreadPool;
import com.tt.miniapphost.NativeModule;
import com.tt.miniapphost.host.HostDependManager;
import com.tt.miniapphost.language.LocaleManager;
import com.tt.miniapphost.language.LocaleUtils;
import com.tt.miniapphost.process.callback.IpcCallback;
import com.tt.miniapphost.process.callback.IpcCallbackManagerProxy;
import com.tt.miniapphost.process.data.CrossProcessDataEntity;
import com.tt.miniapphost.process.helper.AsyncIpcHandler;
import com.tt.miniapphost.util.DebugUtil;
import com.tt.miniapphost.util.StorageUtil;
import com.tt.option.e.e;
import com.tt.option.e.f;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
class InnerHostProcessCallHandler {
public static void addHostEventListener(CrossProcessDataEntity paramCrossProcessDataEntity) {
if (paramCrossProcessDataEntity != null) {
String str2 = paramCrossProcessDataEntity.getString("host_event_mp_id");
String str1 = paramCrossProcessDataEntity.getString("host_event_event_name");
if (!TextUtils.isEmpty(str2) && !TextUtils.isEmpty(str1)) {
HostEventServiceInterface hostEventServiceInterface = (HostEventServiceInterface)ServiceProvider.getInstance().getService(HostEventService.class);
if (hostEventServiceInterface != null)
hostEventServiceInterface.hostProcessAddHostEventListener(str2, str1);
}
}
}
private static void addToFavoriteSet(CrossProcessDataEntity paramCrossProcessDataEntity) {
if (paramCrossProcessDataEntity == null)
return;
String str = paramCrossProcessDataEntity.getString("mini_app_id");
if (TextUtils.isEmpty(str))
return;
if (FavoriteMiniAppMenuItem.sFavoriteSet == null)
FavoriteMiniAppMenuItem.sFavoriteSet = new LinkedHashSet();
FavoriteMiniAppMenuItem.sFavoriteSet.add(str);
}
private static void apiHandler(CrossProcessDataEntity paramCrossProcessDataEntity, final AsyncIpcHandler asyncIpcHandler) {
if (paramCrossProcessDataEntity == null) {
DebugUtil.outputError("InnerHostProcessCallHandler", new Object[] { "apiHandler callData == null" });
return;
}
String str2 = paramCrossProcessDataEntity.getString("apiName");
String str1 = paramCrossProcessDataEntity.getString("apiData");
AppBrandLogger.d("InnerHostProcessCallHandler", new Object[] { "handleAsyncCall apiHandler apiName: ", str2, " apiData: ", str1 });
f.a a = AppbrandContext.getInst().getExtensionApiCreator();
if (!TextUtils.isEmpty(str2) && a != null) {
final b handler = a.a(str2, str1, 0, null);
if (b != null) {
b.mApiHandlerCallback = new e() {
public final void callback(int param1Int, String param1String) {
handler.operateFinishOnGoalProcess(param1String, asyncIpcHandler);
}
};
CrossProcessOperatorScheduler.apiHandlerAct(b);
return;
}
asyncIpcHandler.callback(null, true);
AppBrandLogger.e("InnerHostProcessCallHandler", new Object[] { "handleAsyncCall apiHandler cannot create target ApiHandler. apiName:", str2 });
return;
}
asyncIpcHandler.callback(null, true);
AppBrandLogger.e("InnerHostProcessCallHandler", new Object[] { "handleAsyncCall TextUtils.isEmpty(apiName) || extApiHandlerCreator== null. apiName:", str2 });
}
private static CrossProcessDataEntity backApp(CrossProcessDataEntity paramCrossProcessDataEntity) {
String str1 = paramCrossProcessDataEntity.getString("miniAppId");
String str2 = paramCrossProcessDataEntity.getString("refererInfo");
boolean bool = paramCrossProcessDataEntity.getBoolean("isApiCall");
if (paramCrossProcessDataEntity.getBoolean("is_launch_with_float_style")) {
Activity activity = HostActivityManager.getHostTopActivity();
if (activity != null)
ActivityUtil.moveHostActivityTaskToFront(activity, false);
}
return CrossProcessDataEntity.Builder.create().put("back_app_result", Boolean.valueOf(AppJumpListManager.backToApp(str1, str2, bool))).build();
}
private static void callback(CrossProcessDataEntity paramCrossProcessDataEntity1, CrossProcessDataEntity paramCrossProcessDataEntity2) {
if (paramCrossProcessDataEntity2 == null) {
DebugUtil.outputError("InnerHostProcessCallHandler", new Object[] { "callback callExtraData == null" });
return;
}
int i = paramCrossProcessDataEntity2.getInt("callbackId", 0);
boolean bool = paramCrossProcessDataEntity2.getBoolean("finishCallBack");
IpcCallbackManagerProxy.getInstance().handleIpcCallBack(i, paramCrossProcessDataEntity1);
if (bool)
IpcCallbackManagerProxy.getInstance().unregisterIpcCallback(i);
}
private static void checkUpdateOfflineZip(CrossProcessDataEntity paramCrossProcessDataEntity, final AsyncIpcHandler asyncIpcHandler) {
if (paramCrossProcessDataEntity != null) {
List list = paramCrossProcessDataEntity.getStringList("offline_zip_module_names");
if (list != null)
OfflineZipManager.INSTANCE.checkUpdateOfflineZipInMainProcess((Context)AppbrandContext.getInst().getApplicationContext(), list, new OnOfflineZipCheckUpdateResultListener() {
public final void onComplete(boolean param1Boolean) {
asyncIpcHandler.callback((new CrossProcessDataEntity.Builder()).put("offline_zip_update_result", Boolean.valueOf(param1Boolean)).build(), true);
}
});
}
}
private static CrossProcessDataEntity getCurrentLocale(CrossProcessDataEntity paramCrossProcessDataEntity) {
String str1;
Locale locale = LocaleManager.getInst().getCurrentHostSetLocale();
if (locale != null) {
str1 = LocaleUtils.locale2String(locale);
} else {
str1 = "";
}
String str2 = str1;
if (TextUtils.isEmpty(str1))
str2 = "";
StringBuilder stringBuilder = new StringBuilder("getCurrentLocale:");
stringBuilder.append(str2);
AppBrandLogger.d("InnerHostProcessCallHandler", new Object[] { stringBuilder.toString() });
return CrossProcessDataEntity.Builder.create().put("localeLang", str2).build();
}
private static CrossProcessDataEntity getFavoriteSet() {
return (FavoriteMiniAppMenuItem.sFavoriteSet == null) ? null : CrossProcessDataEntity.Builder.create().putStringList("favorite_set", new ArrayList(FavoriteMiniAppMenuItem.sFavoriteSet)).build();
}
private static CrossProcessDataEntity getFavoriteSettings() {
String str = SettingsDAO.getString((Context)AppbrandContext.getInst().getApplicationContext(), null, new Enum[] { (Enum)Settings.TT_TMA_SWITCH, (Enum)Settings.TmaSwitch.FAVORITES });
AppBrandLogger.d("InnerHostProcessCallHandler", new Object[] { "favoritesJsonStr == ", str });
return CrossProcessDataEntity.Builder.create().put("favorite_settings", str).build();
}
private static void getLocation(AsyncIpcHandler paramAsyncIpcHandler) {
LocateCrossProcessHandler.inst((Context)AppbrandContext.getInst().getApplicationContext()).getLocation(paramAsyncIpcHandler);
}
private static CrossProcessDataEntity getPlatformSession(CrossProcessDataEntity paramCrossProcessDataEntity) {
if (paramCrossProcessDataEntity == null) {
DebugUtil.outputError("InnerHostProcessCallHandler", new Object[] { "getPlatformSession callData == null" });
return null;
}
Application application = AppbrandContext.getInst().getApplicationContext();
if (application == null) {
AppBrandLogger.e("InnerHostProcessCallHandler", new Object[] { "getPlatformSession context == null" });
return null;
}
String str = paramCrossProcessDataEntity.getString("miniAppId");
if (TextUtils.isEmpty(str)) {
AppBrandLogger.e("InnerHostProcessCallHandler", new Object[] { "getPlatformSession appId is empty" });
return null;
}
return CrossProcessDataEntity.Builder.create().put("platformSession", StorageUtil.getSessionByAppid((Context)application, str)).build();
}
private static void getSnapShot(CrossProcessDataEntity paramCrossProcessDataEntity, AsyncIpcHandler paramAsyncIpcHandler) {
// Byte code:
// 0: invokestatic currentTimeMillis : ()J
// 3: lstore_2
// 4: invokestatic getHostTopActivity : ()Landroid/app/Activity;
// 7: astore #7
// 9: aconst_null
// 10: astore #6
// 12: aload_0
// 13: ifnull -> 185
// 16: aload_0
// 17: ldc_w 'forceGetHostActivitySnapshot'
// 20: invokevirtual getBoolean : (Ljava/lang/String;)Z
// 23: istore #5
// 25: aload_0
// 26: ldc 'miniAppId'
// 28: invokevirtual getString : (Ljava/lang/String;)Ljava/lang/String;
// 31: astore_0
// 32: aload_0
// 33: invokestatic getProcessInfoByAppId : (Ljava/lang/String;)Lcom/tt/miniapp/process/AppProcessManager$ProcessInfo;
// 36: astore #8
// 38: aload #8
// 40: ifnull -> 57
// 43: aload #8
// 45: invokevirtual isLaunchActivityInHostStack : ()Z
// 48: ifeq -> 57
// 51: iconst_1
// 52: istore #4
// 54: goto -> 60
// 57: iconst_0
// 58: istore #4
// 60: ldc 'InnerHostProcessCallHandler'
// 62: bipush #6
// 64: anewarray java/lang/Object
// 67: dup
// 68: iconst_0
// 69: ldc_w 'request getSnapShot appId:'
// 72: aastore
// 73: dup
// 74: iconst_1
// 75: aload_0
// 76: aastore
// 77: dup
// 78: iconst_2
// 79: ldc_w 'forceGetHostActivitySnapshot:'
// 82: aastore
// 83: dup
// 84: iconst_3
// 85: iload #5
// 87: invokestatic valueOf : (Z)Ljava/lang/Boolean;
// 90: aastore
// 91: dup
// 92: iconst_4
// 93: ldc_w 'isMiniAppLaunchInHostStack:'
// 96: aastore
// 97: dup
// 98: iconst_5
// 99: iload #4
// 101: invokestatic valueOf : (Z)Ljava/lang/Boolean;
// 104: aastore
// 105: invokestatic i : (Ljava/lang/String;[Ljava/lang/Object;)V
// 108: iload #5
// 110: ifeq -> 125
// 113: iload #4
// 115: ifne -> 125
// 118: invokestatic getLatestUsingHostStackProcessInfo : ()Lcom/tt/miniapp/process/AppProcessManager$ProcessInfo;
// 121: astore_0
// 122: goto -> 154
// 125: aload_0
// 126: invokestatic getPreAppId : (Ljava/lang/String;)Ljava/lang/String;
// 129: astore_0
// 130: ldc 'InnerHostProcessCallHandler'
// 132: iconst_2
// 133: anewarray java/lang/Object
// 136: dup
// 137: iconst_0
// 138: ldc_w 'getSnapShot preAppId:'
// 141: aastore
// 142: dup
// 143: iconst_1
// 144: aload_0
// 145: aastore
// 146: invokestatic i : (Ljava/lang/String;[Ljava/lang/Object;)V
// 149: aload_0
// 150: invokestatic getProcessInfoByAppId : (Ljava/lang/String;)Lcom/tt/miniapp/process/AppProcessManager$ProcessInfo;
// 153: astore_0
// 154: ldc 'InnerHostProcessCallHandler'
// 156: iconst_2
// 157: anewarray java/lang/Object
// 160: dup
// 161: iconst_0
// 162: ldc_w 'getSnapShot snapshotMiniAppProcessInfo:'
// 165: aastore
// 166: dup
// 167: iconst_1
// 168: aload_0
// 169: aastore
// 170: invokestatic i : (Ljava/lang/String;[Ljava/lang/Object;)V
// 173: aload_0
// 174: ifnull -> 185
// 177: aload_0
// 178: getfield mProcessIdentity : Ljava/lang/String;
// 181: astore_0
// 182: goto -> 187
// 185: aconst_null
// 186: astore_0
// 187: aload_0
// 188: invokestatic isEmpty : (Ljava/lang/CharSequence;)Z
// 191: ifeq -> 288
// 194: ldc 'InnerHostProcessCallHandler'
// 196: iconst_2
// 197: anewarray java/lang/Object
// 200: dup
// 201: iconst_0
// 202: ldc_w 'getHostActivitySnapShot activity:'
// 205: aastore
// 206: dup
// 207: iconst_1
// 208: aload #7
// 210: aastore
// 211: invokestatic i : (Ljava/lang/String;[Ljava/lang/Object;)V
// 214: aload #7
// 216: aload #7
// 218: invokestatic getSnapshot : (Landroid/app/Activity;)Landroid/graphics/Bitmap;
// 221: invokestatic compressSnapshot : (Landroid/graphics/Bitmap;)[B
// 224: invokestatic saveSnapshotFile : (Landroid/app/Activity;[B)Ljava/io/File;
// 227: astore #7
// 229: aload #6
// 231: astore_0
// 232: aload #7
// 234: ifnull -> 255
// 237: invokestatic create : ()Lcom/tt/miniapphost/process/data/CrossProcessDataEntity$Builder;
// 240: ldc_w 'snapshot'
// 243: aload #7
// 245: invokevirtual getAbsolutePath : ()Ljava/lang/String;
// 248: invokevirtual put : (Ljava/lang/String;Ljava/lang/Object;)Lcom/tt/miniapphost/process/data/CrossProcessDataEntity$Builder;
// 251: invokevirtual build : ()Lcom/tt/miniapphost/process/data/CrossProcessDataEntity;
// 254: astore_0
// 255: aload_1
// 256: aload_0
// 257: iconst_1
// 258: invokevirtual callback : (Lcom/tt/miniapphost/process/data/CrossProcessDataEntity;Z)V
// 261: ldc 'InnerHostProcessCallHandler'
// 263: iconst_2
// 264: anewarray java/lang/Object
// 267: dup
// 268: iconst_0
// 269: ldc_w '获取主进程页面截图 duration:'
// 272: aastore
// 273: dup
// 274: iconst_1
// 275: invokestatic currentTimeMillis : ()J
// 278: lload_2
// 279: lsub
// 280: invokestatic valueOf : (J)Ljava/lang/Long;
// 283: aastore
// 284: invokestatic d : (Ljava/lang/String;[Ljava/lang/Object;)V
// 287: return
// 288: ldc 'InnerHostProcessCallHandler'
// 290: iconst_2
// 291: anewarray java/lang/Object
// 294: dup
// 295: iconst_0
// 296: ldc_w 'getMiniAppSnapShot preAppProcessIdentify:'
// 299: aastore
// 300: dup
// 301: iconst_1
// 302: aload_0
// 303: aastore
// 304: invokestatic i : (Ljava/lang/String;[Ljava/lang/Object;)V
// 307: aload_0
// 308: new com/tt/miniapp/process/handler/InnerHostProcessCallHandler$6
// 311: dup
// 312: aload_1
// 313: lload_2
// 314: invokespecial <init> : (Lcom/tt/miniapphost/process/helper/AsyncIpcHandler;J)V
// 317: invokestatic getSnapshot : (Ljava/lang/String;Lcom/tt/miniapphost/process/callback/IpcCallback;)V
// 320: return
}
public static CrossProcessDataEntity getSpData(CrossProcessDataEntity paramCrossProcessDataEntity) {
CrossProcessDataEntity crossProcessDataEntity = null;
if (paramCrossProcessDataEntity != null) {
String str1;
CrossProcessDataEntity.Builder builder = new CrossProcessDataEntity.Builder();
String str4 = paramCrossProcessDataEntity.getString("sp_data_file");
String str5 = paramCrossProcessDataEntity.getString("sp_data_key");
String str3 = paramCrossProcessDataEntity.getString("sp_data_default");
paramCrossProcessDataEntity = crossProcessDataEntity;
if (!TextUtils.isEmpty(str5)) {
paramCrossProcessDataEntity = crossProcessDataEntity;
if (str4 != null)
str1 = KVUtil.getSharedPreferences((Context)AppbrandContext.getInst().getApplicationContext(), str4).getString(str5, str3);
}
String str2 = str1;
if (TextUtils.isEmpty(str1)) {
str1 = str3;
if (str3 == null)
str1 = "";
str2 = str1;
}
builder.put("sp_data_value", str2);
return builder.build();
}
return null;
}
static boolean handleAsyncCall(String paramString, CrossProcessDataEntity paramCrossProcessDataEntity1, CrossProcessDataEntity paramCrossProcessDataEntity2, AsyncIpcHandler paramAsyncIpcHandler) {
byte b;
AppBrandLogger.i("InnerHostProcessCallHandler", new Object[] { "beforeHandleAsyncCall callType:", paramString });
switch (paramString.hashCode()) {
default:
b = -1;
break;
case 1915939293:
if (paramString.equals("hostProcess_callback")) {
b = 4;
break;
}
case 1707634780:
if (paramString.equals("updateBaseBundle")) {
b = 3;
break;
}
case 820504303:
if (paramString.equals("registerBgAudioPlayState")) {
b = 6;
break;
}
case -316023509:
if (paramString.equals("getLocation")) {
b = 5;
break;
}
case -600628793:
if (paramString.equals("scheduleApiHandler")) {
b = 0;
break;
}
case -806813950:
if (paramString.equals("notifyPreloadEmptyProcess")) {
b = 8;
break;
}
case -953620209:
if (paramString.equals("checkUpdateOfflineZip")) {
b = 9;
break;
}
case -1405248603:
if (paramString.equals("setTmaLaunchFlag")) {
b = 1;
break;
}
case -1614149786:
if (paramString.equals("savePlatformSession")) {
b = 2;
break;
}
case -1932192966:
if (paramString.equals("getSnapshot")) {
b = 7;
break;
}
}
switch (b) {
default:
bool = false;
AppBrandLogger.i("InnerHostProcessCallHandler", new Object[] { "afterHandleAsyncCall callType:", paramString, "handled:", Boolean.valueOf(bool) });
return bool;
case 9:
checkUpdateOfflineZip(paramCrossProcessDataEntity1, paramAsyncIpcHandler);
break;
case 8:
preloadEmptyProcess();
break;
case 7:
getSnapShot(paramCrossProcessDataEntity1, paramAsyncIpcHandler);
break;
case 6:
registerBgAudioPlayState(paramCrossProcessDataEntity1, paramAsyncIpcHandler);
break;
case 5:
getLocation(paramAsyncIpcHandler);
break;
case 4:
callback(paramCrossProcessDataEntity1, paramCrossProcessDataEntity2);
break;
case 3:
updateBaseBundle();
break;
case 2:
savePlatformSession(paramCrossProcessDataEntity1);
break;
case 1:
setTmaLaunchFlag(paramCrossProcessDataEntity1);
break;
case 0:
apiHandler(paramCrossProcessDataEntity1, paramAsyncIpcHandler);
break;
}
boolean bool = true;
AppBrandLogger.i("InnerHostProcessCallHandler", new Object[] { "afterHandleAsyncCall callType:", paramString, "handled:", Boolean.valueOf(bool) });
return bool;
}
static boolean handleSyncCall(String paramString, CrossProcessDataEntity paramCrossProcessDataEntity1, CrossProcessDataEntity paramCrossProcessDataEntity2, CrossProcessDataEntity[] paramArrayOfCrossProcessDataEntity) {
byte b;
AppBrandLogger.i("InnerHostProcessCallHandler", new Object[] { "beforeHandleSyncCall callType:", paramString });
switch (paramString.hashCode()) {
default:
b = -1;
break;
case 2121261769:
if (paramString.equals("back_app")) {
b = 3;
break;
}
case 2034582128:
if (paramString.equals("type_update_favorite_set")) {
b = 15;
break;
}
case 1301584782:
if (paramString.equals("jump_to_app")) {
b = 1;
break;
}
case 1084566112:
if (paramString.equals("type_add_to_favorite_set")) {
b = 13;
break;
}
case 1078329351:
if (paramString.equals("notify_mini_app_process_crash")) {
b = 8;
break;
}
case 1064884100:
if (paramString.equals("saveSpData")) {
b = 16;
break;
}
case 803973105:
if (paramString.equals("restart_app")) {
b = 0;
break;
}
case 798957213:
if (paramString.equals("getSpData")) {
b = 17;
break;
}
case 638061061:
if (paramString.equals("addHostEventListener")) {
b = 19;
break;
}
case 399449253:
if (paramString.equals("jump_to_app_from_schema")) {
b = 2;
break;
}
case 383221365:
if (paramString.equals("mini_process_used")) {
b = 7;
break;
}
case 213806617:
if (paramString.equals("update_jump_list")) {
b = 4;
break;
}
case 198277422:
if (paramString.equals("actionLog")) {
b = 9;
break;
}
case -39279151:
if (paramString.equals("getCurrentLang")) {
b = 21;
break;
}
case -370283307:
if (paramString.equals("httpRequestWithCommonParam")) {
b = 22;
break;
}
case -488436872:
if (paramString.equals("type_get_favorite_settings")) {
b = 11;
break;
}
case -674684898:
if (paramString.equals("type_remove_from_favorite_set")) {
b = 14;
break;
}
case -676828179:
if (paramString.equals("type_get_favorite_set")) {
b = 12;
break;
}
case -858493621:
if (paramString.equals("removeSpData")) {
b = 18;
break;
}
case -965406614:
if (paramString.equals("is_in_jump_list")) {
b = 5;
break;
}
case -991883533:
if (paramString.equals("type_bg_audio_sync_commond")) {
b = 10;
break;
}
case -1276138387:
if (paramString.equals("getPlatformSession")) {
b = 6;
break;
}
case -2056786814:
if (paramString.equals("removeHostEventListener")) {
b = 20;
break;
}
}
switch (b) {
default:
bool = false;
AppBrandLogger.i("InnerHostProcessCallHandler", new Object[] { "afterHandleSyncCall callType:", paramString, "handled:", Boolean.valueOf(bool) });
return bool;
case 22:
paramArrayOfCrossProcessDataEntity[0] = httpRequestWithCommonParam(paramCrossProcessDataEntity1);
break;
case 21:
paramArrayOfCrossProcessDataEntity[0] = getCurrentLocale(paramCrossProcessDataEntity1);
break;
case 20:
removeHostEventListener(paramCrossProcessDataEntity1);
break;
case 19:
addHostEventListener(paramCrossProcessDataEntity1);
break;
case 18:
removeSpData(paramCrossProcessDataEntity1);
break;
case 17:
paramArrayOfCrossProcessDataEntity[0] = getSpData(paramCrossProcessDataEntity1);
break;
case 16:
saveSpData(paramCrossProcessDataEntity1);
break;
case 15:
updateFavoriteSet(paramCrossProcessDataEntity1);
break;
case 14:
removeFromFavoriteSet(paramCrossProcessDataEntity1);
break;
case 13:
addToFavoriteSet(paramCrossProcessDataEntity1);
break;
case 12:
paramArrayOfCrossProcessDataEntity[0] = getFavoriteSet();
break;
case 11:
paramArrayOfCrossProcessDataEntity[0] = getFavoriteSettings();
break;
case 10:
paramArrayOfCrossProcessDataEntity[0] = innerDealBgAudioCommond(paramCrossProcessDataEntity1);
break;
case 9:
bool = innerPreHandleEventLog(paramCrossProcessDataEntity1);
AppBrandLogger.i("InnerHostProcessCallHandler", new Object[] { "afterHandleSyncCall callType:", paramString, "handled:", Boolean.valueOf(bool) });
return bool;
case 8:
notifyMiniAppProcessCrash(paramCrossProcessDataEntity1);
break;
case 7:
initMiniProcessMonitor(paramCrossProcessDataEntity1);
break;
case 6:
paramArrayOfCrossProcessDataEntity[0] = getPlatformSession(paramCrossProcessDataEntity1);
break;
case 5:
paramArrayOfCrossProcessDataEntity[0] = isInJumplist(paramCrossProcessDataEntity1);
break;
case 4:
updateJumpList(paramCrossProcessDataEntity1);
break;
case 3:
paramArrayOfCrossProcessDataEntity[0] = backApp(paramCrossProcessDataEntity1);
break;
case 2:
jumpToAppFromOpenSchema(paramCrossProcessDataEntity1);
break;
case 1:
jumpToApp(paramCrossProcessDataEntity1);
break;
case 0:
restartApp(paramCrossProcessDataEntity1);
break;
}
boolean bool = true;
AppBrandLogger.i("InnerHostProcessCallHandler", new Object[] { "afterHandleSyncCall callType:", paramString, "handled:", Boolean.valueOf(bool) });
return bool;
}
private static CrossProcessDataEntity httpRequestWithCommonParam(CrossProcessDataEntity paramCrossProcessDataEntity) {
HttpRequest.RequestResult requestResult;
HttpRequest.RequestTask requestTask = (HttpRequest.RequestTask)paramCrossProcessDataEntity.getParcelable("httpRequestTask");
try {
requestResult = RequestManagerV2.getInst().requestSync("ttnet", requestTask);
} finally {
Exception exception = null;
AppBrandLogger.e("InnerHostProcessCallHandler", new Object[] { "httpRequestWithCommonParam", exception });
requestResult = new HttpRequest.RequestResult(requestTask.a);
requestResult.b = false;
}
return CrossProcessDataEntity.Builder.create().putParcelable("httpRequestResult", (Parcelable)requestResult).build();
}
private static void initMiniProcessMonitor(CrossProcessDataEntity paramCrossProcessDataEntity) {
if (paramCrossProcessDataEntity == null)
return;
AppProcessManager.ProcessInfo processInfo = AppProcessManager.getProcessInfoByProcessName(paramCrossProcessDataEntity.getString("processName"));
if (processInfo != null)
AppProcessManager.startMiniProcessMonitor((Context)AppbrandContext.getInst().getApplicationContext(), processInfo, false);
}
private static CrossProcessDataEntity innerDealBgAudioCommond(CrossProcessDataEntity paramCrossProcessDataEntity) {
BgAudioState bgAudioState1;
String str2;
BgAudioModel bgAudioModel;
String str1;
CrossProcessDataEntity.Builder builder;
BgAudioState bgAudioState2 = null;
if (paramCrossProcessDataEntity == null)
return null;
int i = paramCrossProcessDataEntity.getInt("bgAudioId");
BgAudioCommand bgAudioCommand = BgAudioCommand.fromString(paramCrossProcessDataEntity.getString("bgAudioCommondType"));
switch (bgAudioCommand) {
default:
return null;
case null:
return CrossProcessDataEntity.Builder.create().put("bgAudioCommandRetNeedKeepAlive", Boolean.valueOf(BgAudioManagerServiceNative.getInst().needKeepAlive(i))).build();
case GET_AUDIO_STATE:
bgAudioState1 = BgAudioManagerServiceNative.getInst().getAudioState(i);
builder = CrossProcessDataEntity.Builder.create();
if (bgAudioState1 == null) {
bgAudioState1 = bgAudioState2;
} else {
str2 = bgAudioState1.toJSONStr();
}
return builder.put("bgAudioCommondRetState", str2).build();
case SET_AUDIO_MODEL:
bgAudioModel = BgAudioModel.parseFromJSONStr(str2.getString("bgAudioCommondInfo"));
if (bgAudioModel != null) {
BgAudioManagerServiceNative.getInst().setAudioModel(i, bgAudioModel);
return null;
}
return null;
case SEEK:
str1 = bgAudioModel.getString("bgAudioCommondInfo");
if (!TextUtils.isEmpty(str1)) {
BgAudioManagerServiceNative.getInst().seek(i, Integer.valueOf(str1).intValue());
return null;
}
return null;
case STOP:
BgAudioManagerServiceNative.getInst().stop(i);
return null;
case PAUSE:
BgAudioManagerServiceNative.getInst().pause(i);
return null;
case PLAY:
BgAudioManagerServiceNative.getInst().play(i);
return null;
case OBTAIN_MANAGER:
break;
}
BgAudioCallExtra bgAudioCallExtra = BgAudioCallExtra.parseFromJSONStr(str1.getString("bgAudioCommondInfo"));
i = BgAudioManagerServiceNative.getInst().obtainManager(i, bgAudioCallExtra);
return CrossProcessDataEntity.Builder.create().put("bgAudioId", Integer.valueOf(i)).build();
}
private static boolean innerPreHandleEventLog(CrossProcessDataEntity paramCrossProcessDataEntity) {
return (paramCrossProcessDataEntity == null) ? false : InnerMiniProcessLogHelper.innerHandleEventLog(paramCrossProcessDataEntity.getString("logEventName"), paramCrossProcessDataEntity.getJSONObject("logEventData"));
}
private static CrossProcessDataEntity isInJumplist(CrossProcessDataEntity paramCrossProcessDataEntity) {
String str = paramCrossProcessDataEntity.getString("miniAppId");
return CrossProcessDataEntity.Builder.create().put("is_in_jumplist", Boolean.valueOf(AppJumpListManager.isInAppJumpList(str))).build();
}
private static void jumpToApp(CrossProcessDataEntity paramCrossProcessDataEntity) {
String str1 = paramCrossProcessDataEntity.getString("miniAppToId");
String str2 = paramCrossProcessDataEntity.getString("miniAppFromId");
String str3 = paramCrossProcessDataEntity.getString("startPage");
String str4 = paramCrossProcessDataEntity.getString("query");
String str5 = paramCrossProcessDataEntity.getString("refererInfo");
String str6 = paramCrossProcessDataEntity.getString("version_type");
int i = paramCrossProcessDataEntity.getInt("miniAppOrientation");
AppJumpListManager.jumpToApp(str1, str3, str4, str5, paramCrossProcessDataEntity.getBoolean("isGame"), str6, str2, i, paramCrossProcessDataEntity.getString("miniAppOriginEntrance"));
}
private static void jumpToAppFromOpenSchema(CrossProcessDataEntity paramCrossProcessDataEntity) {
if (paramCrossProcessDataEntity == null)
return;
AppJumpListManager.jumpToApp(paramCrossProcessDataEntity.getString("schema"), paramCrossProcessDataEntity.getString("miniAppFromId"), paramCrossProcessDataEntity.getBoolean("isGame"));
}
private static void notifyMiniAppProcessCrash(final CrossProcessDataEntity callData) {
if (callData == null)
return;
if (ChannelUtil.isLocalTest()) {
final Activity hostProcessTopActivity = HostActivityManager.getHostTopActivity();
if (activity == null || activity.isFinishing()) {
HostDependManager.getInst().showToast((Context)AppbrandContext.getInst().getApplicationContext(), null, a.a("小程序进程 %s 出现 crash:%s", new Object[] { callData.getString("processName"), callData.getString("exceptionMessage") }), 0L, null);
return;
}
ThreadUtil.runOnUIThread(new Runnable() {
public final void run() {
HostDependManager hostDependManager = HostDependManager.getInst();
Activity activity = hostProcessTopActivity;
StringBuilder stringBuilder = new StringBuilder("此消息仅在 local_test 渠道下展示。\nCrash信息:\n");
stringBuilder.append(callData.getString("exceptionMessage"));
hostDependManager.showModal(activity, null, "小程序进程 Crash", stringBuilder.toString(), false, null, null, "确定", null, new NativeModule.NativeModuleCallback<Integer>() {
public void onNativeModuleCall(Integer param2Integer) {}
});
}
});
return;
}
}
private static void preloadEmptyProcess() {
AppbrandConstants.getProcessManager().preloadEmptyProcess(true);
}
private static void registerBgAudioPlayState(CrossProcessDataEntity paramCrossProcessDataEntity, final AsyncIpcHandler asyncIpcHandler) {
if (paramCrossProcessDataEntity == null) {
DebugUtil.outputError("InnerHostProcessCallHandler", new Object[] { "registerBgAudioPlayState callData == null" });
return;
}
final int audioId = paramCrossProcessDataEntity.getInt("bgAudioId");
if (i < 0)
return;
ThreadUtil.runOnWorkThread(new Action() {
public final void act() {
BgAudioManagerServiceNative.getInst().register(audioId, new BgAudioPlayStateListener() {
public void onBgPlayProcessDied(BgAudioModel param2BgAudioModel, boolean param2Boolean) {}
public void onPlayStateChange(String param2String, BgAudioModel param2BgAudioModel, boolean param2Boolean) {
asyncIpcHandler.callback(CrossProcessDataEntity.Builder.create().put("bgAudioPlayState", param2String).build(), false);
}
public void onProgressChange(int param2Int, BgAudioModel param2BgAudioModel) {}
public void onTriggerPlay(BgAudioModel param2BgAudioModel) {}
});
}
}ThreadPools.defaults());
}
private static void removeFromFavoriteSet(CrossProcessDataEntity paramCrossProcessDataEntity) {
if (paramCrossProcessDataEntity == null)
return;
String str = paramCrossProcessDataEntity.getString("mini_app_id");
if (TextUtils.isEmpty(str))
return;
if (FavoriteMiniAppMenuItem.sFavoriteSet == null)
return;
Iterator<String> iterator = FavoriteMiniAppMenuItem.sFavoriteSet.iterator();
while (iterator.hasNext()) {
if (((String)iterator.next()).contentEquals(str)) {
iterator.remove();
break;
}
}
}
public static void removeHostEventListener(CrossProcessDataEntity paramCrossProcessDataEntity) {
if (paramCrossProcessDataEntity != null) {
String str2 = paramCrossProcessDataEntity.getString("host_event_mp_id");
String str1 = paramCrossProcessDataEntity.getString("host_event_event_name");
if (!TextUtils.isEmpty(str2) && !TextUtils.isEmpty(str1)) {
HostEventServiceInterface hostEventServiceInterface = (HostEventServiceInterface)ServiceProvider.getInstance().getService(HostEventService.class);
if (hostEventServiceInterface != null)
hostEventServiceInterface.hostProcessRemoveHostEventListener(str2, str1);
}
}
}
public static void removeSpData(CrossProcessDataEntity paramCrossProcessDataEntity) {
if (paramCrossProcessDataEntity != null) {
String str2 = paramCrossProcessDataEntity.getString("sp_data_key");
String str1 = paramCrossProcessDataEntity.getString("sp_data_file");
if (!TextUtils.isEmpty(str2) && !TextUtils.isEmpty(str1))
KVUtil.getSharedPreferences((Context)AppbrandContext.getInst().getApplicationContext(), str1).edit().remove(str2).apply();
}
}
private static void restartApp(final CrossProcessDataEntity callData) {
if (callData == null) {
DebugUtil.outputError("InnerHostProcessCallHandler", new Object[] { "restartApp callData == null" });
return;
}
Observable.create(new Action() {
public final void act() {
AppbrandContext.getInst().getApplicationContext();
String str2 = callData.getString("miniAppId");
String str1 = callData.getString("miniAppSchema");
if (!TextUtils.isEmpty(str2))
AppProcessManager.killProcess(str2);
try {
Thread.sleep(500L);
} catch (InterruptedException interruptedException) {
AppBrandLogger.stacktrace(6, "InnerHostProcessCallHandler", interruptedException.getStackTrace());
}
if (!TextUtils.isEmpty(str1))
AppbrandSupport.inst().openAppbrand(str1);
}
}).schudleOn((Scheduler)LaunchThreadPool.getInst()).subscribeSimple();
}
private static void savePlatformSession(CrossProcessDataEntity paramCrossProcessDataEntity) {
if (paramCrossProcessDataEntity == null) {
DebugUtil.outputError("InnerHostProcessCallHandler", new Object[] { "savePlatformSession callData == null" });
return;
}
Application application = AppbrandContext.getInst().getApplicationContext();
if (application == null) {
AppBrandLogger.e("InnerHostProcessCallHandler", new Object[] { "savePlatformSession context == null" });
return;
}
String str2 = paramCrossProcessDataEntity.getString("miniAppId");
String str1 = paramCrossProcessDataEntity.getString("platformSession");
StringBuilder stringBuilder = new StringBuilder("appId ");
stringBuilder.append(str2);
stringBuilder.append(" platformSession ");
stringBuilder.append(str1);
AppBrandLogger.d("InnerHostProcessCallHandler", new Object[] { stringBuilder.toString() });
if (!TextUtils.isEmpty(str2)) {
if (TextUtils.isEmpty(str1))
return;
StorageUtil.saveSession((Context)application, str2, str1);
}
}
public static void saveSpData(CrossProcessDataEntity paramCrossProcessDataEntity) {
if (paramCrossProcessDataEntity != null) {
String str2 = paramCrossProcessDataEntity.getString("sp_data_file");
String str3 = paramCrossProcessDataEntity.getString("sp_data_key");
String str1 = paramCrossProcessDataEntity.getString("sp_data_value");
if (!TextUtils.isEmpty(str3) && str2 != null)
KVUtil.getSharedPreferences((Context)AppbrandContext.getInst().getApplicationContext(), str2).edit().putString(str3, str1).apply();
}
}
private static void setTmaLaunchFlag(CrossProcessDataEntity paramCrossProcessDataEntity) {
if (paramCrossProcessDataEntity == null) {
DebugUtil.outputError("InnerHostProcessCallHandler", new Object[] { "setTmaLaunchFlag callData == null" });
return;
}
final String processName = paramCrossProcessDataEntity.getString("processName");
final String appId = paramCrossProcessDataEntity.getString("miniAppId");
final String versionType = paramCrossProcessDataEntity.getString("miniAppVersionType");
AppBrandLogger.d("InnerHostProcessCallHandler", new Object[] { "handleAsyncCall setTmaLaunchFlag processName:", str2, "appId:", str3, "versionType:", str1 });
if (TextUtils.isEmpty(str2) || TextUtils.isEmpty(str3)) {
DebugUtil.outputError("InnerHostProcessCallHandler", new Object[] { "TextUtils.isEmpty(processName) || TextUtils.isEmpty(appId)" });
return;
}
ThreadUtil.runOnWorkThread(new Action() {
public final void act() {
AppProcessManager.updateAppProcessInfo(processName, appId, versionType);
Application application = AppbrandContext.getInst().getApplicationContext();
LaunchCacheDAO.INSTANCE.increaseNormalLaunchCounter((Context)application, appId);
}
}Schedulers.shortIO());
}
private static void updateBaseBundle() {
AppbrandConstants.getBundleManager().checkUpdateBaseBundle((Context)AppbrandContext.getInst().getApplicationContext());
}
private static void updateFavoriteSet(CrossProcessDataEntity paramCrossProcessDataEntity) {
if (paramCrossProcessDataEntity == null) {
FavoriteMiniAppMenuItem.sFavoriteSet = null;
return;
}
List<?> list = paramCrossProcessDataEntity.getStringList("favorite_set");
if (list == null) {
FavoriteMiniAppMenuItem.sFavoriteSet = null;
return;
}
FavoriteMiniAppMenuItem.sFavoriteSet = new LinkedHashSet(list);
}
private static void updateJumpList(CrossProcessDataEntity paramCrossProcessDataEntity) {
AppJumpListManager.updateJumpList(paramCrossProcessDataEntity.getString("miniAppId"), paramCrossProcessDataEntity.getBoolean("isGame"), paramCrossProcessDataEntity.getBoolean("isSpecial"));
AppJumpListManager.killPreAppIfNeed();
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\process\handler\InnerHostProcessCallHandler.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
/**
*
*/
package queries;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import queries.EmployeeMapReduce4.EmployeeMapper4;
import queries.EmployeeMapReduce4.EmployeeReducer4;
/**
* @author kiran
*
*/
public class EmployeeQueriesToolRunner extends Configured implements Tool {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
int result = ToolRunner.run(new EmployeeQueriesToolRunner(), args);
System.exit(result);
}
public int run(String[] args) throws Exception{
if(args.length != 2 ){
System.err.println("Invalid arguments: Expected format EmployeeQueriesToolRunner <inputfile path> <outputfile path>");
return -1;
}
Job job = Job.getInstance(this.getConf(), "Employee Queries");
job.setJarByClass(EmployeeMapReduce.class);
FileInputFormat.setInputPaths(job, new Path(args[0]));
Path fileOutputPath = new Path(args[1]);
FileOutputFormat.setOutputPath(job, fileOutputPath);
//delete the path if already exist
fileOutputPath.getFileSystem(this.getConf()).delete(fileOutputPath,true);
job.setMapperClass(EmployeeMapper4.class);
job.setReducerClass(EmployeeReducer4.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(DoubleWritable.class);
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
return job.waitForCompletion(true) ? 0 : 1;
}
}
|
package br.com.sicredi.validationpoints;
import org.junit.Assert;
public class SimulationValidationPoint {
private static final String MORE_OPTIONS_MESSAGE = "Veja estas outras opções para você";
private static final String TOTAL_AMOUNT = "R$ 2.206";
public SimulationValidationPoint() {
}
public void validateMoreOptionsMessage(String message){
Assert.assertEquals(MORE_OPTIONS_MESSAGE, message);
}
public void validateTotalAmount(String totalAmount){
Assert.assertEquals(totalAmount, TOTAL_AMOUNT);
}
}
|
package com.classcheck.tree;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TreeItemIterator implements Iterator<FileNode> {
private FileNode root;
private LinkedList<FileNode> stack;
private Pattern pattern;
public TreeItemIterator(FileTree tree) {
this.root = tree.getRoot();
this.stack = new LinkedList<FileNode>();
stack.push(root);
this.pattern = tree.getPattern();
}
public boolean hasNext() {
return !stack.isEmpty();
}
/*
* 幅優先探索を行う
*/
public FileNode next() {
FileNode fileNode = stack.pop();
List<FileNode> children = fileNode.getChildren();
Matcher matcher = null;
//childrenがnullの時は空
if (children != null) {
for (FileNode child : children) {
stack.addLast(child);
}
}
//fileNodeが特定のファイル拡張子と一致した場合のみ返却する
matcher = pattern.matcher(fileNode.getName());
if (matcher.find()) {
return fileNode;
}else{
return null;
}
}
public Iterator<FileNode> iterator() {
return this;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
} |
package ar.utn.frba.sceu.tickets.DTO;
import java.sql.Date;
import ar.utn.frba.sceu.tickets.Models.Cliente;
import ar.utn.frba.sceu.tickets.Models.Tecnico;
public class SolicitudDTO {
Integer id;
private Tecnico tecnico_id;
boolean realizado, borrado;
Date fecha_limite;
String detalle;
private Cliente cliente_id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Cliente getCliente_id() {
return cliente_id;
}
public void setCliente_id(Cliente cliente_id) {
this.cliente_id = cliente_id;
}
public Tecnico getTecnico_id() {
return tecnico_id;
}
public void setTecnico_id(Tecnico tecnico_id) {
this.tecnico_id = tecnico_id;
}
public boolean isRealizado() {
return realizado;
}
public void setRealizado(boolean realizado) {
this.realizado = realizado;
}
public boolean isBorrado() {
return borrado;
}
public void setBorrado(boolean borrado) {
this.borrado = borrado;
}
public Date getFecha_limite() {
return fecha_limite;
}
public void setFecha_limite(Date fecha_limite) {
this.fecha_limite = fecha_limite;
}
public String getDetalle() {
return detalle;
}
public void setDetalle(String detalle) {
this.detalle = detalle;
}
}
|
package com.gmail.ivanytskyy.vitaliy.repository;
import java.util.List;
import com.gmail.ivanytskyy.vitaliy.model.Group;
/*
* Repository interface for Group domain objects
* @author Vitaliy Ivanytskyy
*/
public interface GroupRepository {
Group create(Group group);
Group findById(long id);
List<Group> findByName(String name);
List<Group> findAll();
boolean isExistsWithName(String name);
void deleteById(long id);
} |
package com.config;
import com.badlogic.gdx.graphics.Texture;
import com.classes.ETFortress;
import com.config.Constants;
/* Data class for use when providing unique parameters to the spawning of a new ETFortress.
*
*/
public class ETFortressFactory {
public Texture texture;
public Texture destroyedTexture;
public int projectileDamage;
public int maxHealth;
private float x;
private float y;
private float scaleX;
private float scaleY;
// Fortress-specific values
public ETFortress createETFortress (ETFortressType type) {
switch (type) {
case CLIFFORDS_TOWER:
texture = new Texture("MapAssets/UniqueBuildings/cliffordstower.png");
destroyedTexture = new Texture("MapAssets/UniqueBuildings/cliffordstower_wet.png");
projectileDamage = 10;
maxHealth = 100;
x = 69;
y = 51;
scaleX = 1;
scaleY = 1;
break;
case RAIL_STATION:
texture = new Texture("MapAssets/UniqueBuildings/railstation.png");
destroyedTexture = new Texture("MapAssets/UniqueBuildings/railstation_wet.png");
projectileDamage = 15;
maxHealth = 50;
x = 1;
y = 72.75f;
scaleX = 3;
scaleY = 2.5f;
break;
case YORK_MINSTER:
texture = new Texture("MapAssets/UniqueBuildings/Yorkminster.png");
destroyedTexture = new Texture("MapAssets/UniqueBuildings/Yorkminster_wet.png");
projectileDamage = 5;
maxHealth = 150;
x = 68.25f;
y = 82.25f;
scaleX = 2;
scaleY = 3.25f;
break;
case STADIUM:
texture = new Texture("MapAssets/UniqueBuildings/YorkStadium.png");
destroyedTexture = new Texture("MapAssets/UniqueBuildings/YorkStadium_wet.png");
projectileDamage = 7;
maxHealth = 125;
x = 36;
y = 69;
scaleX = 1;
scaleY = 1;
break;
case FIBBERS:
texture = new Texture("MapAssets/UniqueBuildings/fibbers.png");
destroyedTexture = new Texture("MapAssets/UniqueBuildings/fibbers_wet.png");
projectileDamage = 13;
maxHealth = 75;
x = 91;
y = 70;
scaleX = 1;
scaleY = 1;
break;
case WINDMILL:
texture = new Texture("MapAssets/UniqueBuildings/windmill.png");
destroyedTexture = new Texture("MapAssets/UniqueBuildings/windmill_wet.png");
projectileDamage = 9;
maxHealth = 110;
x = 25;
y = 48;
scaleX = 1;
scaleY = 1;
break;
default:
throw new RuntimeException("Requested ETFortressType " + type + " does not exist.");
}
return new ETFortress(texture, destroyedTexture, projectileDamage, maxHealth, scaleX, scaleY, x * Constants.TILE_DIMS, y * Constants.TILE_DIMS, type);
}
}
|
package com.hawk.application.model;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class SearchReportVoTest {
@Test
public void test() {
SearchReportVo vo = new SearchReportVo.Builder().build();
assertTrue(vo.isSelectedAllApp());
}
}
|
package sk.itsovy.strausz.projectdp;
public class Whey implements Protein {
@Override
public void print() {
System.out.println("Iam Whey protein.");
}
}
|
package com.example.demo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.example.demo.service.EmailService;
@Configuration
public class MyConfiguration {
// spEl
@Value("#{systemProperties['user.name']}")
private String userName;
@Bean
public EmailService emailService(@Value("${email.server}") String server,
@Value("${email.port}") int port) {
return new EmailService(server + ":" + userName, port);
}
}
|
package entidades.abstractas;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import GUI.Gui;
import juego.Juego;
import state.Estado;
import visitor.VisitorDisparoAliado;
public abstract class DisparoAliado extends Disparo{
protected DisparoAliado(int x, int y, int daņo, int vel, int alcance, Estado estado) {
super(x, y, daņo, vel, estado);
target = this.x + alcance*Gui.spriteSize + Gui.spriteSize/2;
setVisitor();
this.x += Gui.spriteSize/2; //Ubica el inicio del disparo en el centro de la celda
sprite = new JLabel();
sprite.setIcon(new ImageIcon(this.getClass().getResource("/recursos/arrow.png")));
sprite.setBounds(this.x, this.y, Gui.spriteSize, Gui.spriteSize);
}
protected void setVisitor() {
miVisitor = new VisitorDisparoAliado(this);
}
public void mover() {
x+= estado.getVelocidad(velocidad);
sprite.setBounds(x, y, Gui.spriteSize, Gui.spriteSize);
if (x>=target) {
morir();
}
}
public void accion(float estimatedTime) {
Juego.getJuego().visitarEntidades(miVisitor);
mover();
}
}
|
package com.company;
public class Main {
private static Menu menu = new Menu();
private static String option;
public static void main(String[] args) {
option = menu.startMenu();
if (option.equals("1")) {
System.out.println("Aguarde, estamos processando suas informações!");
} else if (option.equals("2")) {
System.exit(0);
} else {
System.out.println("Código não reconhecido, tente novamente");
option = menu.startMenu();
}
CSVReader csvReader = new CSVReader();
csvReader.run("/Users/isa/Documents/BSI/doutorado/test/resources/example.csv");
}
}
|
package com.cn.my.dao;
import com.cn.my.bean.Code;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface CodeMapper{
/**
* 插入代码
* @param code
* @return
*/
public int insertCode(Code code);
/**
* 修改代码
* @param code
* @return
*/
public int updateCode(Code code);
/**
* 删除代码
* @param code
* @return
*/
public int deletetCodeById(Code code);
/**
* 根据ID查找代码
* @param codeId
* @return
*/
public Code selectCodeById(int codeId);
/**
* 根据条件代码
* @param
* @return
*/
public List<Code> selectCodeByCond(Code code);
/**
* 查找数量
* @param code
* @return
*/
public int selectCodeCountByCond(Code code);
} |
package io.twodigits.urlshortener.exceptions;
public class URLNotValidException extends URLShortenerException
{
public URLNotValidException() {
super("URL IS INVALID");
}
}
|
package com.bowlong.sql.jdbc;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import javax.sql.DataSource;
import javax.sql.RowSet;
import javax.sql.rowset.CachedRowSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.bowlong.lang.StrEx;
import com.bowlong.lang.task.MyThreadFactory;
import com.bowlong.sql.SqlEx;
import com.bowlong.third.FastJSON;
import com.bowlong.util.ExceptionEx;
import com.bowlong.util.ListEx;
import com.bowlong.util.MapEx;
import com.bowlong.util.NewSet;
import com.sun.rowset.CachedRowSetImpl;
@SuppressWarnings("all")
public class JdbcTempletOrigin {
/*** 记录数据连接对象目录下的所有表名称 **/
private static final Map<String, NewSet<String>> TABLES = newMap();
// 数据库连接模式[conn如果不为空,则只有一个连接]
Connection conn; // 单链接模式
DataSource ds_r; // 读写分离模式(读数据源)
DataSource ds_w; // 读写分离模式(写数据源)
// 检索此 Connection 对象的当前目录名称。
private String catalog_r;
// 检索此 Connection 对象的当前目录名称。
private String catalog_w;
public static final Log getLog(Class<?> clazz) {
return LogFactory.getLog(clazz);
}
public JdbcTempletOrigin(final Connection conn) {
this.conn = conn;
}
public JdbcTempletOrigin(final DataSource ds) {
this.ds_r = ds;
this.ds_w = ds;
}
public JdbcTempletOrigin(final DataSource ds_r, final DataSource ds_w) {
this.ds_r = ds_r;
this.ds_w = ds_w;
}
public DataSource ds_r() {
return ds_r;
}
public DataSource ds_w() {
return ds_w;
}
public String catalog_r() throws SQLException {
if (!StrEx.isEmpty(catalog_r))
return catalog_r;
Connection conn = null;
try {
conn = conn_r();
catalog_r = conn.getCatalog();
return catalog_r;
} finally {
closeNoExcept(conn);
}
}
public String catalog_w() throws SQLException {
if (!StrEx.isEmpty(catalog_w))
return catalog_w;
Connection conn = null;
try {
conn = conn_w();
catalog_w = conn.getCatalog();
return catalog_w;
} finally {
closeNoExcept(conn);
}
}
// /////////////////////////
public void close() throws SQLException {
try {
if (this.conn != null && !this.conn.isClosed()) {
this.conn.close();
}
} finally {
this.conn = null;
this.ds_r = null;
this.ds_w = null;
}
}
protected final void closeNoExcept(final Connection conn) {
try {
close(conn);
} catch (Exception e) {
}
}
protected final void close(final Connection conn) throws SQLException {
if (this.conn != null) // 如果是单链接模式则不关闭链接
return;
conn.close();
}
// /////////////////////////
public final Connection conn_r() throws SQLException {
if (this.conn != null)
return this.conn;
return ds_r.getConnection();
}
public final Connection conn_w() throws SQLException {
if (this.conn != null)
return this.conn;
return ds_w.getConnection();
}
// /////////////////////////
public void execute(final String sql) throws SQLException {
Connection conn = conn_w();
try {
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.execute();
stmt.close();
} catch (SQLException e) {
throw rethrow(e, sql);
} finally {
close(conn);
}
}
public CachedRowSet query(final String sql) throws SQLException {
Connection conn = conn_r();
try {
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
CachedRowSet crs = new CachedRowSetImpl();
crs.populate(rs);
rs.close();
stmt.close();
return crs;
} catch (SQLException e) {
throw rethrow(e, sql);
} finally {
close(conn);
}
}
// private <T> T query(String sql, Class c) throws Exception {
// ResultSetHandler rsh = getRsh(c);
// return query(sql, rsh);
// }
public <T> T query(final String sql, final ResultSetHandler rsh)
throws SQLException {
Connection conn = conn_r();
try {
T r2 = null;
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
if (rs.next())
r2 = (T) rsh.handle(rs);
rs.close();
stmt.close();
return r2;
} catch (SQLException e) {
throw rethrow(e, sql);
} finally {
close(conn);
}
}
public final <T> T queryForObject(final String sql,
final ResultSetHandler rsh) throws SQLException {
return query(sql, rsh);
}
public Map queryForMap(final String sql) throws SQLException {
Connection conn = conn_r();
try {
Map r2 = null;
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
if (rs.next())
r2 = toMap(rs);
rs.close();
stmt.close();
return r2;
} catch (SQLException e) {
throw rethrow(e, sql);
} finally {
close(conn);
}
}
public List<Map> queryForList(final String sql) throws SQLException {
Connection conn = conn_r();
try {
List<Map> r2 = null;
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
r2 = toMaps(rs);
rs.close();
stmt.close();
return r2;
} catch (SQLException e) {
throw rethrow(e, sql);
} finally {
close(conn);
}
}
public <T> List<T> queryForKeys(final String sql) throws SQLException {
Connection conn = conn_r();
try {
List<T> r2 = null;
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
r2 = toKeys(rs);
rs.close();
stmt.close();
return r2;
} catch (SQLException e) {
throw rethrow(e, sql);
} finally {
close(conn);
}
}
public <T> List<T> queryForList(final String sql, final ResultSetHandler rsh)
throws SQLException {
Connection conn = conn_r();
try {
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
List<T> result = newList();
while (rs.next()) {
T v = (T) rsh.handle(rs);
result.add(v);
}
rs.close();
stmt.close();
return result;
} catch (SQLException e) {
throw rethrow(e, sql);
} finally {
close(conn);
}
}
public long queryForLong(final String sql) throws SQLException {
Connection conn = conn_r();
try {
long r2 = 0;
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
if (rs.next())
r2 = rs.getLong(1);
rs.close();
stmt.close();
return r2;
} catch (SQLException e) {
throw rethrow(e, sql);
} finally {
close(conn);
}
}
public int queryForInt(final String sql) throws SQLException {
Connection conn = conn_r();
try {
int r2 = 0;
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
if (rs.next())
r2 = rs.getInt(1);
rs.close();
stmt.close();
return r2;
} catch (SQLException e) {
throw rethrow(e, sql);
} finally {
close(conn);
}
}
public double queryForDouble(final String sql) throws SQLException {
Connection conn = conn_r();
try {
double r2 = 0;
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
if (rs.next())
r2 = rs.getDouble(1);
rs.close();
stmt.close();
return r2;
} catch (SQLException e) {
throw rethrow(e, sql);
} finally {
close(conn);
}
}
public final RowSet queryForRowSet(final String sql) throws SQLException {
return query(sql);
}
public int update(final String sql) throws SQLException {
Connection conn = conn_w();
try {
int r2 = 0;
PreparedStatement stmt = conn.prepareStatement(sql);
r2 = stmt.executeUpdate();
stmt.close();
return r2;
} catch (SQLException e) {
throw rethrow(e, sql);
} finally {
close(conn);
}
}
public int[] batchUpdate(final String as[]) throws SQLException {
Connection conn = conn_w();
try {
int r2[] = null;
Statement stmt = conn.createStatement();
for (String sql : as) {
stmt.addBatch(sql);
}
r2 = stmt.executeBatch();
stmt.close();
return r2;
} finally {
close(conn);
}
}
/***
* CallableStatement接口扩展 PreparedStatement,用来调用存储过程 <br/>
* 调用已储存过程的语法:{call 过程名[(?, ?, ...)]} <br/>
* 不带参数的已储存过程的语法:{call 过程名} 如sql = "call pro_rnkScore();"<br/>
* 带参数的已储存过程的语法:{call 过程名[(?, ?, ...)]} <br/>
* 例如ps_isa_ywxx_insert有4个参数,第四个是OUT出来INT的参数 <br/>
* ps = conn.prepareCall(" call ps_isa_ywxx_insert(?,?,?,?) ; "); <br/>
* ps.setString(1, ywbh); <br/>
* ps.setString(2, ywmc); <br/>
* ps.setString(3, ywbz); <br/>
* ps.registerOutParameter(4, Types.INTEGER) ; <br/>
* ps.execute() ; <br/>
* insertResult = ps.getInt(4); <br/>
* 返回结果参数的过程的语法:{? = call 过程名[(?, ?, ...)]}
* **/
public void call(final String sql, final Object... params)
throws SQLException {
Connection conn = conn_w();
try {
CallableStatement stmt = conn.prepareCall(sql);
if (params != null && params.length > 0) {
int lens = params.length;
for (int i = 0; i < lens; i++) {
int index = i + 1;
stmt.setObject(index, params[i]);
}
}
stmt.execute();
stmt.close();
} catch (SQLException e) {
throw rethrow(e, sql);
} finally {
close(conn);
}
}
public List<Map> queryByCall(final String sql) throws SQLException {
Connection conn = conn_w();
try {
List<Map> r2 = null;
CallableStatement stmt = conn.prepareCall(sql);
ResultSet rs = stmt.executeQuery();
r2 = toMaps(rs);
rs.close();
stmt.close();
return r2;
} catch (SQLException e) {
throw rethrow(e, sql);
} finally {
close(conn);
}
}
private static final PreparedStatement prepareMap(
final PreparedStatement stmt, final List<String> keys, final Map m)
throws SQLException {
int index = 0;
for (String key : keys) {
index++;
Object var = m.get(key);
stmt.setObject(index, var);
}
return stmt;
}
public static final String e2s(final Throwable e) {
return e2s(e, null, new Object[0]);
}
public static final String e2s(final Throwable e, final Object obj) {
return e2s(e, String.valueOf(obj), new Object[0]);
}
public static String e2s(final Throwable e, final String fmt,
final Object... args) {
return ExceptionEx.e2s(e, fmt, args);
}
// ///////////////////////////////////////////////////
public static final List<Map> toMaps(final ResultSet rs)
throws SQLException {
List<Map> result = new Vector();
while (rs.next()) {
Map m = toMap(rs);
result.add(m);
}
return result;
}
public static final <T> List<T> toKeys(final ResultSet rs)
throws SQLException {
List<T> result = new Vector();
while (rs.next()) {
Object o = rs.getObject(1);
result.add((T) o);
}
return result;
}
public static final Map toMap(final ResultSet rs) throws SQLException {
Map result = newMap();
ResultSetMetaData rsmd = rs.getMetaData();
int cols = rsmd.getColumnCount();
for (int i = 1; i <= cols; i++)
result.put(rsmd.getColumnName(i), rs.getObject(i));
return result;
}
public static final int pageCount(final int count, final int pageSize) {
return ListEx.pageCount(count, pageSize);
}
public static final List getPage(final List v, final int page,
final int pageSize) {
return ListEx.getPage(v, page, pageSize);
}
static public final int getInt(Map map, Object key) {
return MapEx.getInt(map, key);
}
static public final long getLong(Map map, Object key) {
return MapEx.getLong(map, key);
}
static public final <T> List<T> newList() {
return ListEx.newListT();
}
static public final Map newMap() {
return MapEx.newMap();
}
public void truncate(final String TABLENAME2) throws SQLException {
String sql = "TRUNCATE TABLE `" + TABLENAME2 + "`";
this.update(sql);
}
public void repair(final String TABLENAME2) throws SQLException {
String sql = "REPAIR TABLE `" + TABLENAME2 + "`";
this.update(sql);
}
public void optimize(final String TABLENAME2) throws SQLException {
String sql = "OPTIMIZE TABLE `" + TABLENAME2 + "`";
this.update(sql);
}
public void dropTable(final String TABLENAME2) throws SQLException {
String sql = "DROP TABLE IF EXISTS `" + TABLENAME2 + "`";
this.update(sql);
}
// //////////////////////////////////////////////////////////
// static ScheduledExecutorService _executor = null;
//
// public static void setExecutor(ScheduledExecutorService ses) {
// _executor = ses;
// }
//
// protected static ScheduledExecutorService executor() {
// if (_executor == null)
// _executor = Executors.newScheduledThreadPool(8,
// new MyThreadFactory("JdbcTemplate", false));
// return _executor;
// }
// //////////////////////////////////////////////////////////
ScheduledExecutorService _single_executor = null;
public void setSingleExecutor(ScheduledExecutorService ses) {
this._single_executor = ses;
}
protected synchronized ScheduledExecutorService executor(final String name) {
if (_single_executor == null)
_single_executor = Executors
.newSingleThreadScheduledExecutor(new MyThreadFactory(name,
false));
return _single_executor;
}
// //////////////////////////////////////////////////////////
public boolean exist_r(String TABLENAME2) {
boolean ret = false;
Connection conn = null;
try {
String catalog = catalog_r();
NewSet<String> tables = TABLES.get(catalog);
if (tables != null) {
if (tables.contains(TABLENAME2))
return true;
} else {
tables = new NewSet<String>();
TABLES.put(catalog, tables);
}
conn = conn_r();
List<Map> maps = SqlEx.getTables(conn);
for (Map map : maps) {
String str = MapEx.getString(map, "TABLE_NAME");
if (tables.contains(str))
continue;
tables.Add(str);
ret = ret || (str.equals(TABLENAME2));
}
} catch (Exception e) {
ret = false;
} finally {
closeNoExcept(conn);
}
return ret;
}
public boolean exist_w(String TABLENAME2) {
boolean ret = false;
Connection conn = null;
try {
String catalog = catalog_w();
NewSet<String> tables = TABLES.get(catalog);
if (tables != null) {
if (tables.contains(TABLENAME2))
return true;
} else {
tables = new NewSet<String>();
TABLES.put(catalog, tables);
}
conn = conn_w();
List<Map> maps = SqlEx.getTables(conn);
for (Map map : maps) {
String str = MapEx.getString(map, "TABLE_NAME");
if (tables.contains(str))
continue;
tables.Add(str);
ret = ret || (str.equals(TABLENAME2));
}
} catch (Exception e) {
ret = false;
} finally {
closeNoExcept(conn);
}
return ret;
}
protected SQLException rethrow(SQLException cause, String sql)
throws SQLException {
String causeMessage = cause.getMessage();
if (causeMessage == null) {
causeMessage = "";
}
StringBuffer msg = new StringBuffer(causeMessage);
msg.append("\r\n");
msg.append(" Query: ");
msg.append("\r\n");
msg.append(sql);
msg.append("\r\n");
SQLException e = new SQLException(msg.toString(), cause.getSQLState(),
cause.getErrorCode());
e.setNextException(cause);
return e;
}
public static SQLException rethrow(SQLException cause, String sql,
Object... params) {
String causeMessage = cause.getMessage();
if (causeMessage == null) {
causeMessage = "";
}
StringBuffer msg = new StringBuffer(causeMessage);
msg.append("\r\n");
msg.append(" Query: ");
msg.append("\r\n");
msg.append(sql);
msg.append("\r\n");
msg.append(" Parameters: ");
msg.append("\r\n");
if (params == null) {
msg.append("[]");
} else {
msg.append(Arrays.deepToString(params));
}
msg.append("\r\n");
SQLException e = new SQLException(msg.toString(), cause.getSQLState(),
cause.getErrorCode());
e.setNextException(cause);
return e;
}
protected SQLException rethrow(SQLException cause, String sql, Map params)
throws SQLException {
String causeMessage = cause.getMessage();
if (causeMessage == null) {
causeMessage = "";
}
StringBuffer msg = new StringBuffer(causeMessage);
msg.append("\r\n");
msg.append(" Query: ");
msg.append("\r\n");
msg.append(sql);
msg.append("\r\n");
msg.append(" Parameters: ");
msg.append("\r\n");
if (params == null) {
msg.append("{}");
} else {
msg.append(FastJSON.prettyFormat(params));
// msg.append(JSON.toJSONStringNotExcept(params));
}
msg.append("\r\n");
SQLException e = new SQLException(msg.toString(), cause.getSQLState(),
cause.getErrorCode());
e.setNextException(cause);
return e;
}
protected SQLException rethrow(SQLException cause, String sql, List params)
throws SQLException {
String causeMessage = cause.getMessage();
if (causeMessage == null) {
causeMessage = "";
}
StringBuffer msg = new StringBuffer(causeMessage);
msg.append("\r\n");
msg.append(" Query: ");
msg.append("\r\n");
msg.append(sql);
msg.append("\r\n");
msg.append(" Parameters: ");
msg.append("\r\n");
if (params == null) {
msg.append("[]");
} else {
msg.append(FastJSON.prettyFormat(params));
// msg.append(JSON.toJSONStringNotExcept(params));
}
msg.append("\r\n");
SQLException e = new SQLException(msg.toString(), cause.getSQLState(),
cause.getErrorCode());
e.setNextException(cause);
return e;
}
public static void main(String[] args) throws Exception {
// DataSource ds = Dbcp.newMysql("fych").dataSource();
// JdbcTemplate jt = new JdbcTemplate(ds);
// String TABLENAME2 = "Copyright";
// String sql =
// "INSERT INTO Copyright (name, version) VALUES (:name, :version)";
// Copyright c = Copyright.newCopyright(0L, "name -- 0", "version");
// ResultSet rs = jt.insert(sql, c);
// System.out.println(SqlEx.toMaps(rs));
// String sql = "SELECT id, name, version FROM " + TABLENAME2
// + " WHERE id = :id";
//
// Copyright x = Copyright.newCopyright(200L, "name -- 0", "version");
// Copyright c2 = jt.queryForObject(sql, x,
// new ResultSetHandler<Copyright>() {
// public Copyright handle(ResultSet rs) throws SQLException {
// Map e = SqlEx.toMap(rs);
// return Copyright.mapTo(e);
// }
// });
// System.out.println(c2);
}
}
|
package programmers.lv2;
import java.util.Stack;
public class Parenthesis_Test {
//올바른 괄호
//스택을 이용해서 풀었지만 다른 풀이를 보니 스택을 풀지 않고 해결했다.
//생각해보니 스택을 이용하지 않아도 충분히 해결 가능한 문제.
boolean solution(String s) {
char[] cArr = s.toCharArray();
Stack<Character> stack = new Stack<>();
boolean check = true;
for(int i=0; i<cArr.length; i++) {
if(stack.isEmpty()) {
if(cArr[i] == '(') {
stack.add(cArr[i]);
}else {
check = false;
break;
}
}else {
if(cArr[i] == ')') {
stack.pop();
}else {
stack.add(cArr[i]);
}
}
}
if(check && stack.size() == 0) {
check = true;
}else {
check = false;
}
return check;
}
boolean anotherSolution(String s) {
boolean answer = false;
int count = 0;
for(int i = 0; i<s.length();i++){
if(s.charAt(i) == '('){
count++;
}
if(s.charAt(i) == ')'){
count--;
}
if(count < 0){
break;
}
}
if(count == 0){
answer = true;
}
return answer;
}
}
|
package com.qingjiezhao.dao.impl;
import java.util.Calendar;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import com.qingjiezhao.bean.LocationBean;
import com.qingjiezhao.dao.LocationDao;
/**
* @author qingjiezhao
*
*/
public class LocationDaoImpl implements LocationDao {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
/*
* (non-Javadoc)
*
* @see com.qingjiezhao.dao.UserDao#findAll()
*/
@SuppressWarnings("unchecked")
@Override
public List<LocationBean> findAll() {
String hql = "FROM LocationBean";
Query query = this.sessionFactory.getCurrentSession().createQuery(hql);
if (null != query) {
return query.list();
}
return null;
}
public LocationBean findLocationById(int id) {
String hql = "FROM LocationBean WHERE id =:param1";
Query query = this.sessionFactory.getCurrentSession().createQuery(hql);
query.setParameter("param1", id);
if (null != query) {
List list = query.list();
LocationBean locationBean = (LocationBean) list.get(0);
return locationBean;
}
return null;
}
/*
* (non-Javadoc)
*
* @see com.qingjiezhao.dao.LocationDao#findLocationById(int)
*/
public LocationBean findLocationBeanByEmotion_selected(
String emotion_selected) {
String hql = "FROM LocationBean WHERE emotion_selected =:param1";
Query query = this.sessionFactory.getCurrentSession().createQuery(hql);
query.setParameter("param1", emotion_selected);
if (null != query) {
List list = query.list();
LocationBean locationBean = (LocationBean) list.get(0);
return locationBean;
}
return null;
}
/*
* (non-Javadoc)
*
* @see com.qingjiezhao.dao.UserDao#save(com.qingjiezhao.bean.UserBean)
*/
@Override
public void save(LocationBean locationBean) {
this.sessionFactory.getCurrentSession().save(locationBean);
}
public List<LocationBean> findLocationBeanListByDay() {
Calendar cal = Calendar.getInstance();
int day = cal.get(Calendar.DATE);
String hql = "FROM LocationBean WHERE day(currentTime) =:param1";
Query query = this.sessionFactory.getCurrentSession().createQuery(hql);
query.setParameter("param1", day);
//query.setParameter("param1", 21);
if (null != query) {
return query.list();
}
return null;
}
}
|
class Test {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println("第一次调用方法之前");
int ret = add(a, b);
System.out.println("第一次调用方法之后");
System.out.println("ret = " + ret);
System.out.println("第二次调用方法之前");
ret = add(30, 50);
System.out.println("第二次调用方法之后");
System.out.println("ret = " + ret);
}
public static int add(int x, int y) {
System.out.println("调用方法中 x = " + x + " y = " + y);
return x + y;
}
}
|
package com.bowlong.third.redis;
import java.util.ArrayList;
import java.util.List;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.SortingParams;
import com.bowlong.lang.StrEx;
import com.bowlong.util.ListEx;
/**
* jedis -- 主要操作 <br/>
* T-List -- Key - Val(list 元素); <br/>
* T-Hash -- Key - Filed - Val 值
*
* @author Canyon
*/
public class JedisNormal extends JedisBase {
private static final long serialVersionUID = 1L;
// ///////////////////// Type:Redis's_List的操作 /////////////////////
// 常用操作
// ///////////////////// ===================== /////////////////////
// ///////////////////// 取得长度 /////////////////////
static public final Long llen(final JedisPool pool, final String key)
throws Exception {
final Jedis jedis = getJedis(pool);
try {
return llen(jedis, key);
} catch (Exception e) {
throw e;
} finally {
returnJedis(pool, jedis);
}
}
static public final Long llen(final Jedis jedis, final String key) {
return jedis.llen(key);
}
static public final Long llen(final Jedis jedis, final byte[] key) {
return jedis.llen(key);
}
static public final Long llen(final String key) throws Exception {
final JedisPool pool = getJedisPool();
return llen(pool, key);
}
// ////////// 取得区间在[start,end]的值,包含start与end //////////
static public final List<String> lrange(final JedisPool pool,
final String key, final long start, final long end)
throws Exception {
final Jedis jedis = getJedis(pool);
try {
return lrange(jedis, key, start, end);
} catch (Exception e) {
throw e;
} finally {
returnJedis(pool, jedis);
}
}
static public final List<String> lrange(final Jedis jedis,
final String key, final long start, final long end) {
return jedis.lrange(key, start, end);
}
static public final List<byte[]> lrange(final Jedis jedis,
final byte[] key, final long start, final long end) {
return jedis.lrange(key, start, end);
}
static public final List<String> lrange(final String key, final long start,
final long end) throws Exception {
final JedisPool pool = getJedisPool();
return lrange(pool, key, start, end);
}
// ////////// ltrim[保留(retain) start(包含),end(包含)之间的值] 成功_返回:ok //////////
static public final String ltrim(final JedisPool pool, final String key,
final long start, final long end) throws Exception {
final Jedis jedis = getJedis(pool);
try {
return ltrim(jedis, key, start, end);
} catch (Exception e) {
throw e;
} finally {
returnJedis(pool, jedis);
}
}
static public final String ltrim(final Jedis jedis, final String key,
final long start, final long end) {
return jedis.ltrim(key, start, end);
}
static public final String ltrim(final Jedis jedis, final byte[] key,
final long start, final long end) {
return jedis.ltrim(key, start, end);
}
static public final String ltrim(final String key, final long start,
final long end) throws Exception {
final JedisPool pool = getJedisPool();
return ltrim(pool, key, start, end);
}
// ////////// 取得 Redis_List对象的所有值 //////////
static public final List<String> getAllList4TList(final JedisPool pool,
final String key) throws Exception {
final Jedis jedis = getJedis(pool);
try {
return getAllList4TList(jedis, key);
} catch (Exception e) {
throw e;
} finally {
returnJedis(pool, jedis);
}
}
static public final List<String> getAllList4TList(final Jedis jedis,
final String key) {
final long end = llen(jedis, key);
return jedis.lrange(key, 0, end);
}
static public final List<byte[]> getAllList4TList(final Jedis jedis,
final byte[] key) {
final long end = llen(jedis, key);
return jedis.lrange(key, 0, end);
}
static public final List<String> getAllList4TList2(final Jedis jedis,
final String key) {
return jedis.lrange(key, 0, -1);
}
static public final List<byte[]> getAllList4TList2(final Jedis jedis,
final byte[] key) {
return jedis.lrange(key, 0, -1);
}
static public final List<String> getAllList4TList(final String key)
throws Exception {
final JedisPool pool = getJedisPool();
return getAllList4TList(pool, key);
}
// ////////// list中删除count个值为val,返回:被移除元素的数量 //////////
/**
* count > 0 : 从表头开始向表尾搜索,移除与 value 相等的元素,数量为 count 。 <br/>
* count < 0 : 从表尾开始向表头搜索,移除与 value 相等的元素,数量为 count 的绝对值。<br/>
* count = 0 : 移除表中所有与 value 相等的值。<br/>
*/
static public final Long lrem(final JedisPool pool, final String key,
final long count, final String val) throws Exception {
final Jedis jedis = getJedis(pool);
try {
return lrem(jedis, key, count, val);
} catch (Exception e) {
throw e;
} finally {
returnJedis(pool, jedis);
}
}
static public final Long lrem(final Jedis jedis, final String key,
final long count, final String val) {
return jedis.lrem(key, count, val);
}
static public final Long lrem(final Jedis jedis, final byte[] key,
final long count, final byte[] val) {
return jedis.lrem(key, count, val);
}
static public final Long lrem(final String key, final long count,
final String val) throws Exception {
final JedisPool pool = getJedisPool();
return lrem(pool, key, count, val);
}
static public final Long remvoeAllVal4TList(final JedisPool pool,
final String key, final String val) throws Exception {
final Jedis jedis = getJedis(pool);
try {
return remvoeAllVal4TList(jedis, key, val);
} catch (Exception e) {
throw e;
} finally {
returnJedis(pool, jedis);
}
}
static public final Long remvoeAllVal4TList(final Jedis jedis,
final String key, final String val) {
return jedis.lrem(key, 0, val);
}
static public final Long remvoeAllVal4TList(final Jedis jedis,
final byte[] key, final byte[] val) {
return jedis.lrem(key, 0, val);
}
static public final Long remvoeAllVal4TList(final String key,
final String val) throws Exception {
final JedisPool pool = getJedisPool();
return remvoeAllVal4TList(pool, key, val);
}
// ////////// 取得下标为index一个值 不成功_返回:nil //////////
static public final String lindex(final JedisPool pool, final String key,
final long index) throws Exception {
final Jedis jedis = getJedis(pool);
try {
return lindex(jedis, key, index);
} catch (Exception e) {
throw e;
} finally {
returnJedis(pool, jedis);
}
}
static public final String lindex(final Jedis jedis, final String key,
final long index) {
return jedis.lindex(key, index);
}
static public final byte[] lindex(final Jedis jedis, final byte[] key,
final long index) {
return jedis.lindex(key, index);
}
static public final String lindex(final String key, final long index)
throws Exception {
final JedisPool pool = getJedisPool();
return lindex(pool, key, index);
}
// ////////// 设置下标为index一个值 ,成功_返回:ok //////////
static public final String lset(final JedisPool pool, final String key,
final long index, final String val) throws Exception {
final Jedis jedis = getJedis(pool);
try {
return lset(jedis, key, index, val);
} catch (Exception e) {
throw e;
} finally {
returnJedis(pool, jedis);
}
}
static public final String lset(final Jedis jedis, final String key,
final long index, final String val) {
return jedis.lset(key, index, val);
}
static public final String lset(final Jedis jedis, final byte[] key,
final long index, final byte[] val) {
return jedis.lset(key, index, val);
}
static public final String lset(final String key, final long index,
final String val) throws Exception {
final JedisPool pool = getJedisPool();
return lset(pool, key, index, val);
}
// ////////// rpush 将元素插入尾部 先进先出[返回:表的长度] //////////
static public final Long rpush(final JedisPool pool, final String key,
final String... val) throws Exception {
final Jedis jedis = getJedis(pool);
try {
return rpush(jedis, key, val);
} catch (Exception e) {
throw e;
} finally {
returnJedis(pool, jedis);
}
}
static public final Long rpush(final Jedis jedis, final String key,
final String... val) {
return jedis.rpush(key, val);
}
static public final Long rpush(final Jedis jedis, final byte[] key,
final byte[]... val) {
return jedis.rpush(key, val);
}
static public final Long rpush(final String key, final String... val)
throws Exception {
final JedisPool pool = getJedisPool();
return rpush(pool, key, val);
}
static public final Long rpush(final JedisPool pool, final String key,
final List<String> vals) throws Exception {
final Jedis jedis = getJedis(pool);
try {
return rpush(jedis, key, vals);
} catch (Exception e) {
throw e;
} finally {
returnJedis(pool, jedis);
}
}
static public final Long rpush(final Jedis jedis, final String key,
final List<String> vals) {
if (jedis == null || ListEx.isEmpty(vals))
return llen(jedis, key);
String[] val = {};
val = vals.toArray(val);
return jedis.rpush(key, val);
}
// ////////// lpush 将元素插入头部 先进后出[返回:表的长度] //////////
static public final Long lpush(final JedisPool pool, final String key,
final String... val) throws Exception {
final Jedis jedis = getJedis(pool);
try {
return lpush(jedis, key, val);
} catch (Exception e) {
throw e;
} finally {
returnJedis(pool, jedis);
}
}
static public final Long lpush(final Jedis jedis, final String key,
final String... val) {
return jedis.lpush(key, val);
}
static public final Long lpush(final JedisPool pool, final byte[] key,
final byte[]... val) throws Exception {
final Jedis jedis = getJedis(pool);
try {
return lpush(jedis, key, val);
} catch (Exception e) {
throw e;
} finally {
returnJedis(pool, jedis);
}
}
static public final Long lpush(final Jedis jedis, final byte[] key,
final byte[]... val) {
return jedis.lpush(key, val);
}
static public final Long lpush(final String key, final String... val)
throws Exception {
final JedisPool pool = getJedisPool();
return lpush(pool, key, val);
}
static public final Long lpush(final JedisPool pool, final String key,
final List<String> vals) throws Exception {
final Jedis jedis = getJedis(pool);
try {
return lpush(jedis, key, vals);
} catch (Exception e) {
throw e;
} finally {
returnJedis(pool, jedis);
}
}
static public final Long lpush(final Jedis jedis, final String key,
final List<String> vals) {
if (jedis == null || ListEx.isEmpty(vals))
return llen(jedis, key);
String[] val = {};
val = vals.toArray(val);
return jedis.lpush(key, val);
}
static public final Long lpush(final Jedis jedis, final byte[] key,
final List<byte[]> vals) {
if (jedis == null || ListEx.isEmpty(vals))
return llen(jedis, key);
byte[][] val = {};
val = vals.toArray(val);
return jedis.lpush(key, val);
}
// ////////// 取得 SortingParams 筛选排序值 //////////
static public final List<String> getListSort4TList(final JedisPool pool,
final String key, final SortingParams sop) throws Exception {
final Jedis jedis = getJedis(pool);
try {
return getListSort4TList(jedis, key, sop);
} catch (Exception e) {
throw e;
} finally {
returnJedis(pool, jedis);
}
}
static public final List<String> getListSort4TList(final Jedis jedis,
final String key, final SortingParams sop) {
return jedis.sort(key, sop);
}
static public final List<String> getListSort4TList(final String key,
final SortingParams sop) throws Exception {
final JedisPool pool = getJedisPool();
return getListSort4TList(pool, key, sop);
}
// ////////// 取得 这个值在list里面的所有Index位置 //////////
static public final List<Long> getIndexs4TList(final JedisPool pool,
final String key, final String val) throws Exception {
final Jedis jedis = getJedis(pool);
try {
return getIndexs4TList(jedis, key, val);
} catch (Exception e) {
throw e;
} finally {
returnJedis(pool, jedis);
}
}
static public final List<Long> getIndexs4TList(final Jedis jedis,
final String key, final String val) {
List<Long> ret = new ArrayList<Long>();
List<String> all = getAllList4TList(jedis, key);
if (ListEx.isEmpty(all))
return ret;
int lens = all.size();
for (int i = 0; i < lens; i++) {
String v = all.get(i);
if (StrEx.isSame(val, v)) {
ret.add((long) i);
}
}
return ret;
}
static public final List<Long> getIndexs4TList(final String key,
final String val) throws Exception {
final JedisPool pool = getJedisPool();
return getIndexs4TList(pool, key, val);
}
// ///////////////////// Type:Redis's_HashMap的操作 /////////////////////
// 常用操作
// ///////////////////// ===================== /////////////////////
// ///////////////////// 取得长度 /////////////////////
static public final Long hlen(final JedisPool pool, final String key)
throws Exception {
final Jedis jedis = getJedis(pool);
try {
return hlen(jedis, key);
} catch (Exception e) {
throw e;
} finally {
returnJedis(pool, jedis);
}
}
static public final Long hlen(final Jedis jedis, final String key) {
return jedis.hlen(key);
}
static public final Long hlen(final Jedis jedis, final byte[] key) {
return jedis.hlen(key);
}
static public final Long hlen(final String key) throws Exception {
final JedisPool pool = getJedisPool();
return hlen(pool, key);
}
// ///////////////////// 是否存在 /////////////////////
static public final boolean hexists(final JedisPool pool, final String key,
final String filed) throws Exception {
final Jedis jedis = getJedis(pool);
try {
return hexists(jedis, key, filed);
} catch (Exception e) {
throw e;
} finally {
returnJedis(pool, jedis);
}
}
static public final boolean hexists(final Jedis jedis, final String key,
final String filed) {
return jedis.hexists(key, filed);
}
static public final boolean hexists(final Jedis jedis, final byte[] key,
final byte[] filed) {
return jedis.hexists(key, filed);
}
static public final boolean hexists(final String key, final String filed)
throws Exception {
final JedisPool pool = getJedisPool();
return hexists(pool, key, filed);
}
// ///////////////////// 取得val根据k_f /////////////////////
static public final String hget(final JedisPool pool, final String key,
final String filed) throws Exception {
final Jedis jedis = getJedis(pool);
try {
return hget(jedis, key, filed);
} catch (Exception e) {
throw e;
} finally {
returnJedis(pool, jedis);
}
}
static public final String hget(final Jedis jedis, final String key,
final String filed) {
return jedis.hget(key, filed);
}
static public final byte[] hget(final Jedis jedis, final byte[] key,
final byte[] filed) {
return jedis.hget(key, filed);
}
static public final String hget(final String key, final String filed)
throws Exception {
final JedisPool pool = getJedisPool();
return hget(pool, key, filed);
}
// ///////////////////// 删除k_fields /////////////////////
static public final Long hdel(final JedisPool pool, final String key,
final String... filed) throws Exception {
final Jedis jedis = getJedis(pool);
try {
return hdel(jedis, key, filed);
} catch (Exception e) {
throw e;
} finally {
returnJedis(pool, jedis);
}
}
static public final Long hdel(final Jedis jedis, final String key,
final String... filed) {
return jedis.hdel(key, filed);
}
static public final Long hdel(final Jedis jedis, final byte[] key,
final byte[]... filed) {
return jedis.hdel(key, filed);
}
static public final Long hdel(final String key, final String... filed)
throws Exception {
final JedisPool pool = getJedisPool();
return hdel(pool, key, filed);
}
static public final Long hdel(final JedisPool pool, final String key,
final List<String> filed) throws Exception {
final Jedis jedis = getJedis(pool);
try {
return hdel(jedis, key, filed);
} catch (Exception e) {
throw e;
} finally {
returnJedis(pool, jedis);
}
}
static public final Long hdel(final Jedis jedis, final String key,
final List<String> filed) {
String[] fileds = {};
fileds = filed.toArray(fileds);
return hdel(jedis, key, fileds);
}
// /////////////////////
// /////////////////////
}
|
package com.snab.tachkit.allForm.formOptions;
import com.snab.tachkit.additional.ParamOfField;
import android.content.Context;
import android.text.InputType;
import com.snab.tachkit.R;
import com.snab.tachkit.globalOptions.fieldOptions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
/**
* Created by Таня on 04.02.2015.
* Генерация полей для поиска по категорям
*/
public abstract class FormSearchOptions extends FormOptions{
public FormSearchOptions(Context context, int typeAdvert) {
super(context, typeAdvert);
}
public ParamOfField cost(){
ParamOfField cost = new ParamOfField(fieldOptions.PICKER_DIALOG, getString(R.string.cost) + " (тыс. руб.)", "cost");
cost.setSubTitleNoResult(getString(R.string.select_options_between));
cost.setVariable(new ArrayList(Arrays.asList(new ParamOfField.VariableStructure[]{new ParamOfField.VariableStructure(10, ""), new ParamOfField.VariableStructure(10000, ""), new ParamOfField.VariableStructure(10, "")})));
return cost;
}
public ParamOfField year(){
ParamOfField year = new ParamOfField(fieldOptions.PICKER_DIALOG, getString(R.string.year), "year");
year.setSubTitleNoResult(getString(R.string.select_options_between));
year.setVariable(new ArrayList(Arrays.asList(new ParamOfField.VariableStructure[]{new ParamOfField.VariableStructure(1930, ""), new ParamOfField.VariableStructure(Calendar.getInstance().get(Calendar.YEAR), "")})));
return year;
}
public ParamOfField own_weight() {
ParamOfField own_weight = new ParamOfField(fieldOptions.TWO_INPUT_INLINE, getString(R.string.own_weight), getString(R.string.from), getString(R.string.to), "own_weight");
own_weight.setInputType(InputType.TYPE_CLASS_NUMBER);
own_weight.setInputTypeTwo(InputType.TYPE_CLASS_NUMBER);
return own_weight;
}
public ParamOfField seat_height() {
ParamOfField seat_height = new ParamOfField(fieldOptions.TWO_INPUT_INLINE, getString(R.string.seat_height), getString(R.string.from), getString(R.string.to), "height");
seat_height.setInputType(InputType.TYPE_CLASS_NUMBER);
seat_height.setInputTypeTwo(InputType.TYPE_CLASS_NUMBER);
return seat_height;
}
public ParamOfField seat_count() {
ParamOfField seat_count = new ParamOfField(fieldOptions.TWO_INPUT_INLINE, getString(R.string.seat_count), getString(R.string.from), getString(R.string.to), "count_seats");
seat_count.setInputType(InputType.TYPE_CLASS_NUMBER);
seat_count.setInputTypeTwo(InputType.TYPE_CLASS_NUMBER);
return seat_count;
}
public ParamOfField engine_volume() {
ParamOfField seat_count = new ParamOfField(fieldOptions.TWO_INPUT_INLINE, getString(R.string.engine_volume), getString(R.string.from), getString(R.string.to), "volume");
seat_count.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
seat_count.setInputTypeTwo(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
return seat_count;
}
public ParamOfField engine_power() {
ParamOfField engine_power = new ParamOfField(fieldOptions.TWO_INPUT_INLINE, getString(R.string.engine_power), getString(R.string.from), getString(R.string.to), "power");
engine_power.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
engine_power.setInputTypeTwo(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
return engine_power;
}
public ParamOfField capacity() {
ParamOfField capacity = new ParamOfField(fieldOptions.TWO_INPUT_INLINE, getString(R.string.capacity), getString(R.string.from), getString(R.string.to), "capacity");
capacity.setInputType(InputType.TYPE_CLASS_NUMBER);
capacity.setInputTypeTwo(InputType.TYPE_CLASS_NUMBER);
return capacity;
}
public ParamOfField whole_mass() {
ParamOfField whole_mass = new ParamOfField(fieldOptions.TWO_INPUT_INLINE, getString(R.string.whole_mass), getString(R.string.from), getString(R.string.to), "whole_mass");
whole_mass.setInputType(InputType.TYPE_CLASS_NUMBER);
whole_mass.setInputTypeTwo(InputType.TYPE_CLASS_NUMBER);
return whole_mass;
}
public ParamOfField motohours() {
ParamOfField motohours = new ParamOfField(fieldOptions.TWO_INPUT_INLINE, getString(R.string.motohours), getString(R.string.from), getString(R.string.to), "motohours");
motohours.setInputType(InputType.TYPE_CLASS_NUMBER);
motohours.setInputTypeTwo(InputType.TYPE_CLASS_NUMBER);
return motohours;
}
public ParamOfField costEnter(){
ParamOfField cost = new ParamOfField(fieldOptions.TWO_INPUT_INLINE, getString(R.string.cost), getString(R.string.from), getString(R.string.to), "cost");
cost.setSubTitleNoResult(getString(R.string.select_options_between));
cost.setInputType(InputType.TYPE_CLASS_NUMBER);
cost.setInputTypeTwo(InputType.TYPE_CLASS_NUMBER);
return cost;
}
}
|
/**
* Copyright (c) 2000-present Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.onboarding.form.web.portlet.action;
import com.liferay.form.onboarding.constants.OnboardingFormPortletKeys;
import com.liferay.form.onboarding.exception.OBFormEntryFormException;
import com.liferay.form.onboarding.exception.OBFormEntryNameException;
import com.liferay.form.onboarding.model.OBFormEntry;
import com.liferay.form.onboarding.model.OBFormFieldMapping;
import com.liferay.form.onboarding.service.OBFormEntryService;
import com.liferay.form.onboarding.service.OBFormFieldMappingLocalService;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.portlet.LiferayPortletURL;
import com.liferay.portal.kernel.portlet.PortletURLFactoryUtil;
import com.liferay.portal.kernel.portlet.bridges.mvc.BaseMVCActionCommand;
import com.liferay.portal.kernel.portlet.bridges.mvc.MVCActionCommand;
import com.liferay.portal.kernel.service.ServiceContext;
import com.liferay.portal.kernel.service.ServiceContextFactory;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.Constants;
import com.liferay.portal.kernel.util.JavaConstants;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.Validator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.portlet.PortletRequest;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
/**
* @author Evan Thibodeau
*/
@Component(
immediate = true,
property = {
"javax.portlet.name=" + OnboardingFormPortletKeys.ONBOARDING_FORM,
"mvc.command.name=editEntry"
},
service = MVCActionCommand.class
)
public class EditEntryMVCActionCommand extends BaseMVCActionCommand {
@Override
protected void doProcessAction(
ActionRequest actionRequest, ActionResponse actionResponse)
throws Exception {
ServiceContext serviceContext = ServiceContextFactory.getInstance(
OBFormEntry.class.getName(), actionRequest);
try {
String name = ParamUtil.getString(actionRequest, "name");
if (Validator.isNull(name)) {
throw new OBFormEntryNameException(
"you-must-include-a-valid-name");
}
long obFormEntryId = ParamUtil.getLong(
actionRequest, "obFormEntryId");
long userId = serviceContext.getUserId();
if (obFormEntryId > 0) {
long[] organizationIds = ParamUtil.getLongValues(
actionRequest, "organizationIds");
long[] roleIds = ParamUtil.getLongValues(
actionRequest, "roleIds");
long[] siteIds = ParamUtil.getLongValues(
actionRequest, "siteIds");
long[] userGroupIds = ParamUtil.getLongValues(
actionRequest, "userGroupIds");
boolean sendEmail = ParamUtil.getBoolean(
actionRequest, "sendEmail");
boolean active = ParamUtil.getBoolean(actionRequest, "active");
_obFormEntryService.updateOBFormEntry(
userId, obFormEntryId, name, organizationIds, roleIds,
siteIds, userGroupIds, sendEmail, active, serviceContext);
String[] mappableFields = ParamUtil.getStringValues(
actionRequest, "mappableField");
String[] mappableFieldReferences = ParamUtil.getStringValues(
actionRequest, "mappableFieldReference");
_updateMappableFields(
obFormEntryId, mappableFields, mappableFieldReferences);
actionResponse.setRenderParameter(
"obFormEntryId", String.valueOf(obFormEntryId));
}
else {
long formId = ParamUtil.getLong(actionRequest, "formId");
if (formId <= 0) {
throw new OBFormEntryFormException(
"you-must-select-a-form");
}
OBFormEntry obFormEntry = _obFormEntryService.addOBFormEntry(
userId, name, formId, serviceContext);
_sendDraftRedirect(actionRequest, actionResponse, obFormEntry);
}
}
catch (Exception e) {
SessionErrors.add(actionRequest, e.getClass());
actionResponse.setRenderParameter(
"mvcRenderCommandName", "/onboarding_form/create_entry");
hideDefaultSuccessMessage(actionRequest);
}
}
private String _getEditRedirect(
ActionRequest actionRequest, OBFormEntry entry, String redirect)
throws Exception {
PortletConfig portletConfig = (PortletConfig)actionRequest.getAttribute(
JavaConstants.JAVAX_PORTLET_CONFIG);
LiferayPortletURL portletURL = PortletURLFactoryUtil.create(
actionRequest, portletConfig.getPortletName(),
PortletRequest.RENDER_PHASE);
portletURL.setParameter(
"mvcRenderCommandName", "/onboarding_form/edit_entry");
portletURL.setParameter(Constants.CMD, Constants.UPDATE, false);
portletURL.setParameter("redirect", redirect, false);
portletURL.setParameter(
"groupId", String.valueOf(entry.getGroupId()), false);
portletURL.setParameter(
"obFormEntryId", String.valueOf(entry.getObFormEntryId()), false);
portletURL.setWindowState(actionRequest.getWindowState());
return portletURL.toString();
}
private void _sendDraftRedirect(
ActionRequest actionRequest, ActionResponse actionResponse,
OBFormEntry entry)
throws Exception {
String redirect = ParamUtil.getString(actionRequest, "redirect");
sendRedirect(
actionRequest, actionResponse,
_getEditRedirect(actionRequest, entry, redirect));
}
private void _updateMappableFields(
long obFormEntryId, String[] mappableFields,
String[] mappableFieldReferences) {
Map<String, String> mappableFieldsMap = new HashMap<>();
for (int i = 0; i < mappableFields.length; i++) {
String mappableField = mappableFields[i];
String mappableFieldReference = mappableFieldReferences[i];
mappableFieldsMap.put(mappableFieldReference, mappableField);
}
List<OBFormFieldMapping> obFormFieldMappings =
_obFormFieldMappingLocalService.getOBFormFieldMappings(
obFormEntryId);
for (OBFormFieldMapping obFormFieldMapping : obFormFieldMappings) {
String formFieldReference =
obFormFieldMapping.getFormFieldReference();
if (mappableFieldsMap.containsKey(formFieldReference)) {
obFormFieldMapping.setUserPropertyName(
mappableFieldsMap.get(formFieldReference));
_obFormFieldMappingLocalService.updateOBFormFieldMapping(
obFormFieldMapping);
mappableFieldsMap.remove(formFieldReference);
}
else {
try {
_obFormFieldMappingLocalService.deleteOBFormFieldMapping(
obFormEntryId, formFieldReference);
}
catch (PortalException e) {
e.printStackTrace();
}
}
}
mappableFieldsMap.forEach(
(String formFieldReference, String userProperty) ->
_obFormFieldMappingLocalService.addOBFormFieldMapping(
obFormEntryId, formFieldReference, userProperty));
}
@Reference
private OBFormEntryService _obFormEntryService;
@Reference
private OBFormFieldMappingLocalService _obFormFieldMappingLocalService;
} |
package com.example.structural.facade;
/**
* Copyright (C), 2020
* FileName: FacadePatternDemo
*
* @author: xieyufeng
* @date: 2020/11/2 09:31
* @description:
*/
public class FacadePatternDemo {
public static void main(String[] args) {
ShapeMaker shapeMaker = new ShapeMaker();
shapeMaker.drawCircle();
shapeMaker.drawRectangle();
shapeMaker.drawSquare();
}
}
|
package com.tiandi.logistics.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tiandi.logistics.aop.log.annotation.ControllerLogAnnotation;
import com.tiandi.logistics.aop.log.enumeration.OpTypeEnum;
import com.tiandi.logistics.aop.log.enumeration.SysTypeEnum;
import com.tiandi.logistics.entity.pojo.Company;
import com.tiandi.logistics.entity.pojo.Role;
import com.tiandi.logistics.entity.pojo.User;
import com.tiandi.logistics.entity.front.AuthManageEntity;
import com.tiandi.logistics.entity.result.ResultMap;
import com.tiandi.logistics.service.CompanyService;
import com.tiandi.logistics.service.RoleService;
import com.tiandi.logistics.service.UserService;
import com.tiandi.logistics.utils.JWTUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
/**
* 用户管理模块实现
*
* @author Yue Wu
* @version 1.0
* @since 2020/12/2 8:33
*/
@RestController
@Api(tags = "用户管理")
@RequestMapping("/auth/manage")
public class AuthManagementController {
@Autowired
private UserService userService;
@Autowired
private ResultMap resultMap;
@Autowired
private RoleService roleService;
@Autowired
private CompanyService companyService;
/**
* 对用户进行删除/开除/离职进行处理
*
* @param token 凭证
* @param targetUsername 目标用户用户名
* @param note 操作原因备注
* @return
*/
@PostMapping("/deleteAtuh")
@ControllerLogAnnotation(remark = "对用户进行删除/开除/离职进行处理", sysType = SysTypeEnum.ADMIN, opType = OpTypeEnum.DELETE)
@ApiOperation(value = "对用户进行删除/开除/离职进行处理", notes = "该方法底层实现为逻辑删除")
@ApiImplicitParams({
@ApiImplicitParam(name = "targetUsername", value = "修改的目标用户用户名", required = true, paramType = "query"),
@ApiImplicitParam(name = "note", value = "移除用户的原因备注", required = true, paramType = "query"),
@ApiImplicitParam(name = "token", value = "凭证", required = true, paramType = "header")
})
@RequiresRoles(logical = Logical.OR, value = {"branchCompany", "headCompany", "admin", "distribution"})
@RequiresPermissions(logical = Logical.OR, value = {"admin", "normal", "root"})
public ResultMap deleteAuth(@RequestHeader String token, @RequestParam("targetUsername") String targetUsername,
@RequestParam("note") String note) {
boolean remove = userService.remove(new QueryWrapper<User>().eq("username", targetUsername));
if (remove) {
resultMap.success().message(JWTUtil.getUsername(token) + " 将该 " + targetUsername + " 用户进行了" + note + "处理");
} else {
resultMap.fail().message("修改失败!服务器内部错误");
}
return resultMap;
}
/**
* 进行工作权限委派
*
* @param token 凭证
* @param targetUsername 目标用户
* @param changeRole 修改权限
* @return
*/
@PostMapping("/changeAuthRole")
@ControllerLogAnnotation(remark = "用户权限委派", sysType = SysTypeEnum.ADMIN, opType = OpTypeEnum.UPDATE)
@ApiOperation(value = "进行工作权限委派", notes = "总公司对分公司管理员进行分配\n系统管理员对总公司管理员进行分配")
@ApiImplicitParams({
@ApiImplicitParam(name = "targetUsername", value = "修改的目标用户用户名", required = true, paramType = "query"),
@ApiImplicitParam(name = "changeRole", value = "修改的权限ID", required = true, paramType = "query"),
@ApiImplicitParam(name = "token", value = "凭证", required = true, paramType = "header")
})
@RequiresRoles(logical = Logical.OR, value = {"admin", "headCompany"})
@RequiresPermissions(logical = Logical.OR, value = {"admin", "normal", "root"})
public ResultMap changeAuthRole(@RequestHeader String token,
@RequestParam("targetUsername") String targetUsername,
@RequestParam("changeRole") String changeRole) {
boolean update = userService.update(new UpdateWrapper<User>().set("role", changeRole).eq("username", targetUsername));
if (update) {
resultMap.success().message(JWTUtil.getUsername(token) + " 将该 " + targetUsername + " 用户权限修改: " + changeRole);
} else {
resultMap.fail().message("修改失败!服务器内部错误");
}
return resultMap;
}
/**
* 获取所有的用户信息接口,为第三方数据库拉取数据/胡乱查询提供支持
*
* @param token 请求用户的凭证
* @param size 每页容量
* @param pageCurrent 页码
* @return
*/
@GetMapping("/getAllAuth/{size}/{pageCurrent}")
@ApiOperation(value = "获取所有的用户信息", notes = "拓展接口,项目中使用概率不高\n管理员层面接口,根据管理权限不同获取的用户的身份也不同")
@ApiImplicitParams({
@ApiImplicitParam(name = "size", value = "每一页的数据数量", required = true, paramType = "path"),
@ApiImplicitParam(name = "pageCurrent", value = "当前页码", required = true, paramType = "path"),
@ApiImplicitParam(name = "token", value = "凭证", required = true, paramType = "header")
})
@RequiresRoles("admin")
public ResultMap getAllAuth(@RequestHeader String token, @PathVariable String size,
@PathVariable String pageCurrent) {
String role = JWTUtil.getUserRole(token);
String permission = JWTUtil.getUserPermission(token);
Integer roleId = roleService.getOne(new QueryWrapper<Role>().select("id_tb_role").eq("role", role).eq("permission", permission)).getIdTbRole();
Page<AuthManageEntity> auth = null;
if ("root".equals(role)) {
auth = (Page<AuthManageEntity>) userService.getAllAuth(new Page<>(Long.parseLong(pageCurrent), Long.parseLong(size)), roleId);
} else {
auth = (Page<AuthManageEntity>) userService.getAllAuth(new Page<>(Long.parseLong(pageCurrent), Long.parseLong(size)), roleId, roleId + 1);
}
return resultMap.success().message("获取所有用户信息")
.addElement("total", auth.getTotal())
.addElement("userList", auth.getRecords())
.addElement("totalPageNumber", auth.getTotal() / Long.parseLong(size));
}
/**
* 获取所有消费者用户
*
* @param size 每页容量
* @param pageCurrent 当前页
* @return
*/
@GetMapping("/getAllConsumerAuth/{size}/{pageCurrent}")
@ApiOperation(value = "获取所有消费者用户", notes = "管理员端接口")
@ApiImplicitParams({
@ApiImplicitParam(name = "size", value = "每一页的数据数量", required = true, paramType = "path"),
@ApiImplicitParam(name = "pageCurrent", value = "当前页码", required = true, paramType = "path")
})
@RequiresRoles("admin")
public ResultMap getAllConsumerAuth(@PathVariable String size, @PathVariable String pageCurrent) {
Page<AuthManageEntity> consumerAuth = (Page<AuthManageEntity>) userService.getAllConsumerAuth(
new Page<AuthManageEntity>(Long.parseLong(pageCurrent), Long.parseLong(size)));
return resultMap.success().message("获取消费者用户成功")
.addElement("userList", consumerAuth.getRecords())
.addElement("total", consumerAuth.getTotal())
.addElement("totalPageNumber", consumerAuth.getTotal() / Long.parseLong(size));
}
/**
* 通过组织来获取其对应的所属用户(员工)
*
* @param organization 组织名
* @param size 页容量
* @param pageCurrent 页数
* @param delete 删除标志位: 0: 现存 1:删除
* @param token 凭证
* @return
*/
@GetMapping("/getAuthByOrganization/{organization}/{size}/{pageCurrent}/{delete}")
@ApiOperation(value = "通过组织获取用户", notes = "各个公司的管理员可以获取对应公司员工的接口\n系统管理员可以获取对应公司下的员工和管理员人员信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "token", value = "凭证", required = true, paramType = "header", dataType = "String"),
@ApiImplicitParam(name = "organization", value = "组织名称", required = true, paramType = "path", dataType = "String"),
@ApiImplicitParam(name = "size", value = "页面容量", required = true, paramType = "path", dataType = "String"),
@ApiImplicitParam(name = "pageCurrent", value = "当前页", required = true, paramType = "path", dataType = "String"),
@ApiImplicitParam(name = "delete", value = "是否是已经辞退的用户", required = true, paramType = "path", dataType = "String")
})
@RequiresRoles(logical = Logical.OR, value = {"branchCompany", "headCompany", "admin", "distribution"})
@RequiresPermissions(logical = Logical.OR, value = {"admin", "normal", "root"})
public ResultMap getAuthByOrganization(@RequestHeader String token, @PathVariable String organization,
@PathVariable String size, @PathVariable String pageCurrent,
@PathVariable String delete) {
List<Integer> roleId = new ArrayList<>();
String userRole = JWTUtil.getUserRole(token);
getRoleListTools(userRole, organization, roleId);
Page<AuthManageEntity> auth = (Page<AuthManageEntity>) userService.getAuthByOrganization(
new Page<>(Long.parseLong(pageCurrent), Long.parseLong(size)), organization, roleId, delete);
return resultMap.success().message("获取某个组织所有用户信息")
.addElement("total", auth.getTotal())
.addElement("userList", auth.getRecords())
.addElement("totalPageNumber", auth.getTotal() / Long.parseLong(size));
}
/**
* 通过组织来获取其对应的所属用户(员工)
*
* @param organization 组织名
* @param size 页容量
* @param pageCurrent 页数
* @param delete 删除标志位: 0: 现存 1:删除
* @param token 凭证
* @return
*/
@GetMapping("/getAuthByOrganizationStandBy/{organization}/{size}/{pageCurrent}/{ban}/{delete}")
@ApiOperation(value = "通过组织获取用户", notes = "各个公司的管理员可以获取对应公司员工的接口\n系统管理员可以获取对应公司下的员工和管理员人员信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "token", value = "凭证", required = true, paramType = "header", dataType = "String"),
@ApiImplicitParam(name = "organization", value = "组织名称", required = true, paramType = "path", dataType = "String"),
@ApiImplicitParam(name = "size", value = "页面容量", required = true, paramType = "path", dataType = "String"),
@ApiImplicitParam(name = "pageCurrent", value = "当前页", required = true, paramType = "path", dataType = "String"),
@ApiImplicitParam(name = "delete", value = "是否是已经辞退的用户", required = true, paramType = "path", dataType = "String")
})
@RequiresRoles(logical = Logical.OR, value = {"branchCompany", "headCompany", "admin", "distribution"})
@RequiresPermissions(logical = Logical.OR, value = {"admin", "normal", "root"})
public ResultMap getAuthByOrganizationStandBy(@RequestHeader String token, @PathVariable String organization,
@PathVariable String size, @PathVariable String pageCurrent,
@PathVariable String delete, @PathVariable String ban) {
List<Integer> roleId = new ArrayList<>();
String userRole = JWTUtil.getUserRole(token);
getRoleListTools(userRole, organization, roleId);
Page<AuthManageEntity> auth = (Page<AuthManageEntity>) userService.getAuthByOrganization(
new Page<>(Long.parseLong(pageCurrent), Long.parseLong(size)), organization, roleId, delete, ban);
return resultMap.success().message("获取某个组织所有用户信息")
.addElement("total", auth.getTotal())
.addElement("userList", auth.getRecords())
.addElement("totalPageNumber", auth.getTotal() / Long.parseLong(size));
}
/**
* 通过组织来获取其对应的所属用户(员工)
* 同时增加过滤筛选条件
*
* @param organization 组织名
* @param type 用户的身份类别
* @param size 页容量
* @param pageCurrent 页数
* @param delete 删除标志 0:现存 1:删除
* @param token 凭证
* @return
*/
@GetMapping("/getAuthByOrganization/{organization}/{size}/{pageCurrent}/{type}/{delete}")
@ApiOperation(value = "通过组织获取对应分类用户")
@ApiImplicitParams({
@ApiImplicitParam(name = "token", value = "凭证", required = true, paramType = "header", dataType = "String"),
@ApiImplicitParam(name = "organization", value = "组织名称", required = true, paramType = "path", dataType = "String"),
@ApiImplicitParam(name = "size", value = "页面容量", required = true, paramType = "path", dataType = "String"),
@ApiImplicitParam(name = "pageCurrent", value = "当前页", required = true, paramType = "path", dataType = "String"),
@ApiImplicitParam(name = "type", value = "角色类别", required = true, paramType = "path", dataType = "String"),
@ApiImplicitParam(name = "delete", value = "是否是已经辞退的用户", required = true, paramType = "path", dataType = "String")
})
@RequiresRoles(logical = Logical.OR, value = {"branchCompany", "headCompany", "admin", "distribution"})
@RequiresPermissions(logical = Logical.OR, value = {"admin", "normal", "root"})
public ResultMap getAuthByOrganization(@RequestHeader String token, @PathVariable String organization,
@PathVariable String type, @PathVariable String size,
@PathVariable String pageCurrent, @PathVariable String delete) {
List<Integer> roleId = new ArrayList<>();
String userRole = JWTUtil.getUserRole(token);
getRoleListTools(userRole, organization, roleId);
Page<AuthManageEntity> auth = (Page<AuthManageEntity>) userService.getAuthByOrganizationOnType(
new Page<>(Long.parseLong(pageCurrent), Long.parseLong(size)), organization, roleId, type, delete);
return resultMap.success().message("获取所有用户信息")
.addElement("total", auth.getTotal())
.addElement("userList", auth.getRecords())
.addElement("totalPageNumber", auth.getTotal() / Long.parseLong(size));
}
/**
* 判断身份信息使用,用于获取用户管理界面中用户信息时筛选使用方法
*
* @param userRole 用户的当前权限
* @param organization 所查询的用户组织
* @param roleId 保存查询出来的权限集合
*/
public void getRoleListTools(String userRole, String organization, List<Integer> roleId) {
if ("branchCompany".equals(userRole)) {
Integer idTbRole = roleService.getOne(new QueryWrapper<Role>()
.select("id_tb_role")
.eq("role", "branchCompany")
.eq("permission", "worker")).getIdTbRole();
roleId.add(idTbRole);
} else if ("headCompany".equals(userRole)) {
Integer idTbRole = roleService.getOne(new QueryWrapper<Role>()
.select("id_tb_role")
.eq("role", "headCompany")
.eq("permission", "worker")).getIdTbRole();
roleId.add(idTbRole);
} else if ("distribution".equals(userRole)) {
Integer idTbRole = roleService.getOne(new QueryWrapper<Role>()
.select("id_tb_role")
.eq("role", "distribution")
.eq("permission", "worker")).getIdTbRole();
roleId.add(idTbRole);
} else {
Integer headCompany = companyService.getOne(new QueryWrapper<Company>()
.select("head_company")
.eq("name_company", organization)).getHeadCompany();
if (headCompany != null && headCompany > 0) {
List<Role> list = roleService.list(new QueryWrapper<Role>()
.select("id_tb_role")
.eq("role", "branchCompany"));
for (Role r : list) {
roleId.add(r.getIdTbRole());
}
} else {
List<Role> list = roleService.list(new QueryWrapper<Role>()
.select("id_tb_role")
.eq("role", "headCompany"));
for (Role r : list) {
roleId.add(r.getIdTbRole());
}
}
}
}
}
|
package com.tencent.mm.plugin.wallet_core.c;
import com.tencent.mm.ab.b;
import com.tencent.mm.ab.b.a;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.network.k;
import com.tencent.mm.network.q;
import com.tencent.mm.protocal.c.agg;
import com.tencent.mm.protocal.c.agh;
import com.tencent.mm.sdk.platformtools.x;
public final class f extends l implements k {
private b diG;
private e diJ;
public String pjb = "";
public boolean pjc = false;
public f() {
a aVar = new a();
aVar.dIG = new agg();
aVar.dIH = new agh();
aVar.uri = "/cgi-bin/mmpay-bin/getpayuserduty";
aVar.dIF = 2541;
aVar.dII = 0;
aVar.dIJ = 0;
this.diG = aVar.KT();
}
public final int getType() {
return 2541;
}
public final int a(com.tencent.mm.network.e eVar, e eVar2) {
this.diJ = eVar2;
return a(eVar, this.diG, this);
}
public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) {
x.d("MircoMsg.NetSceneGetPayUserDuty", "errType = " + i2 + ", errCode = " + i3);
if (i2 == 0 && i3 == 0) {
agh agh = (agh) ((b) qVar).dIE.dIL;
this.pjb = agh.pjb;
this.pjc = agh.pjc;
x.i("MircoMsg.NetSceneGetPayUserDuty", "duty_info %s need_agree_duty %s", new Object[]{this.pjb, Boolean.valueOf(this.pjc)});
this.diJ.a(i2, i3, str, this);
return;
}
this.diJ.a(i2, i3, str, this);
}
}
|
package com.javakc.ssm.modules.dictionary.dao;
import com.javakc.ssm.base.dao.BaseDao;
import com.javakc.ssm.base.dao.MyBatisDao;
import com.javakc.ssm.modules.dictionary.entity.DictionaryEntity;
/**
* 数据字典模块数据层实现
* @author javakc
* @version 0.1
*/
@MyBatisDao
public interface DictionaryDao extends BaseDao<DictionaryEntity>{
}
|
package org.buaa.ly.MyCar.logic;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.github.binarywang.wxpay.bean.order.WxPayNativeOrderResult;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.github.binarywang.wxpay.bean.result.WxPayRefundQueryResult;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import org.buaa.ly.MyCar.entity.Order;
public interface PayLogic {
WxPayNativeOrderResult getPayUrl(Order order, String ip) throws WxPayException;
WxPayOrderQueryResult queryOrder(String oid) throws WxPayException;
WxPayRefundResult refundOrder(Order order) throws WxPayException;
WxPayRefundQueryResult refundQuery(String oid) throws WxPayException;
WxPayOrderNotifyResult payNotify(String xmlData) throws WxPayException;
WxPayRefundNotifyResult refundNotify(String xmlData) throws WxPayException;
}
|
package fadhel.iac.tn.eventtracker.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by Fadhel on 30/03/2016.
*/
public class NetworkUtil {
public static int CONNECTED = 1;
public static int DISCONNECTED = 0 ;
public static int getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNet = cm.getActiveNetworkInfo();
if(activeNet!=null)
if(activeNet.getType()==ConnectivityManager.TYPE_WIFI || activeNet.getType()==ConnectivityManager.TYPE_MOBILE)
return CONNECTED;
return DISCONNECTED;
}
public static boolean hasActiveConnection(Context context) {
if(getConnectivityStatus(context)==1){
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 204 &&
urlc.getContentLength() == 0);
} catch (IOException e) {
Log.e("Connection", "Error checking internet connection", e);
}
} else {
Log.d("Connection", "No network available!");
}
return false;
}
} |
package rent.common.projection;
import org.springframework.data.rest.core.config.Projection;
import rent.common.entity.TariffValueEntity;
import java.time.LocalDate;
@Projection(types = {TariffValueEntity.class})
public interface TariffValueBasic extends AbstractBasic {
CalculationTypeBasic getCalculationType();
MeasurementUnitBasic getMeasurementUnit();
Double getValue();
LocalDate getDateStart();
LocalDate getDateEnd();
}
|
package com.tencent.mm.plugin.appbrand.jsapi;
import com.tencent.mm.plugin.appbrand.ipc.AppBrandMainProcessService;
import com.tencent.mm.plugin.appbrand.l;
import com.tencent.mm.plugin.appbrand.r.c;
import org.json.JSONObject;
public final class JsApiGetSetting extends a {
public static final int CTRL_INDEX = 236;
public static final String NAME = "getSetting";
public final void a(l lVar, JSONObject jSONObject, int i) {
GetSettingTask getSettingTask = new GetSettingTask();
getSettingTask.mAppId = lVar.mAppId;
getSettingTask.fFw = i;
getSettingTask.fcy = lVar;
c.br(getSettingTask);
AppBrandMainProcessService.a(getSettingTask);
}
}
|
package net.javaguides.springboot.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import net.javaguides.springboot.model.Instance;
import net.javaguides.springboot.repository.InstanceRepository;
@Service
public class InstanceServiceimpl implements InstanceService{
@Autowired
private InstanceRepository instanceRepository;
@Override
public List<Instance> getAllInstances() {
return instanceRepository.findAll();
}
}
|
package com.tr.selenium.tests;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ContactDeletionTests extends TestBase {
@Test
public void contactDeletionTest(){
app.getNavigationHelper().goToHomePage();
if(!app.getContactHelper().isContactExist()){
app.getContactHelper().createContact();
}
int before = app.getContactHelper().getContactCount();
app.getContactHelper().chooseContact();
app.getContactHelper().deleteContact();
int after = app.getContactHelper().getContactCount();
Assert.assertEquals(after, before-1);
}
}
|
package com.borroom.backend.domain;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.*;
import java.util.Date;
@Entity
@Table(name = "record")
public class Record {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String userid;
private String roomnum;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createtime;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm")
private Date starttime;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm")
private Date endtime;
private String usereason;
private Integer status;
public Date getStarttime() {
return starttime;
}
public void setStarttime(Date starttime) {
this.starttime = starttime;
}
public Date getEndtime() {
return endtime;
}
public void setEndtime(Date endtime) {
this.endtime = endtime;
}
public Record() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserid() {
return userid;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getRoomnum() {
return roomnum;
}
public void setRoomnum(String roomnum) {
this.roomnum = roomnum;
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getUsereason() {
return usereason;
}
public void setUsereason(String usereason) {
this.usereason = usereason;
}
}
|
package net.iz44kpvp.kitpvp.Comandos;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import net.iz44kpvp.kitpvp.Sistemas.API;
public class Fly implements CommandExecutor {
public boolean onCommand(final CommandSender sender, final Command cmd, final String label, final String[] args) {
final Player p = (Player) sender;
if (cmd.getName().equalsIgnoreCase("fly")) {
if (p.hasPermission("Ninho.fly")) {
if (args.length == 0) {
if (!p.getAllowFlight()) {
p.setAllowFlight(true);
p.setFlying(true);
p.sendMessage(String.valueOf(String.valueOf(API.preffix)) + "§5Voc\u00ea ativou seu fly");
} else {
p.setAllowFlight(false);
p.setFlying(false);
p.sendMessage(String.valueOf(String.valueOf(API.preffix)) + "§bVoc\u00ea desativou seu fly");
}
} else {
final Player target = p.getServer().getPlayer(args[0]);
if (target != null) {
if (!target.getAllowFlight()) {
target.setAllowFlight(true);
target.setFlying(true);
target.sendMessage(String.valueOf(String.valueOf(API.preffix)) + "§bO(A) jogador(a): §5"
+ p.getDisplayName() + " §bativou seu fly");
p.sendMessage(String.valueOf(String.valueOf(API.preffix))
+ "§bVoc\u00ea ativou o fly de: §5" + target.getDisplayName());
} else {
target.setAllowFlight(false);
target.setAllowFlight(false);
target.setFlying(false);
target.sendMessage(String.valueOf(String.valueOf(API.preffix)) + "§bO(A) jogador(a): §5"
+ p.getDisplayName() + " §bdesativou seu fly");
p.sendMessage(String.valueOf(String.valueOf(API.preffix))
+ "§bVoc\u00ea desativou o fly de: §5" + target.getDisplayName());
}
} else {
p.sendMessage(API.jogadoroff);
}
}
} else {
p.sendMessage(API.semperm);
}
}
return false;
}
}
|
package commandline.command;
import commandline.argument.GenericArgumentList;
import org.junit.Test;
public class GenericCommandTest {
@Test(expected = IllegalArgumentException.class)
public void testConstructor() {
new GenericCommand(" ", new GenericArgumentList());
}
} |
package com.lister.bll.interfaces;
import java.io.Serializable;
import java.util.List;
public interface IGenericService <T extends Serializable, ID extends Serializable> {
public boolean create(T e);
public boolean delete(T e);
public boolean update(T e);
public T get(ID id);
public List<T> get();
}
|
package edu.sit.bancodedados.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import edu.sit.bancodedados.conexao.Conexao;
import edu.sit.bancodedados.conexao.ConexaoException;
import edu.sit.erros.dao.DaoException;
import edu.sit.erros.dao.EErrosDao;
import edu.sit.model.Fornecedor;
public class FornecedorDao extends InstaladorDao implements IDao<Fornecedor> {
@Override
public boolean criaTabela() throws DaoException, ConexaoException {
Connection conexao = Conexao.abreConexao();
try {
Statement st = conexao.createStatement();
st.executeUpdate("CREATE TABLE IF NOT EXISTS `Fornecedor` (" +
" `id` INT NOT NULL AUTO_INCREMENT," +
" `Nome` VARCHAR(45) NOT NULL," +
" `PessoaResponsavel` VARCHAR(45) NOT NULL," +
" `CNPJ` VARCHAR(45) NOT NULL," +
" `Contato` INT NOT NULL," +
" PRIMARY KEY (`id`)," +
" INDEX `fk_Fornecedor_Contato1_idx` (`Contato` ASC) )" +
"ENGINE = InnoDB;");
return true;
} catch (Exception e) {
throw new DaoException(EErrosDao.CRIAR_TABELA, e.getMessage(), this.getClass());
} finally {
Conexao.fechaConexao();
}
}
@Override
public boolean excluiTabela() throws DaoException, ConexaoException {
Connection conexao = Conexao.abreConexao();
try {
Statement st = conexao.createStatement();
st.execute("DROP TABLE Fornecedor;");
return true;
} catch (Exception e) {
throw new DaoException(EErrosDao.EXCLUI_DADO, e.getMessage(), this.getClass());
} finally {
Conexao.fechaConexao();
}
}
@Override
public Fornecedor consulta(Integer codigo) throws DaoException, ConexaoException {
Connection conexao = Conexao.abreConexao();
try {
PreparedStatement pst = conexao.prepareStatement("SELECT * FROM Fornecedor WHERE id = ?;");
pst.setInt(1, codigo);
ResultSet rs = pst.executeQuery();
return rs.first() ? new Fornecedor(rs.getInt("id"), rs.getString("Nome"),
rs.getString("CNPJ"), rs.getString("PessoaResponsavel"), rs.getInt("Contato")) : null;
} catch (Exception e) {
throw new DaoException(EErrosDao.CONSULTA_DADO, e.getMessage(), this.getClass());
} finally {
Conexao.fechaConexao();
}
}
public Fornecedor consultaCompleta(Integer id) throws DaoException, ConexaoException {
Fornecedor fornecedor = consulta(id);
fornecedor.setContato(new ContatoDao().consulta(fornecedor.getContatoid()));
return fornecedor;
}
public Fornecedor consultaCNPJ(String cnpj) throws DaoException, ConexaoException {
Connection conexao = Conexao.abreConexao();
try {
PreparedStatement pst = conexao.prepareStatement("SELECT * FROM Fornecedor Where CNPJ = ?;");
pst.setString(1, cnpj);
ResultSet rs = pst.executeQuery();
return rs.first() ? new Fornecedor(rs.getInt("id"), rs.getString("Nome"),
rs.getString("CNPJ"), rs.getString("PessoaResponsavel"), rs.getInt("Contato")) : null;
} catch (Exception e) {
throw new DaoException(EErrosDao.CONSULTA_DADO, e.getMessage(), this.getClass());
} finally {
Conexao.fechaConexao();
}
}
@Override
public List<Fornecedor> consultaTodos() throws DaoException, ConexaoException {
Connection conexao = Conexao.abreConexao();
List<Fornecedor> fornecedores = new ArrayList<Fornecedor>();
try {
Statement st = conexao.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM Fornecedor;");
while (rs.next()) {
fornecedores.add(new Fornecedor(rs.getInt("id"), rs.getString("Nome"),
rs.getString("CNPJ"), rs.getString("PessoaResponsavel"), rs.getInt("Contato")));
}
return fornecedores;
} catch (Exception e) {
throw new DaoException(EErrosDao.CONSULTA_DADO, e.getMessage(), this.getClass());
} finally {
Conexao.fechaConexao();
}
}
public List<Fornecedor> consultaTodosCompleto() throws DaoException, ConexaoException {
List<Fornecedor> fornecedoresCompleto = new ArrayList<>();
List<Fornecedor> fornecedores = consultaTodos();
for (Fornecedor fornecedor : fornecedores) {
fornecedoresCompleto.add(consultaCompleta(fornecedor.getId()));
}
return fornecedoresCompleto;
}
@Override
public List<Fornecedor> consultaVariosPorID(Integer... codigos) throws DaoException, ConexaoException {
Connection conexao = Conexao.abreConexao();
List<Fornecedor> fornecedor = new ArrayList<Fornecedor>();
try {
PreparedStatement pst = conexao.prepareStatement("SELECT * FROM Fornecedor WHERE id = ?;");
for (Integer codigo : codigos) {
try {
pst.setInt(1, codigo);
ResultSet rs = pst.executeQuery();
if (rs.first()) {
fornecedor.add(new Fornecedor(rs.getInt("id"), rs.getString("Nome"),
rs.getString("CNPJ"), rs.getString("PessoaResponsavel"), rs.getInt("Contato")));
}
} catch (Exception c) {
new DaoException(EErrosDao.CONSULTA_DADO, c.getMessage(), this.getClass());
}
}
} catch (Exception e) {
throw new DaoException(EErrosDao.CONSULTA_DADO, e.getMessage(), this.getClass());
} finally {
Conexao.fechaConexao();
}
return fornecedor;
}
public List<Fornecedor> consultaFaixaCompleto(Integer... codigos) throws DaoException, ConexaoException {
List<Fornecedor> fornecedoresCompleto = new ArrayList<>();
List<Fornecedor> fornecedores = consultaVariosPorID(codigos);
for (Fornecedor fornecedor : fornecedores) {
fornecedoresCompleto.add(consultaCompleta(fornecedor.getId()));
}
return fornecedoresCompleto;
}
@Override
public boolean insere(Fornecedor objeto) throws DaoException, ConexaoException {
Connection conexao = Conexao.abreConexao();
try {
PreparedStatement pst = conexao.prepareStatement(
"INSERT INTO Fornecedor (Nome, CNPJ, PessoaResponsavel, Contato) values (?, ?, ?, ?);");
pst.setString(1, objeto.getNome());
pst.setString(2, objeto.getCNPJ());
pst.setString(3, objeto.getPessoaResponsavel());
pst.setInt(4, objeto.getContatoid());
return pst.executeUpdate() > 0;
} catch (Exception e) {
throw new DaoException(EErrosDao.INSERE_DADO, e.getMessage(), this.getClass());
} finally {
Conexao.fechaConexao();
}
}
@Override
public boolean altera(Fornecedor objeto) throws DaoException, ConexaoException {
Connection conexao = Conexao.abreConexao();
try {
PreparedStatement pst = conexao.prepareStatement(
"UPDATE Fornecedor SET Nome = ?, CNPJ = ?, PessoaResponsavel = ?, Contato = ? WHERE id = ?;");
pst.setString(1, objeto.getNome());
pst.setString(2, objeto.getCNPJ());
pst.setString(3, objeto.getPessoaResponsavel());
pst.setInt(4, objeto.getContatoid());
pst.setInt(5, objeto.getId());
return pst.executeUpdate() > 0;
} catch (Exception e) {
throw new DaoException(EErrosDao.ALTERA_DADO, e.getMessage(), this.getClass());
} finally {
Conexao.fechaConexao();
}
}
@Override
public boolean exclui(Integer... codigos) throws DaoException, ConexaoException {
Connection conexao = Conexao.abreConexao();
try {
PreparedStatement pst = conexao.prepareStatement("DELETE FROM Fornecedor WHERE id = ?;");
for (Integer novo : codigos) {
pst.setInt(1, novo);
pst.execute();
}
} catch (Exception e) {
throw new DaoException(EErrosDao.EXCLUI_DADO, e.getMessage(), this.getClass());
} finally {
Conexao.fechaConexao();
}
return true;
}
public Integer pegaUltimoID() throws DaoException, ConexaoException {
Connection conexao = Conexao.abreConexao();
try {
Statement st = conexao.createStatement();
ResultSet rs = st.executeQuery("SELECT MAX(id) FROM Fornecedor;");
return rs.first() ? rs.getInt(1) : 0;
} catch (Exception e) {
throw new DaoException(EErrosDao.PEGA_ID, e.getMessage(), this.getClass());
} finally {
Conexao.fechaConexao();
}
}
}
|
package com.rastiehaiev.notebook.controller;
import com.rastiehaiev.notebook.bean.User;
import com.rastiehaiev.notebook.management.IVocabularyManagementService;
import com.rastiehaiev.notebook.response.IResponse;
import com.rastiehaiev.notebook.response.word.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpSession;
/**
* @author Roman Rastiehaiev
* Created on 21.09.15.
*/
@Controller
public class VocabularyController extends BaseController {
private static final Logger LOG = Logger.getLogger(VocabularyController.class);
@Autowired
private IVocabularyManagementService vocabularyManagementService;
@RequestMapping(value = "/vocabulary", method = RequestMethod.GET)
public ModelAndView showVocabulary(@RequestParam(value = "page", required = false) String pageNumber, HttpSession session) {
User user = getUser(session);
return getModelAndViewWithVocabularyOfUserById(pageNumber, user.getId());
}
@RequestMapping(value = "/vocabulary/{login}", method = RequestMethod.GET)
public ModelAndView showVocabularyOfAnotherUser(@RequestParam(value = "page", required = false) String pageNumber,
@PathVariable String login) {
return getModelAndViewWithVocabularyOfUserByLogin(pageNumber, login);
}
@RequestMapping(value = {"/vocabulary"}, method = RequestMethod.POST)
public ModelAndView addNewWordAndRedirect(@RequestParam(value = "wordId", required = false) String wordId,
@RequestParam("word") String englishWord,
@RequestParam("translation") String translation,
HttpSession session) {
LOG.info("Adding new word: " + englishWord + "=" + translation);
User user = (User) session.getAttribute("user");
if (user == null) {
throw new IllegalStateException("User cannot be null.");
}
IResponse response = vocabularyManagementService.createWord(user.getId(), wordId, englishWord, translation);
return modelAndViewWithErrorsIfAny("vocabulary", response, session);
}
@RequestMapping(value = {"/vocabulary"}, method = RequestMethod.DELETE)
public void removeWords(@RequestParam("words") String wordsToBeRemoved, HttpSession session) {
User user = getUser(session);
vocabularyManagementService.removeWords(user.getId(), wordsToBeRemoved);
}
@RequestMapping(value = {"/vocabulary/{wordId}"}, method = RequestMethod.DELETE)
public
@ResponseBody
void removeSingleWord(@PathVariable String wordId, HttpSession session) {
User user = getUser(session);
vocabularyManagementService.removeWords(user.getId(), wordId);
}
@RequestMapping(value = {"/vocabulary"}, method = RequestMethod.PUT)
public
@ResponseBody
EditWordResponse editWord(HttpSession session,
@RequestParam("id") String id,
@RequestParam("word") String word,
@RequestParam("translation") String translation) {
LOG.info("Editing word " + id);
User user = getUser(session);
return vocabularyManagementService.editWord(user.getId(), id, word, translation);
}
@RequestMapping(value = {"/vocabulary/{userId}/test"})
public
@ResponseBody
GetNextWordForTestResponse getNextWordForTest(@PathVariable String userId) {
LOG.info("Getting next word for test...");
return vocabularyManagementService.getNextWordForTest(userId);
}
@RequestMapping(value = {"/vocabulary/{userId}/test"}, method = RequestMethod.POST)
public
@ResponseBody
CheckAnswerAndReturnNextWordResponse checkWordAndGetNext(@PathVariable String userId,
@RequestParam("word") String word,
@RequestParam("translation") String translation) {
LOG.info("Getting next word for test...");
return vocabularyManagementService.checkWordAndGetNext(userId, word, translation);
}
@RequestMapping(value = {"/vocabulary/steal"}, method = RequestMethod.POST)
public
@ResponseBody
StealWordResponse stealWord(@RequestParam("wordId") String wordId, HttpSession session) {
User user = getUser(session);
return vocabularyManagementService.stealWord(user.getId(), wordId);
}
private ModelAndView getModelAndViewWithVocabularyOfUserById(String pageNumber, String userId) {
GetWordsResponse response = vocabularyManagementService.getWordsByUserId(userId, pageNumber);
return this.getModelAndViewWithVocabulary(response);
}
private ModelAndView getModelAndViewWithVocabularyOfUserByLogin(String pageNumber, String login) {
GetWordsResponse response = vocabularyManagementService.getWordsByLogin(login, pageNumber);
return this.getModelAndViewWithVocabulary(response);
}
private ModelAndView getModelAndViewWithVocabulary(GetWordsResponse response) {
ModelAndView modelAndView = new ModelAndView("vocabulary");
modelAndView.addObject("words", response.getWords());
modelAndView.addObject("pageNumber", response.getPageNumber());
modelAndView.addObject("pagesCount", response.getPagesCount());
modelAndView.addObject("totalWordsCount", response.getTotalCount());
modelAndView.addObject("owner", response.getOwner());
LOG.info(String.format("wordsCount:%s, pageNumber:%s, pagesCount:%s", response.getWords().size(), response.getPageNumber(), response.getPagesCount()));
return modelAndView;
}
}
|
package com.psl.flashnotes.bean;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
@Embeddable
public class CompositeId1 implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Column(name = "noteId")
private int noteId;
@Column(name = "userId")
private int userId;
public int getNoteId() {
return noteId;
}
public void setNoteId(int noteId) {
this.noteId = noteId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
} |
package prj5;
import student.TestCase;
/**
* Testing the glyph
*
* @author emily
* @version 2019.12.02
*/
public class GlyphTest extends TestCase {
private Glyph glyph;
/**
* sets up the class
*/
public void setUp() {
Song boho = new Song("Queen", "Bohemian Rhapsody", "Rock", "1975");
int[] heard = new int[] { 4, 0, 0, 0, 8, 0, 0, 0 };
int[] liked = new int[] { 3, 0, 0, 0, 6, 0, 0, 0 };
glyph = new Glyph(boho, heard, liked);
}
/**
* Test getter methods
*/
public void testGetters() {
assertEquals("Queen", glyph.getArtist());
assertEquals("Bohemian Rhapsody", glyph.getTitle());
assertEquals("Rock", glyph.getGenre());
assertEquals("1975", glyph.getYear());
assertEquals(0, glyph.getPercent(0, 100));
assertEquals(50, glyph.getPercent(4, 8));
assertEquals(0, glyph.getPercHeard(2));
assertEquals(0, glyph.getPercHeard(1));
assertEquals(50, glyph.getPercHeard(3));
assertEquals(0, glyph.getPercHeard(4));
assertEquals(50, glyph.getPercHeard(0));
assertEquals(0, glyph.getPercLiked(2));
assertEquals(0, glyph.getPercLiked(1));
assertEquals(50, glyph.getPercLiked(3));
assertEquals(0, glyph.getPercLiked(4));
assertEquals(50, glyph.getPercLiked(0));
}
}
|
package map;
import java.util.HashSet;
import java.util.Set;
public class HashCodeAndEquals {
public static void main(String[] args) {
Pen pen1 = new Pen(10, "blue");
Pen pen2 = new Pen(10, "blue");
//System.out.println(pen1==pen2);
//System.out.println(pen1);
//System.out.println(pen2); //pen1 and pen2 both are at different location in memory
//System.out.println(pen1.equals(pen2)); // returns false
//after implement equal method
System.out.println(pen1);
System.out.println(pen2);
System.out.println(pen1.equals(pen2)); // this is showing both pens are equal
Set<Pen> pens = new HashSet<>();
pens.add(pen1);
pens.add(pen2);
//System.out.println(pens); //here HashSet can enter both entries
// of pen1 and pen2 it means hash set is not considering them equal
//so we have to implement Hashcode
//after implement hash code
System.out.println(pens);
//this is entring only one pen it means it consider both pens are same
// according to equality of their price and color
}
}
class Pen{
int price;
String color;
public Pen(int price, String color) {
this.price = price;
this.color = color;
}
@Override
public boolean equals(Object obj) {
Pen that = (Pen) obj; //casting
boolean isEqual = this.price==that.price &&
this.color.equals(that.color);
return isEqual; //now this will show that pen1 and pen2 both are equal
}//accordin equals function output both pens are equal and this may cause of occurring collision
//so we have to improve hashCode to reduce collision
@Override
public int hashCode() {
return price+color.hashCode();
}
}
// eclipse already gives the functionality to create hashCode() and equals() by clicks some option
/*
* 1) click source
* 2) scroll down and click generate hashCode() and equals()
* 3) select attributes for which you want to generate hashcode and equals
* */
|
package com.store.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.store.service.PermissionService;
import com.store.service.PermissionServiceImpl;
/**
* Servlet implementation class PerDelServlet
*/
@WebServlet("/PerDelServlet")
public class PerDelServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
int id = Integer.parseInt(request.getParameter("id"));
PermissionService pService = new PermissionServiceImpl();
pService.delSysPermission(id);
request.getRequestDispatcher("perIndex").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
|
package com.example.a12306f.fragment;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import com.example.a12306f.R;
import com.example.a12306f.a.Seat;
import com.example.a12306f.a.Train;
import com.example.a12306f.adapter.JAdapter;
import com.example.a12306f.stationlist.StationListActivity;
import com.example.a12306f.ticket.TicketQuery;
import com.example.a12306f.utils.History;
import com.google.gson.internal.bind.ReflectiveTypeAdapterFactory;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TicketFragment extends Fragment {
private TextView tv_start_city,tv_arrive_city,tv_time;
Button btn_query;
private ImageView img_station_exchange;
private ListView lv_history;
final private String TAG = "TicketFragment";
private History history;
private List<Map<String,Object>> data;
private ArrayList arrayList;
private JAdapter Adapter;
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
"android.permission.READ_EXTERNAL_STORAGE",
"android.permission.WRITE_EXTERNAL_STORAGE" };
public static void verifyStoragePermissions(Activity activity) {
try {
//检测是否有写的权限
int permission = ActivityCompat.checkSelfPermission(activity,
"android.permission.WRITE_EXTERNAL_STORAGE");
if (permission != PackageManager.PERMISSION_GRANTED) {
// 没有写的权限,去申请写的权限,会弹出对话框
ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public TicketFragment(){
//需要空的构造方法
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_ticket_fragment,container,false);
}
private Handler handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
switch (msg.what){
case 1:
Train[] trains = (Train[]) msg.obj;
for (Train trains1:trains){
Map<String,Object> map = new HashMap<>();
map.put("trainNo",trains1.getTrainNo());
if (trains1.getStartStationName().equals(trains1.getFromStationName())){
map.put("img1",R.drawable.flg_shi);
}else {
map.put("img1",R.drawable.flg_guo);
}
if (trains1.getEndStationName().equals(trains1.getToStationName())){
map.put("img2",R.drawable.flg_zhong);
}else {
map.put("img2",R.drawable.flg_guo);
}
// map.put("startStationName",trains1.getStartStationName());
// map.put("endStationName",trains1.getEndStationName());
// map.put("fromStationName",trains1.getFromStationName());
// map.put("toStationName",trains1.getToStationName());
map.put("startTime",trains1.getStartTime());
map.put("durationTime",trains1.getDurationTime());
map.put("arriveTime",trains1.getArriveTime()+"("+trains1.getDayDifference()+")");
String[] seatKey = {"seat1","seat2","seat3","seat4"};
int i = 0;
Map<String, Seat> seats = trains1.getSeats();
for (String key :seats.keySet()){
Seat seat = seats.get(key);
map.put(seatKey[i++],seat.getSeatName()+ ":" + seat.getSeatNum());
}
// map.put("dayDifference",trains1.getDayDifference());
// map.put("durationTime",trains1.getDurationTime());
// map.put("startTrainDate",trains1.getStartTrainDate());
// map.put("seats",trains1.getSeats());
data.add(map);
}
break;
case 2:
Toast.makeText(getActivity(),"服务器错误,请重新登录!",Toast.LENGTH_SHORT).show();
break;
}
}
};
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
lv_history = view.findViewById(R.id.history);
tv_start_city = view.findViewById(R.id.tv_start_city);
tv_arrive_city = view.findViewById(R.id.tv_arrive_city);
tv_time = view.findViewById(R.id.tv_time);
btn_query = view.findViewById(R.id.btn_query);
img_station_exchange = view.findViewById(R.id.img_station_exchange);
//出发城市
tv_start_city.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setClass(getActivity(), StationListActivity.class);
startActivityForResult(intent,100);
}
});
// 到达城市
tv_arrive_city.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setClass(getActivity(),StationListActivity.class);
startActivityForResult(intent,200);
}
});
//
//交换
img_station_exchange.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String leftT = tv_arrive_city.getText().toString();
final String rightT = tv_start_city.getText().toString();
TranslateAnimation anileft = new TranslateAnimation(0,500,0,0);
anileft.setInterpolator(new LinearInterpolator());
anileft.setDuration(500);
anileft.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
tv_start_city.clearAnimation();
tv_start_city.setText(leftT);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
tv_start_city.startAnimation(anileft);
//若XDelta>0,则说明控件向右侧发生移动
TranslateAnimation aniright = new TranslateAnimation(0,-500,0,0);
aniright.setInterpolator(new LinearInterpolator());
aniright.setDuration(500);
//三个方法分别是Animation开始的时候调用,完成的时候调用,重复的时候调用。
aniright.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
tv_arrive_city.clearAnimation();
tv_arrive_city.setText(rightT);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
tv_arrive_city.startAnimation(aniright);
}
});
//历史记录
history = new History(getActivity());
arrayList = history.query();
lv_history = view.findViewById(R.id.history);
Adapter= new JAdapter(getActivity(),arrayList,R.layout.history_item);
lv_history.setAdapter(Adapter);
final Calendar oldCalendar = Calendar.getInstance();
final int Year = oldCalendar.get(Calendar.YEAR);
final int Month = oldCalendar.get(Calendar.MONTH);
final int Day = oldCalendar.get(Calendar.DATE);
String Week = DateUtils.formatDateTime(getActivity(),oldCalendar.getTimeInMillis(),DateUtils.FORMAT_SHOW_WEEKDAY);
Log.d("getActivity.this", "Week: "+Week);
tv_time.setText(Year +"-"+(Month +1)+"-"+ Day +" "+Week);
//TODO 日期选择对话框
tv_time.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
// @Override
// public void onDateSet(DatePicker datePicker, int year, int month, int day) {
//
// Calendar newCalendar = Calendar.getInstance();
// newCalendar.set(year,month,day);
// String weekDay = DateUtils.formatDateTime(getActivity(),newCalendar.getTimeInMillis(),DateUtils.FORMAT_SHOW_WEEKDAY);
// tv_time.setText(year+"-"+(month+1)+"-"+day+" "+weekDay);
// Log.d("getActivity.this",weekDay);
// }
// },Year,Month,Day).show();
// DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener(){
// @Override
// public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
// Calendar newCalendar = Calendar.getInstance();
// newCalendar.set(year,month,dayOfMonth);
// String weekDay = DateUtils.formatDateTime(getActivity(),newCalendar.getTimeInMillis(),DateUtils.FORMAT_SHOW_WEEKDAY);
// tv_time.setText(year+"-"+(month+1)+"-"+dayOfMonth+" "+weekDay);
// Log.d("getActivity.this",weekDay);
// }
// };
// DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(),listener,
// Year,Month,Day){
// @Override
// public void onDateChanged(@NonNull DatePicker view, int year, int month, int dayOfMonth) {
// super.onDateChanged(view, year, month, dayOfMonth);
// if (year < Year)
// view.updateDate(Year, Month, Day);
// if (month < Month && year == Year)
// view.updateDate(Year, Month, Day);
// if (dayOfMonth < Day && year == Year && month == Month)
// view.updateDate(Year, Month, Day);
//
// }
// };
// datePickerDialog.show();
DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar newCalender = Calendar.getInstance();
newCalender.set(year,month,dayOfMonth);
String weekDay = DateUtils.formatDateTime(getActivity(),newCalender.getTimeInMillis(),DateUtils.FORMAT_SHOW_WEEKDAY);
tv_time.setText(year+"-"+(month+1)+"-"+dayOfMonth+" "+weekDay);
}
},Year,Month,Day);
datePickerDialog.setTitle("请选择日期");
datePickerDialog.getDatePicker().setMinDate(oldCalendar.getTimeInMillis());
datePickerDialog.show();
}
});
//查询按钮
btn_query.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//历史记录
String SW=tv_start_city.getText().toString();
String EW=tv_arrive_city.getText().toString();
history.insert(SW,EW);
SharedPreferences sharedPreferences= getActivity().getSharedPreferences("user",Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("SW",SW);
editor.putString("EW",EW);
editor.commit();
arrayList = history.query();
Adapter= new JAdapter(getActivity(),arrayList,R.layout.history_item);
Adapter.notifyDataSetChanged();
//跳转查询
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putSerializable("searchData", (Serializable) data);
intent.putExtra("stationFrom",tv_start_city.getText().toString());
intent.putExtra("stationTo",tv_arrive_city.getText().toString());
intent.putExtra("startTicketDate",tv_time.getText().toString());
intent.putExtras(bundle);
intent.setClass(getActivity(), TicketQuery.class);
startActivity(intent);
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String stationName = data.getStringExtra("name");
if(!TextUtils.isEmpty(stationName)){
switch (requestCode){
case 100:
tv_start_city.setText(stationName);
break;
case 200:
tv_arrive_city.setText(stationName);
break;
}
}
}
} |
package com.csform.android.uiapptemplate;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import com.google.android.gms.internal.mm;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MapFragment extends Fragment implements OnMapLongClickListener,
LocationListener {
public static final String LOCATION_SERVICE = "location";
double lat, lon;
String latString, lonString;
String markerString;
LatLng latlng;
TextView textviewMap;
Boolean longpress = true;
LocationManager locationManager;
ProgressBar progressBarMapFragmentDetail;
static public ArrayList<HashMap<String, String>> mylist;
MapFragment(boolean longpress) {
this.longpress = longpress;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mylist = new ArrayList<HashMap<String, String>>();
UserSessionManager session = new UserSessionManager(getActivity());
View v = inflater.inflate(R.layout.map_fragment, container, false);
Toast.makeText(getActivity(),"Long press on map to add tips!!!",Toast.LENGTH_LONG).show();
progressBarMapFragmentDetail = (ProgressBar) v
.findViewById(R.id.progressBarMapFragmentDetail);
//textviewMap = (TextView) v.findViewById(R.id.textView1);
final GoogleMap mMap = ((SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.mapid)).getMap();
locationManager = (LocationManager) getActivity().getSystemService(
LOCATION_SERVICE);
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mMap.getUiSettings().setMapToolbarEnabled(false);
if (longpress) {
//textviewMap.setText("Long press at location to report a crime");
mMap.setOnMapLongClickListener(this);
//textviewMap.setText("Long press to submit a Tips");
markerString = "your current location";
}
else {
//textviewMap.setText("Crime scene");
markerString = "crime scene";
}
if (mMap == null) {
Toast.makeText(getActivity(), "something wrong with google map",
Toast.LENGTH_SHORT).show();
} else {
try {
lat = location.getLatitude();
lon = location.getLongitude();
Log.e("lat n lon",
String.valueOf(lat) + " " + String.valueOf(lon));
LatLng latlng = new LatLng(lat, lon);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 15f));
mMap.addMarker(
new MarkerOptions().position(latlng).title(markerString))
;
} catch (Exception ex) {
try
{
mMap.setMyLocationEnabled(true);
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
lat=arg0.getLatitude();
lon=arg0.getLongitude();
latlng=new LatLng(lat, lon);
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.crimehere);
mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("My current Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 15f));
}
});
}
}catch(Exception ex1)
{
Log.e("lat n lon",
String.valueOf(lat) + " " + String.valueOf(lon));
lat = 24.821387;
lon = 78.060060;
markerString="unable to locate exactly";
LatLng latlng = new LatLng(lat, lon);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 6f));
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.crimehere);
mMap.addMarker(
new MarkerOptions().position(latlng).icon(icon).title(markerString))
;
}
}
}
return v;
}
@Override
public void onMapLongClick(LatLng arg0) {
getCategory(arg0.latitude,arg0.longitude);
// TODO Auto-generated method stub
/*
* Intent i = new Intent(getActivity(), Add_item.class); Bundle bundle =
* new Bundle();
*
* // Add your data to bundle bundle.putString("lat",
* String.valueOf(arg0.latitude)); bundle.putString("lon",
* String.valueOf(arg0.longitude));
*
* // Add the bundle to the intent i.putExtras(bundle);
* startActivity(i); getActivity().finish();
*/}
private void getCategory(final double lat1,final double lon1) {
// TODO Auto-generated method stub
new AsyncTask<Void, Long, Boolean>() {
Boolean status;
String url;
protected void onPreExecute() {
url = getResources().getString(R.string.URL_GET_CATEGORY);
progressBarMapFragmentDetail.setVisibility(View.VISIBLE);
};
protected void onPostExecute(Boolean result) {
progressBarMapFragmentDetail.setVisibility(View.INVISIBLE);
if(result)
{
for (int i = 0; i < mylist.size(); i++) {
String id = mylist.get(i).get("type_id");
String type_name = mylist.get(i).get("type_name");
Log.i("type nam", id+" "+type_name);
}
Intent i = new Intent(getActivity(), Add_item.class);
Bundle b = new Bundle();
b.putString("lat", String.valueOf(lat1));
b.putString("lon", String.valueOf(lon1));
i.putExtras(b);
startActivity(i);
}
else
{
Toast.makeText(getActivity(), "couldnot retrieve category", 0).show();
}
};
@Override
protected Boolean doInBackground(Void... added_item) {
// TODO Auto-generated method stub
status = retrieveData(url);
return status;
}
}.execute(null, null, null);
}
protected Boolean retrieveData(String url) {
// TODO Auto-generated method stub
SSLContext ctx = null;
try {
ctx = SSLContext.getInstance("TLS");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ctx.init(null, new TrustManager[] { new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain,
String authType) {
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
} }, null);
} catch (KeyManagementException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
// TODO Auto-generated method stub
return true;
}
});
HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
HttpEntity httpEntity = null;
// TODO Auto-generated method stub
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet();
URI website = new URI(url);
request.setURI(website);
HttpResponse response = httpclient.execute(request);
String json = null;
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
json = EntityUtils.toString(entity);
}
JSONArray jArray = new JSONArray(json);
if (jArray.length() < 1) {
return false;
} else {
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
map.put("type_id", e.getString("type_id"));
map.put("type_name", e.getString("type_name"));
mylist.add(map);
}
return true;
}
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
|
package com.github.lnframeworkdemo;
import android.os.Bundle;
import com.github.fragmention.SupportActivity;
public class ReplaceChildActivity extends SupportActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_replace_child);
if (savedInstanceState == null) {
loadRootFragment(R.id.vg_contain, new ReplaceMainFragment());
}
}
}
|
package animatronics.common.block;
import java.util.List;
import net.minecraft.block.material.Material;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.world.World;
import animatronics.Animatronics;
import animatronics.api.misc.InformationProvider;
import animatronics.common.tile.TileEntityArcaneFlame;
import animatronics.utils.block.BlockContainerBase;
public class BlockArcaneFlame extends BlockContainerBase implements InformationProvider{
public BlockArcaneFlame() {
super("blockArcaneFlame", Animatronics.MOD_ID, Material.cloth, ItemBlockArcaneFlame.class);
setCreativeTab(Animatronics.creativeTabAnimatronics);
setHardness(0.2F);
setBlockBounds(0.3125F, 0.3125F, 0.3125F, 0.6875F, 0.6875F, 0.6875F);
setStepSound(soundTypeCloth);
setLightLevel(1.0f);
}
public AxisAlignedBB getCollisionBoundingBoxFromPool(World p_149668_1_, int p_149668_2_, int p_149668_3_, int p_149668_4_)
{
return null;
}
public boolean isOpaqueCube()
{
return false;
}
public boolean isFullCube()
{
return false;
}
public int getRenderType(){
return -1215;
}
public boolean renderAsNormalBlock(){
return false;
}
@Override
public void addInformation(ItemStack stk, EntityPlayer p, List list, boolean held) {
list.add(EnumChatFormatting.LIGHT_PURPLE + "Witch hammer");
}
@Override
public TileEntity createNewTileEntity(World world, int metadata) {
return new TileEntityArcaneFlame();
}
}
|
package com.tencent.mm.plugin.sns.ui;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.View.OnTouchListener;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.tmassistantsdk.logreport.BaseReportManager;
class SnsOnlineVideoActivity$5 implements OnTouchListener {
final /* synthetic */ SnsOnlineVideoActivity nZl;
SnsOnlineVideoActivity$5(SnsOnlineVideoActivity snsOnlineVideoActivity) {
this.nZl = snsOnlineVideoActivity;
}
public final boolean onTouch(View view, MotionEvent motionEvent) {
float f = 1.0f;
SnsOnlineVideoActivity.d(this.nZl).onTouchEvent(motionEvent);
if (SnsOnlineVideoActivity.e(this.nZl) == null) {
SnsOnlineVideoActivity.a(this.nZl, VelocityTracker.obtain());
}
if (SnsOnlineVideoActivity.e(this.nZl) != null) {
SnsOnlineVideoActivity.e(this.nZl).addMovement(motionEvent);
}
switch (motionEvent.getAction() & 255) {
case 0:
SnsOnlineVideoActivity.a(this.nZl, motionEvent.getX());
SnsOnlineVideoActivity.b(this.nZl, motionEvent.getY());
if (SnsOnlineVideoActivity.f(this.nZl)) {
SnsOnlineVideoActivity.g(this.nZl);
SnsOnlineVideoActivity.b(this.nZl, false);
break;
}
break;
case 1:
if (SnsOnlineVideoActivity.f(this.nZl)) {
SnsOnlineVideoActivity.c(this.nZl).setPivotX((float) (SnsOnlineVideoActivity.a(this.nZl).getWidth() / 2));
SnsOnlineVideoActivity.c(this.nZl).setPivotY((float) (SnsOnlineVideoActivity.a(this.nZl).getHeight() / 2));
SnsOnlineVideoActivity.c(this.nZl).setScaleX(1.0f);
SnsOnlineVideoActivity.c(this.nZl).setScaleY(1.0f);
SnsOnlineVideoActivity.c(this.nZl).setTranslationX(0.0f);
SnsOnlineVideoActivity.c(this.nZl).setTranslationY(0.0f);
SnsOnlineVideoActivity.h(this.nZl).setAlpha(1.0f);
SnsOnlineVideoActivity.c(this.nZl, 1.0f);
SnsOnlineVideoActivity.c(this.nZl, false);
SnsOnlineVideoActivity.a(this.nZl, false);
return true;
} else if (!SnsOnlineVideoActivity.b(this.nZl) || SnsOnlineVideoActivity.i(this.nZl)) {
SnsOnlineVideoActivity.a(this.nZl, false);
break;
} else {
this.nZl.ayH();
SnsOnlineVideoActivity.a(this.nZl, false);
return true;
}
break;
case 2:
VelocityTracker e = SnsOnlineVideoActivity.e(this.nZl);
e.computeCurrentVelocity(BaseReportManager.MAX_READ_COUNT);
int xVelocity = (int) e.getXVelocity();
int yVelocity = (int) e.getYVelocity();
float translationX = SnsOnlineVideoActivity.c(this.nZl).getTranslationX();
float translationY = SnsOnlineVideoActivity.c(this.nZl).getTranslationY();
SnsOnlineVideoActivity.a(this.nZl, (int) translationX);
SnsOnlineVideoActivity.b(this.nZl, (int) translationY);
x.d("MicroMsg.SnsOnlineVideoActivity", "dancy scaled:%s, tx:%s, ty:%s, vx:%s, vy:%s", new Object[]{Boolean.valueOf(SnsOnlineVideoActivity.b(this.nZl)), Float.valueOf(translationX), Float.valueOf(translationY), Integer.valueOf(xVelocity), Integer.valueOf(yVelocity)});
if ((Math.abs(translationX) > 250.0f || Math.abs(yVelocity) <= Math.abs(xVelocity) || yVelocity <= 0 || SnsOnlineVideoActivity.i(this.nZl)) && !SnsOnlineVideoActivity.b(this.nZl)) {
SnsOnlineVideoActivity.c(this.nZl, false);
} else {
translationX = 1.0f - (translationY / ((float) SnsOnlineVideoActivity.a(this.nZl).getHeight()));
if (translationX <= 1.0f) {
f = translationX;
}
if (((yVelocity > 0 && f < SnsOnlineVideoActivity.j(this.nZl)) || yVelocity < 0) && ((double) f) >= 0.5d) {
x.d("MicroMsg.SnsOnlineVideoActivity", "dancy scale:%s", new Object[]{Float.valueOf(f)});
SnsOnlineVideoActivity.c(this.nZl, f);
SnsOnlineVideoActivity.c(this.nZl).setPivotX((float) (SnsOnlineVideoActivity.a(this.nZl).getWidth() / 2));
SnsOnlineVideoActivity.c(this.nZl).setPivotY((float) (SnsOnlineVideoActivity.a(this.nZl).getHeight() / 2));
SnsOnlineVideoActivity.c(this.nZl).setScaleX(f);
SnsOnlineVideoActivity.c(this.nZl).setScaleY(f);
SnsOnlineVideoActivity.c(this.nZl).setTranslationY(translationY);
SnsOnlineVideoActivity.h(this.nZl).setAlpha(f);
}
SnsOnlineVideoActivity.c(this.nZl, true);
}
if (translationY > 200.0f) {
SnsOnlineVideoActivity.b(this.nZl, false);
} else if (translationY > 10.0f) {
SnsOnlineVideoActivity.b(this.nZl, true);
}
if (translationY > 50.0f) {
SnsOnlineVideoActivity.c(this.nZl).setOnLongClickListener(null);
}
if (SnsOnlineVideoActivity.e(this.nZl) != null) {
SnsOnlineVideoActivity.e(this.nZl).recycle();
SnsOnlineVideoActivity.a(this.nZl, null);
}
if (SnsOnlineVideoActivity.b(this.nZl)) {
return true;
}
break;
}
return false;
}
}
|
package com.linda.framework.rpc.oio;
import com.linda.framework.rpc.RpcObject;
import com.linda.framework.rpc.exception.RpcException;
import com.linda.framework.rpc.exception.RpcNetExceptionHandler;
import com.linda.framework.rpc.net.AbstractRpcConnector;
import com.linda.framework.rpc.utils.RpcUtils;
import com.linda.framework.rpc.utils.SslUtils;
import org.apache.log4j.Logger;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
public class AbstractRpcOioConnector extends AbstractRpcConnector implements RpcNetExceptionHandler {
private Socket socket;
private DataInputStream dis;
private DataOutputStream dos;
private Logger logger = Logger.getLogger(AbstractRpcOioConnector.class);
public AbstractRpcOioConnector(AbstractRpcOioWriter writer) {
super(writer);
this.init();
}
public AbstractRpcOioConnector() {
this(null);
}
private void init() {
if (this.getRpcWriter() == null) {
this.setRpcWriter(new SimpleRpcOioWriter());
}
}
public AbstractRpcOioConnector(Socket socket, AbstractRpcOioWriter writer) {
this(writer);
this.socket = socket;
}
@Override
public void startService() {
super.startService();
try {
if (socket == null) {
socket = SslUtils.getSocketInstance(sslContext, sslMode);
socket.connect(new InetSocketAddress(this.getHost(), this.getPort()));
}
InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
remotePort = remoteAddress.getPort();
remoteHost = remoteAddress.getAddress().getHostAddress();
dis = new DataInputStream(socket.getInputStream());
dos = new DataOutputStream(socket.getOutputStream());
this.getRpcWriter().registerWrite(this);
this.getRpcWriter().startService();
new ClientThread().start();
this.fireStartNetListeners();
} catch (Exception e) {
this.handleNetException(e);
}
}
private class ClientThread extends Thread {
@Override
public void run() {
while (!stop) {
RpcObject rpc = RpcUtils.readDataRpc(dis, AbstractRpcOioConnector.this);
if (rpc != null) {
rpc.setHost(remoteHost);
rpc.setPort(remotePort);
rpc.setRpcContext(rpcContext);
fireCall(rpc);
}
}
}
}
@Override
public void stopService() {
super.stopService();
stop = true;
RpcUtils.close(dis, dos);
try {
socket.close();
} catch (IOException e) {
//do nothing
}
rpcContext.clear();
sendQueueCache.clear();
}
public DataOutputStream getOutputStream() {
return dos;
}
@Override
public void handleConnectorException(Exception e) {
this.getRpcWriter().unRegWrite(this);
this.stopService();
logger.error("connection caught io exception close");
throw new RpcException(e);
}
}
|
package com.wenxc.afdc;
import android.util.Log;
import com.wenxc.afdc.exception.FunctionException;
import com.wenxc.afdc.exception.FunctionNotFoundException;
import com.wenxc.afdc.function.ImplFunction;
import com.wenxc.afdc.inte.IFunction;
import java.util.HashMap;
import java.util.Map;
/**
* 函数类的管理,每个带有fragment的activity都有一个实例,以便依附其上的fragment调用函数
*/
public class FunctionHelper {
private boolean enableAFDC = false;
public FunctionHelper(boolean enableAFDC) {
Log.i(TAG, "FunctionHelper isConstroct");
this.enableAFDC = enableAFDC;
}
private final static String TAG = FunctionHelper.class.getSimpleName();
private Map<String, IFunction> functions;
public void addFunction(ImplFunction function) {
Log.i(TAG, "FunctionHelper addFunction()"+function);
if (function ==null) return;
if (functions == null) functions = new HashMap<>();
if (functions.containsKey(function.getFuntionName())) return;
functions.put(function.getFuntionName(), function);
}
public void invoke(String funcName) throws FunctionException {
Log.i(TAG, "FunctionHelper invoke()"+funcName);
if (!isEnableAFDC()){ Log.i(TAG, "the enableAFCallback is false, if you want to use invoke, please set enableAFCallback as true");return;}
if (funcName == null) return;
if (functions != null) {
IFunction IFunction = functions.get(funcName);
if (IFunction == null)
throw new FunctionNotFoundException("IFunction:" + funcName + "is not exist in functions map, has you add this IFunction in your activity");
IFunction.function();
} else {
throw new FunctionException("functions doesn't exist in activitys, has you init function before invoke");
}
}
public void invokeWithPrams(String funcName, Object... objects) throws FunctionException {
Log.i(TAG, "FunctionHelper invoke()"+funcName);
if (!isEnableAFDC()){ Log.i(TAG, "the enableAFCallback is false, if you want to use invoke, please set enableAFCallback as true");return;}
if (funcName == null) return;
if (functions != null) {
IFunction IFunction = functions.get(funcName);
if (IFunction == null)
throw new FunctionNotFoundException("IFunction:" + funcName + "is not exist in functions map, has you add this IFunction in your activity");
IFunction.functionWithPram(objects);
} else {
throw new FunctionException("functions doesn't exist in activitys, has you init function before invoke");
}
}
public <T> T invokeWithResult(String funcName) throws FunctionException {
Log.i(TAG, "FunctionHelper invoke()"+funcName);
if (!isEnableAFDC()){ Log.i(TAG, "the enableAFCallback is false, if you want to use invoke, please set enableAFCallback as true"); return null;}
if (funcName == null) return null;
if (functions != null) {
IFunction IFunction = functions.get(funcName);
if (IFunction == null)
throw new FunctionNotFoundException("IFunction:" + funcName + "is not exist in functions map, has you add this IFunction in your activity");
return (T) IFunction.functionWithResult();
} else {
throw new FunctionException("functions doesn't exist in activitys, has you init function before invoke");
}
}
public <T> T invokeWithPramAndResult(String funcName, Object... objects) throws FunctionException {
Log.i(TAG, "FunctionHelper invoke()"+funcName);
if (!isEnableAFDC()){ Log.i(TAG, "the enableAFCallback is false, if you want to use invoke, please set enableAFCallback as true"); return null;}
if (funcName == null) return null;
if (functions != null) {
IFunction IFunction = functions.get(funcName);
if (IFunction == null) {
throw new FunctionNotFoundException("IFunction:" + funcName + "is not exist in functions map, has you add this IFunction in your activity");
}
return (T) IFunction.functionWithPramAndResult(objects);
} else {
throw new FunctionException("functions doesn't exist in activitys, has you init function before invoke");
}
}
public boolean isEnableAFDC() {
return enableAFDC;
}
public void setEnableAFCallback(boolean enableAFCallback) {
this.enableAFDC = enableAFCallback;
}
}
|
package com.example.moneymanager.repositorydb;
import android.app.Application;
import androidx.lifecycle.LiveData;
import com.example.moneymanager.dao.ManagerDao;
import com.example.moneymanager.db.AppDatabase;
import com.example.moneymanager.dao.CategoryDao;
import com.example.moneymanager.db.Expenses;
import com.example.moneymanager.db.Income;
import com.example.moneymanager.pojos.Manager;
import java.util.List;
public class AppRepository {
private ManagerDao managerDao;
public AppRepository(Application application)
{
AppDatabase db=AppDatabase.getDatabase(application);
managerDao=db.managerDao();
;
}
public LiveData<List<Manager>> retrieveManagers(String type)
{
return managerDao.retrieveManagers(type);
}
public void insert(Manager manager)
{
managerDao.insertManager(manager);
}
public void saveManager(Manager manager)
{
}
}
|
package com.example.dell.geoquiz;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import static android.widget.Toast.*;
public class QuizActivity extends Activity {
private static final String TAG = "QuizActivity";
private static final String KEY_INDEX = "index";
private static final String KEY_ISCHEATER = "ischeater";
private Button mTrueButton;
private Button mFalseButton;
private Button mNextButton;
private Button mCheatButton;
private TextView mQuestionTextView;
private int mCurrentIndex = 0;
private TrueFalse[] mQuesstionBank = new TrueFalse[]{
new TrueFalse(R.string.first_question, true),
new TrueFalse(R.string.second_question, false),
new TrueFalse(R.string.third_question, true),
};
private boolean mIsCheater[] = new boolean[]{
false, false, false,};
private void updateQuestion(){
int question = mQuesstionBank[mCurrentIndex].getQuestion();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressed) {
boolean answerIsTrue = mQuesstionBank[mCurrentIndex].isTrueQuestion();
int messageResId = 0;
if(mIsCheater[mCurrentIndex]){
messageResId = R.string.judgment_toast;
}else {
if (answerIsTrue == userPressed) {
messageResId = R.string.true_toast;
} else {
messageResId = R.string.false_toast;
}
}
makeText(QuizActivity.this,
messageResId,
Toast.LENGTH_SHORT).show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate() called");
setContentView(R.layout.activity_quiz);
mQuestionTextView = (TextView)findViewById(R.id.question_text);
mTrueButton = (Button) findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button)findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkAnswer(false);
}
});
mCheatButton = (Button) findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(QuizActivity.this,CheatActivity.class);
boolean answerIs = mQuesstionBank[mCurrentIndex].isTrueQuestion();
i.putExtra(CheatActivity.EXTRA_ANSWER_IS, answerIs);
startActivityForResult(i, 0);
}
});
mNextButton = (Button) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuesstionBank.length;
updateQuestion();
}
});
if(savedInstanceState != null) {
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
mIsCheater = savedInstanceState.getBooleanArray(KEY_ISCHEATER);
}
updateQuestion();
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
savedInstanceState.putBooleanArray(KEY_ISCHEATER,mIsCheater);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(data == null){
return;
}
if(!mIsCheater[mCurrentIndex])
mIsCheater[mCurrentIndex] = data.getBooleanExtra(CheatActivity.EXTRA_ANSWER_SHOWN, false);
}
@Override
public void onStart(){
super.onStart();
Log.d(TAG, "onStart() called");
}
@Override
public void onPause(){
super.onPause();
Log.d(TAG,"onPause() called");
}
@Override
public void onResume(){
super.onResume();
Log.d(TAG,"onResume() called");
}
@Override
public void onStop(){
super.onStop();
Log.d(TAG,"onStop() called");
}
@Override
public void onDestroy(){
super.onDestroy();
Log.d(TAG,"onDestroy() called");
}
}
|
package com.scnuweb.domain;
/**
*
* @author yehao
* @date 2016年2月16日
* @comment 对应ExamItem 里面的 input 控件
*/
public class Input {
private String itemId;
private int orderNumber;
private String inputValue;
private int isValueSensitive;
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public int getOrderNumber() {
return orderNumber;
}
public void setOrderNumber(int orderNumber) {
this.orderNumber = orderNumber;
}
public String getInputValue() {
return inputValue;
}
public void setInputValue(String inputValue) {
this.inputValue = inputValue;
}
public int getIsValueSensitive() {
return isValueSensitive;
}
public void setIsValueSensitive(int isValueSensitive) {
this.isValueSensitive = isValueSensitive;
}
}
|
package com.example.shadowview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import com.lwx.shadowlibrary.layout.QMUILinearLayout;
import com.lwx.shadowlibrary.util.QMUIDisplayHelper;
import com.lwx.shadowlibrary.util.QMUILayoutHelper;
public class MainActivity extends AppCompatActivity {
private QMUILinearLayout mTestLayout;
private SeekBar testSeekbarAlpha;
private SeekBar testSeekbarElevation;
private Button shadowColorRed;
private Button shadowColorBlue;
private RadioGroup hideRadiusGroup;
private TextView mAlphaTv;
private TextView mElevationTv;
private float mShadowAlpha = 0.25f;
private int mShadowElevationDp = 14;
private int mRadius;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRadius = QMUIDisplayHelper.dp2px(this, 15);
initView();
initListener();
}
private void initView() {
mTestLayout = (QMUILinearLayout) findViewById(R.id.layout_for_test);
mAlphaTv = (TextView) findViewById(R.id.alpha_tv);
mElevationTv = (TextView) findViewById(R.id.elevation_tv);
testSeekbarAlpha = (SeekBar) findViewById(R.id.test_seekbar_alpha);
testSeekbarElevation = (SeekBar) findViewById(R.id.test_seekbar_elevation);
shadowColorRed = (Button) findViewById(R.id.shadow_color_red);
shadowColorBlue = (Button) findViewById(R.id.shadow_color_blue);
hideRadiusGroup = (RadioGroup) findViewById(R.id.hide_radius_group);
testSeekbarAlpha.setProgress((int) (mShadowAlpha * 100));
testSeekbarElevation.setProgress(mShadowElevationDp);
mTestLayout.setRadiusAndShadow(mRadius,
QMUIDisplayHelper.dp2px(MainActivity.this, mShadowElevationDp),
mShadowAlpha);
mTestLayout.setShadowColor(0xffffff00);
}
private void initListener() {
shadowColorRed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mTestLayout.setShadowColor(0xffff0000);
}
});
shadowColorBlue.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mTestLayout.setShadowColor(0xff0000ff);
}
});
testSeekbarAlpha.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
mShadowAlpha = progress * 1f / 100;
mAlphaTv.setText("alpha: " + mShadowAlpha);
mTestLayout.setRadiusAndShadow(mRadius,
QMUIDisplayHelper.dp2px(MainActivity.this, mShadowElevationDp),
mShadowAlpha);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
testSeekbarElevation.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
mShadowElevationDp = progress;
mElevationTv.setText("elevation: " + progress + "dp");
mTestLayout.setRadiusAndShadow(mRadius,
QMUIDisplayHelper.dp2px(MainActivity.this, mShadowElevationDp), mShadowAlpha);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
hideRadiusGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.hide_radius_none:
mTestLayout.setRadius(mRadius, QMUILayoutHelper.HIDE_RADIUS_SIDE_NONE);
break;
case R.id.hide_radius_left:
mTestLayout.setRadius(mRadius, QMUILayoutHelper.HIDE_RADIUS_SIDE_LEFT);
break;
case R.id.hide_radius_top:
mTestLayout.setRadius(mRadius, QMUILayoutHelper.HIDE_RADIUS_SIDE_TOP);
break;
case R.id.hide_radius_bottom:
mTestLayout.setRadius(mRadius, QMUILayoutHelper.HIDE_RADIUS_SIDE_BOTTOM);
break;
case R.id.hide_radius_right:
mTestLayout.setRadius(mRadius, QMUILayoutHelper.HIDE_RADIUS_SIDE_RIGHT);
break;
}
}
});
}
}
|
package com.spring.app.ws.repository;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
import com.spring.app.ws.io.entity.Users;
@Repository
public interface UserRepository extends PagingAndSortingRepository<Users, Long> {
public Users findByEmail(String email);
public Users findByUserId(String userId);
} |
package org.study.core.concurrency;
import java.util.concurrent.CountDownLatch;
/**
* Created by iovchynnikov on 9/25/2015.
*/
public class InterleavingDemo {
private int value;
public synchronized void increment() {
value++;
// int value = this.value;
// this.value = value +1;
}
public synchronized void decrement() {
value--;
}
@Override
public String toString() {
return "InterleavingDemo{" +
"value=" + value +
'}';
}
public static void main(String[] args) {
InterleavingDemo value = new InterleavingDemo();
CountDownLatch latch = new CountDownLatch(1);
Thread thread1 = new Thread(new PlusMinus(value, true, latch));
Thread thread2 = new Thread(new PlusMinus(value, false, latch));
System.out.println(value);
thread1.start();
thread2.start();
latch.countDown();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(value);
}
}
class PlusMinus implements Runnable {
private final InterleavingDemo interleaving;
private final boolean isIncrement;
private final CountDownLatch latch;
PlusMinus(InterleavingDemo interleaving, boolean isIncrement, CountDownLatch latch) {
this.interleaving = interleaving;
this.isIncrement = isIncrement;
this.latch = latch;
}
public void run() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
for (int i = 0; i < 1000; i++) {
if (isIncrement) {
increment();
} else {
decrement();
}
}
}
public void increment() {
interleaving.increment();
}
public void decrement() {
interleaving.decrement();
}
} |
package com.program9;
import com.google.common.base.Splitter;
import java.util.List;
class GuavaCuttingFunction {
static List<String> GuavaCutter(String s, int length){
return Splitter.fixedLength(length).splitToList(s);
}
}
|
package stepDefinition;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.openqa.selenium.Keys;
import pageObjects.KeyPressesPage;
import utils.TestContext;
import static org.testng.Assert.assertEquals;
public class KeysSteps
{
private TestContext testContext;
private KeyPressesPage keysPage;
public KeysSteps(TestContext context)
{
testContext = context;
keysPage = testContext.getPageObjectManager().getKeyPressesPage();
}
@When("^they input a backspace$")
public void theyInputABackspace()
{
keysPage.enterText("a" + Keys.BACK_SPACE);
}
@Then("^the page displays that backspace was pressed$")
public void thePageDisplaysThatBackspaceWasPressed()
{
assertEquals(keysPage.getResultText(), "You entered: BACK_SPACE");
}
}
|
package catalog.desktop.step_definitions;
import base.BaseSteps;
import catalog.desktop.pages.Catalog_page;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import homepage.desktop.pages.Home_Page;
import pdp.desktop.pages.Pdp_Page;
public class Catalog_Step extends BaseSteps {
@Given("^I visit the catalog page$")
public void iVisitTheCatalogPage() {
visit(Catalog_page.class);
on(Pdp_Page.class).switchToEnglish();
}
@And("^I search \"([^\"]*)\" in header$")
public void iSearchKeywordInHeader(String arg0) {
on(Home_Page.class).searchKeyword(arg0);
}
@When("^I apply the vertical brand filter$")
public void iApplyTheVerticalBrandFilter() {
on(Catalog_page.class).applyVerticalBrandFilter();
}
@When("^I apply the vertical size filter$")
public void iApplyTheVerticalSizeFilter() {
on(Catalog_page.class).applyVerticalSizeFilter();
}
@When("^I apply the vertical Color Family filter$")
public void iApplyTheVerticalColorFamilyFilter() {
on(Catalog_page.class).applyVerticalColorFilter();
}
@When("^I apply the vertical Price Range filter$")
public void iApplyTheVerticalPriceRangeFilter() {
on(Catalog_page.class).applyVerticalPriceFilter();
}
@Then("^\".*?\" Filter should be applied$")
public void filterShouldBeApplied() {
on(Catalog_page.class).assertFilterShouldBeApplied();
}
@And("^I remove \"([^\"]*)\" filters$")
public void iRemoveFilters(String arg0){
on(Catalog_page.class).clearFilters(arg0);
}
@Then("^\"([^\"]*)\" Filters should be removed$")
public void filtersShouldBeRemoved(String arg0) {
on(Catalog_page.class).assertFilterRemoved(arg0);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.