text
stringlengths 10
2.72M
|
|---|
package das.boot.config;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.flyway.FlywayDataSource;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@Configuration
public class PersistenceConfiguration {
//so this config class is all about java configuration and not autoconfiguration
@Bean
@ConfigurationProperties(prefix="spring.datasource")// this will tell the spring boot to take the properties with prefix "spring.datasource" from the application.properties
@Primary //so spring boot knows this is the default datasource JPA
public DataSource dataSource(){
return DataSourceBuilder.create().build();
}
/*
* the reason we created this config file for datasource because we want to have multiple datasource
* flyway and
*/
/*the annotation bean here will say the spring boot that the result of this method which is
a Datasource needs to be set up and stored as a spring bean in
spring context*/
// here below comes the second datasource
@Bean
@ConfigurationProperties(prefix="datasource.flyway")
@FlywayDataSource
public DataSource flywayDataSource(){// name of this two methods doesn matter but the prefix it matters should be the same as in application.properties
return DataSourceBuilder.create().build();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.hnote.Proxy;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
/**
*
* @author Zehao Jin
*/
public class Proxy {
private static final int PORT = 50001;
private ServerSocket serverSocket;
private static Proxy instance = new Proxy();
private Proxy() {
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException ex) {
}
}
public static Proxy getInstance(){
return instance;
}
public void run() {
while (true) {
try {
Socket socket = serverSocket.accept();
System.out.println("Get a connection.");
Frontend frontend = new Frontend(socket);
Backend backend = new Backend();
new CommunicationThread(backend, frontend).start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args){
Proxy.getInstance().run();
}
}
|
import java.util.Random;
public class KMeansPP{
ClusterPoint[] points;
int k;
CentroidPoint[] kpp_centroid;
KMeansPP(ClusterPoint[] points, int k){
this.points = points;
this.k = k;
this.kpp_centroid = new CentroidPoint[k];
}
public CentroidPoint[] KppCentroid(){
Random random = new Random();
double x = (0 + (9-0)*random.nextDouble() )/10;
int sampleIndex = (int)Math.ceil(x*points.length);
//testing
System.out.println("x:"+x);
System.out.println("sampleIndex:"+sampleIndex);
CentroidPoint firstCentroid = new CentroidPoint(points[sampleIndex]);
kpp_centroid[0] = firstCentroid;
for(int i=0; i<points.length; i++){
points[i].setDistance(Double.MAX_VALUE);
}
double[] cumulative = new double[points.length];
for(int j=1; j<k; j++){
for(int i=0; i<points.length; i++){
double d = points[i].sqDistanceTo(kpp_centroid[j-1]);
if(points[i].getDistance() > d){
points[i].setDistance(d);
}
}
cumulative[0] = points[0].getDistance();
for(int i=1; i<points.length; i++){
cumulative[i] = cumulative[i-1] + points[i].getDistance();
}
x = (0 + (9-0)*random.nextDouble() )/10;
double x2 = x*cumulative[cumulative.length-1];
if( x2 <= cumulative[0] ){
sampleIndex = 0;
} else {
for(int i=1; i<points.length; i++){
if(x2 > cumulative[i-1] && x2 <= cumulative[i]){
sampleIndex = i;
}
}
}
CentroidPoint kpp_cd = new CentroidPoint( points[sampleIndex] );
kpp_centroid[j] = kpp_cd;
}
return kpp_centroid;
}
}
|
package junit5test.test;
import io.qameta.allure.*;
import junit5test.Calculator;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@Epic("Epic 计算器项目")
@Feature("Feature 冒烟测试用例")
public class Demo05_1_Allure {
@Test
@Order(1)
@Description("Description")
@Story("Story")
@DisplayName("DisplayName")
@Severity(SeverityLevel.BLOCKER)
@Issue("www.baidu.com")
@Link(name = "Link",type = "mylink",url = "https://ceshiren.com/t/topic/7718/21")
public void testAssertAll(){
int firstResult = Calculator.add(6,6);
int secondResult = Calculator.subtract(10,9);
int thirdResult = Calculator.multipty(10,10);
System.out.println(firstResult);
System.out.println(secondResult);
System.out.println(thirdResult);
assertAll("",
()->assertEquals(12,firstResult),
()->assertEquals(1,secondResult),
()->assertEquals(100,thirdResult)
);
}
@Test
@Order(2)
public void addTest() {
int result = Calculator.add(5, 8);
System.out.println(result);
assertEquals(13,13,"断言结果正确");
}
@Test
@Order(3)
public void subtractTest() {
int result = Calculator.subtract(8, 5);
System.out.println(result);
assertEquals(3,3,"断言结果正确");
}
@Test
@Order(4)
public void muliptyTest() {
int result = Calculator.multipty(5, 8);
System.out.println(result);
assertEquals(40,40,"断言结果正确");
}
@Test
@Order(5)
public void divideTest() {
int result = Calculator.divide(10, 5);
System.out.println(result);
assertEquals(2,2,"断言结果正确");
}
@BeforeEach
public void clearTest(){
Calculator.clear();
}
@Test
@Order(6)
public void sumTest() throws InterruptedException {
int result = Calculator.sum(5);
System.out.println(result);
result = Calculator.sum(5);
System.out.println(result);
result = Calculator.sum(5);
System.out.println(result);
result = Calculator.sum(5);
System.out.println(result);
assertEquals(5,5,"断言结果正确");
assertEquals(10,10,"断言结果正确");
assertEquals(15,15,"断言结果正确");
assertEquals(20,20,"断言结果正确");
}
}
|
/**
*
*/
package com.ee.mavenlearning.com.ee.gmail;
import java.io.IOException;
import java.net.MalformedURLException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* @author paresh
*
*/
public class signin {
WebDriver wd;
drivers.BrowserType type=drivers.BrowserType.CHROME;
elements we ;
//String str="hjhjvhv";
String str=null;
public String url="http://www.gmail.com";
@BeforeMethod
public void setup() throws MalformedURLException{
wd = drivers.Browser(type,true);
wd.get("http://www.gmail.com");
we= PageFactory.initElements(wd, elements.class);
}
@Test (dataProviderClass=dataprovider.class,dataProvider="info")
public void sign_in(String user,String pass){
String str=null;
we.sign(user,pass);
if(str != null && !str.isEmpty()){
we.sign_error(str);
}else{
we.check_error();
}
}
@AfterTest
public void close() throws InterruptedException{
//we.logout();
Thread.sleep(1000);
// wd.quit();
}
}
|
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class HTTPGetServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out;
response.setContentType("text/html");
out = response.getWriter();
StringBuffer buf = new StringBuffer();
buf.append("<html><head><title>");
buf.append("Simple Servlet Example");
buf.append("</title></head><body>");
buf.append("<h1>It actually worked lol</h1>");
buf.append("</body></html>");
out.println(buf.toString());
out.close();
}
}
|
package com.zhaojun.socket;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @auther zhaojun0193
* @create 2017/9/20
*/
public class SocketServer {
public static void main(String[] args) {
try {
//创建socketServer 并绑定端口
ServerSocket socketServer = new ServerSocket();
socketServer.bind(new InetSocketAddress("127.0.0.1",8888));
while (true){
Socket socket = socketServer.accept();
new Thread(() -> {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = bufferedReader.readLine();
System.out.println(line);
PrintWriter printWriter = new PrintWriter(outputStream);
printWriter.print(line +": to server");
printWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try{
if(outputStream != null){
outputStream.close();
}
if(inputStream != null){
inputStream.close();
}
if(socket != null){
socket.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
/**
* This class is generated by jOOQ
*/
package schema.tables.records;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record3;
import org.jooq.Row3;
import org.jooq.impl.UpdatableRecordImpl;
import schema.tables.DjangoContentType;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class DjangoContentTypeRecord extends UpdatableRecordImpl<DjangoContentTypeRecord> implements Record3<Integer, String, String> {
private static final long serialVersionUID = -750427119;
/**
* Setter for <code>bitnami_edx.django_content_type.id</code>.
*/
public void setId(Integer value) {
set(0, value);
}
/**
* Getter for <code>bitnami_edx.django_content_type.id</code>.
*/
public Integer getId() {
return (Integer) get(0);
}
/**
* Setter for <code>bitnami_edx.django_content_type.app_label</code>.
*/
public void setAppLabel(String value) {
set(1, value);
}
/**
* Getter for <code>bitnami_edx.django_content_type.app_label</code>.
*/
public String getAppLabel() {
return (String) get(1);
}
/**
* Setter for <code>bitnami_edx.django_content_type.model</code>.
*/
public void setModel(String value) {
set(2, value);
}
/**
* Getter for <code>bitnami_edx.django_content_type.model</code>.
*/
public String getModel() {
return (String) get(2);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record3 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row3<Integer, String, String> fieldsRow() {
return (Row3) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row3<Integer, String, String> valuesRow() {
return (Row3) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() {
return DjangoContentType.DJANGO_CONTENT_TYPE.ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field2() {
return DjangoContentType.DJANGO_CONTENT_TYPE.APP_LABEL;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field3() {
return DjangoContentType.DJANGO_CONTENT_TYPE.MODEL;
}
/**
* {@inheritDoc}
*/
@Override
public Integer value1() {
return getId();
}
/**
* {@inheritDoc}
*/
@Override
public String value2() {
return getAppLabel();
}
/**
* {@inheritDoc}
*/
@Override
public String value3() {
return getModel();
}
/**
* {@inheritDoc}
*/
@Override
public DjangoContentTypeRecord value1(Integer value) {
setId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public DjangoContentTypeRecord value2(String value) {
setAppLabel(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public DjangoContentTypeRecord value3(String value) {
setModel(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public DjangoContentTypeRecord values(Integer value1, String value2, String value3) {
value1(value1);
value2(value2);
value3(value3);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached DjangoContentTypeRecord
*/
public DjangoContentTypeRecord() {
super(DjangoContentType.DJANGO_CONTENT_TYPE);
}
/**
* Create a detached, initialised DjangoContentTypeRecord
*/
public DjangoContentTypeRecord(Integer id, String appLabel, String model) {
super(DjangoContentType.DJANGO_CONTENT_TYPE);
set(0, id);
set(1, appLabel);
set(2, model);
}
}
|
package edu.mit.cci.simulation.ice.beans;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import javax.faces.event.ActionEvent;
import org.apache.commons.io.IOUtils;
import edu.mit.cci.simulation.excel.server.ExcelSimulation;
import edu.mit.cci.simulation.excel.server.ExcelVariable;
import edu.mit.cci.simulation.model.DataType;
import edu.mit.cci.simulation.model.DefaultSimulation;
import edu.mit.cci.simulation.model.DefaultVariable;
public class Simulation {
private String name = "Temp";//TODO: Delete
private String description = "temp";//TODO: Delete
private String url;
private String indepVarName = "Time";
private String indepVarUnits = "Year";
private String indepVarLabels = "Year";
private String indepVarDescription = "Time in Years";
private String inputVarName = "CO2";//TODO: delete
private String inputVarUnits = "ppm";//TODO: delete
private String inputVarLabels = "CO2";//TODO: delete
private String inputVarDescription = "CO2 Emission";//TODO: delete
private String outputVarName = "GDP";//TODO: delete
private String outputVarUnits = "%Change";//TODO: delete
private String outputVarLabels = "GDP";//TODO: delete
private String outputVarDescription = "Change in GDP"; //TODO: delete
private ResponseSurface responseSurface;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getIndepVarName() {
return indepVarName;
}
public void setIndepVarName(String indepVarName) {
this.indepVarName = indepVarName;
}
public String getIndepVarUnits() {
return indepVarUnits;
}
public void setIndepVarUnits(String indepVarUnits) {
this.indepVarUnits = indepVarUnits;
}
public String getIndepVarLabels() {
return indepVarLabels;
}
public void setIndepVarLabels(String indepVarLabels) {
this.indepVarLabels = indepVarLabels;
}
public String getIndepVarDescription() {
return indepVarDescription;
}
public void setIndepVarDescription(String indepVarDescription) {
this.indepVarDescription = indepVarDescription;
}
public String getInputVarName() {
return inputVarName;
}
public void setInputVarName(String inputVarName) {
this.inputVarName = inputVarName;
}
public String getInputVarUnits() {
return inputVarUnits;
}
public void setInputVarUnits(String inputVarUnits) {
this.inputVarUnits = inputVarUnits;
}
public String getInputVarLabels() {
return inputVarLabels;
}
public void setInputVarLabels(String inputVarLabels) {
this.inputVarLabels = inputVarLabels;
}
public String getInputVarDescription() {
return inputVarDescription;
}
public void setInputVarDescription(String inputVarDescription) {
this.inputVarDescription = inputVarDescription;
}
public String getOutputVarName() {
return outputVarName;
}
public void setOutputVarName(String outputVarName) {
this.outputVarName = outputVarName;
}
public String getOutputVarUnits() {
return outputVarUnits;
}
public void setOutputVarUnits(String outputVarUnits) {
this.outputVarUnits = outputVarUnits;
}
public String getOutputVarLabels() {
return outputVarLabels;
}
public void setOutputVarLabels(String outputVarLabels) {
this.outputVarLabels = outputVarLabels;
}
public String getOutputVarDescription() {
return outputVarDescription;
}
public void setOutputVarDescription(String outputVarDescrption) {
this.outputVarDescription = outputVarDescrption;
}
public ResponseSurface getResponseSurface() {
return responseSurface;
}
public void setResponseSurface(ResponseSurface responseSurface) {
this.responseSurface = responseSurface;
}
//Create Simulation
public void createSimulation(ActionEvent e) throws FileNotFoundException, IOException{
System.out.println("Entering CreateSimulation in Simulation...");//TODO: Delete
//Step1: Create Default Simulation
DefaultSimulation sim = (DefaultSimulation) createBaseSim();
System.out.println("Base Simulation Created");//TODO: Delete
//Step2: Create Excel Simulation
ExcelSimulation esim = new ExcelSimulation();
esim.setSimulation(sim);
System.out.println("Excel Simulation Created");//TODO: Delete
//Step3: Set Creation date for Excel Simulation
esim.setCreation(new Date());
System.out.println("Date inserted to Excel Simulation");//TODO: Delete
//Step4: Excel Simulation File.
esim.setFile(IOUtils.toByteArray(new FileInputStream(responseSurface.getRsPath())));
System.out.println("File Path Set to Excel Simulation. Path: " + responseSurface.getRsPath());//TODO: Delete
System.out.println("Excel IOArity is: " + responseSurface.getExcelIOArity());//TODO: Delete
//Step5: Add data from Excel to Simulation
//5.0: Generate Cell Info
Integer startRow = new Integer(3);
Integer lastRow = startRow + responseSurface.getExcelIOArity();
String col1 = "A" + startRow.toString() + ":A" + lastRow.toString();
String col2 = "B" + startRow.toString() + ":B" + lastRow.toString();
String col3 = "C" + startRow.toString() + ":C" + lastRow.toString();
String col4 = "D" + startRow.toString() + ":D" + lastRow.toString();
esim.getInputs().add(new ExcelVariable(esim, sim.findVariableWithExternalName(indepVarName, true), "Inputs_Outputs", col1));
esim.getInputs().add(new ExcelVariable(esim, sim.findVariableWithExternalName(inputVarName, true), "Inputs_Outputs", col2));
esim.getInputs().add(new ExcelVariable(esim, sim.findVariableWithExternalName(indepVarName, false), "Inputs_Outputs", col3));
esim.getInputs().add(new ExcelVariable(esim, sim.findVariableWithExternalName(outputVarName, false), "Inputs_Outputs", col4));
//Step6: Persist Excel Simulation
esim.persist();
//Step7: Set URL to simulation
sim.setUrl(ExcelSimulation.EXCEL_URL+esim.getId());
//Step8: Persist Simulation
sim.persist();
test(sim);//TODO: Delete
}
//TODO:DELETE (TESTING)
private void test(DefaultSimulation sim){
System.out.println("Simulation URL: " + sim.getUrl());
System.out.println("Simulation Input Variables: " + sim.getInputs().toString());
System.out.println("Simulation Output Variables: " + sim.getOutputs().toString());
}
private DefaultSimulation createBaseSim() {
//Create Default Simulation
DefaultSimulation sim = new DefaultSimulation();
//Add Basic info: name, description, creation, url, version,
sim.setName(this.name);
sim.setDescription(this.description);
sim.setCreated(new Date());
sim.setUrl(/**/"");
sim.setSimulationVersion(1l);
sim.persist();
//Mapping necessary?
//ADDVARS TODO
System.out.println("Default Simulation Created...");//TODO: Delete
//Add IndepVar
System.out.println("adding Variables"); //TODO: Delete
DefaultVariable indepVar = new DefaultVariable(indepVarName,indepVarDescription, responseSurface.getExcelIOArity()); //Max Min?
DefaultVariable inputDepVar = new DefaultVariable(inputVarName, inputVarDescription, responseSurface.getExcelIOArity());
DefaultVariable outputDepVar = new DefaultVariable(outputVarName, outputVarDescription, responseSurface.getExcelIOArity());
System.out.println("Adding Variables Part One Finished");//TODO: Delete
indepVar.setUnits(indepVarUnits);
inputDepVar.setUnits(inputVarUnits);
outputDepVar.setUnits(outputVarUnits);
System.out.println("Addinv variable units");//TODO: Delete
indepVar.setLabels(indepVarLabels);
inputDepVar.setLabels(inputVarLabels);
outputDepVar.setLabels(outputVarLabels);
System.out.println("Adding variable labels");//TODO: Delete
//TODO: indepVar.setDefaultValue();
//indepVar.setExternalName(indepVarName);
//inputDepVar.setExternalName(inputVarName);
//outputDepVar.setExternalName(outputVarName);//external name = internal Name
indepVar.setDataType(DataType.NUM);
inputDepVar.setDataType(DataType.NUM);
outputDepVar.setDataType(DataType.NUM);
System.out.println("Done Editing Variables. Part Two finished. ");//TODO: Delete
indepVar.persist();
inputDepVar.persist();
outputDepVar.persist();
System.out.println("Finished Persisting");//TODO: Delete
sim.getInputs().add(indepVar);
sim.getInputs().add(inputDepVar);
sim.getOutputs().add(indepVar);
sim.getOutputs().add(outputDepVar);
System.out.println("finished adding variable to simulation. ");//TODO: Delete
sim.persist();
return sim;
}
}
|
package com.example.candace.pslapplication;
import java.io.Serializable;
import java.util.ArrayList;
public class QuizModel implements Serializable {
private String name;
private ArrayList<LevelModel> list;
public QuizModel(String n, ArrayList<LevelModel> list){
this.name = n;
this.list = list;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList<LevelModel> getList() {
return list;
}
public void setList(ArrayList<LevelModel> list) {
this.list = list;
}
}
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Functional tests for SIMD vectorization.
*/
public class Main {
static boolean[] a;
//
// Arithmetic operations.
//
/// CHECK-START: void Main.and(boolean) loop_optimization (before)
/// CHECK-DAG: ArrayGet loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
//
/// CHECK-START-{ARM,ARM64}: void Main.and(boolean) loop_optimization (after)
/// CHECK-DAG: VecLoad loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: VecAnd loop:<<Loop>> outer_loop:none
/// CHECK-DAG: VecStore loop:<<Loop>> outer_loop:none
static void and(boolean x) {
for (int i = 0; i < 128; i++)
a[i] &= x; // NOTE: bitwise and, not the common &&
}
/// CHECK-START: void Main.or(boolean) loop_optimization (before)
/// CHECK-DAG: ArrayGet loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
//
/// CHECK-START-{ARM,ARM64}: void Main.or(boolean) loop_optimization (after)
/// CHECK-DAG: VecLoad loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: VecOr loop:<<Loop>> outer_loop:none
/// CHECK-DAG: VecStore loop:<<Loop>> outer_loop:none
static void or(boolean x) {
for (int i = 0; i < 128; i++)
a[i] |= x; // NOTE: bitwise or, not the common ||
}
/// CHECK-START: void Main.xor(boolean) loop_optimization (before)
/// CHECK-DAG: ArrayGet loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
//
/// CHECK-START-{ARM,ARM64}: void Main.xor(boolean) loop_optimization (after)
/// CHECK-DAG: VecLoad loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: VecXor loop:<<Loop>> outer_loop:none
/// CHECK-DAG: VecStore loop:<<Loop>> outer_loop:none
static void xor(boolean x) {
for (int i = 0; i < 128; i++)
a[i] ^= x; // NOTE: bitwise xor
}
/// CHECK-START: void Main.not() loop_optimization (before)
/// CHECK-DAG: ArrayGet loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: ArraySet loop:<<Loop>> outer_loop:none
//
/// CHECK-START-{ARM,ARM64}: void Main.not() loop_optimization (after)
/// CHECK-DAG: VecLoad loop:<<Loop:B\d+>> outer_loop:none
/// CHECK-DAG: VecNot loop:<<Loop>> outer_loop:none
/// CHECK-DAG: VecStore loop:<<Loop>> outer_loop:none
static void not() {
for (int i = 0; i < 128; i++)
a[i] = !a[i];
}
//
// Test Driver.
//
public static void main(String[] args) {
// Set up.
a = new boolean[128];
for (int i = 0; i < 128; i++) {
a[i] = (i & 1) == 0;
}
// Arithmetic operations.
and(true);
for (int i = 0; i < 128; i++) {
expectEquals((i & 1) == 0, a[i], "and-true");
}
xor(true);
for (int i = 0; i < 128; i++) {
expectEquals((i & 1) != 0, a[i], "xor-true");
}
xor(false);
for (int i = 0; i < 128; i++) {
expectEquals((i & 1) != 0, a[i], "xor-false");
}
not();
for (int i = 0; i < 128; i++) {
expectEquals((i & 1) == 0, a[i], "not");
}
or(true);
for (int i = 0; i < 128; i++) {
expectEquals(true, a[i], "or-true");
}
and(false);
for (int i = 0; i < 128; i++) {
expectEquals(false, a[i], "and-false");
}
or(false);
for (int i = 0; i < 128; i++) {
expectEquals(false, a[i], "or-false");
}
// Done.
System.out.println("passed");
}
private static void expectEquals(boolean expected, boolean result, String action) {
if (expected != result) {
throw new Error("Expected: " + expected + ", found: " + result + " for " + action);
}
}
}
|
package at.fhv.itm14.fhvgis.persistence.dao.interfaces.raw;
import at.fhv.itm14.fhvgis.domain.Device;
import at.fhv.itm14.fhvgis.domain.raw.RawMotionValue;
import at.fhv.itm14.fhvgis.persistence.dao.interfaces.IGenericDao;
import at.fhv.itm14.fhvgis.persistence.exceptions.PersistenceException;
import java.util.List;
import java.util.UUID;
public interface IRawMotionValuesDao extends IGenericDao<RawMotionValue> {
void deleteMotionValuesOfDevice(Device device) throws PersistenceException;
List<RawMotionValue> findRawMotionValuesInRangeOfDevice(UUID deviceid, long startStamp, long endStamp) throws PersistenceException;
}
|
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.testfixture.jndi;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NameNotFoundException;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.OperationNotSupportedException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
/**
* Copy of the standard {@link org.springframework.mock.jndi.SimpleNamingContext}
* for testing purposes.
*
* <p>Simple implementation of a JNDI naming context.
* Only supports binding plain Objects to String names.
* Mainly for test environments, but also usable for standalone applications.
*
* <p>This class is not intended for direct usage by applications, although it
* can be used for example to override JndiTemplate's {@code createInitialContext}
* method in unit tests. Typically, SimpleNamingContextBuilder will be used to
* set up a JVM-level JNDI environment.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @see SimpleNamingContextBuilder
* @see org.springframework.jndi.JndiTemplate#createInitialContext
*/
public class SimpleNamingContext implements Context {
private final Log logger = LogFactory.getLog(getClass());
private final String root;
private final Hashtable<String, Object> boundObjects;
private final Hashtable<String, Object> environment = new Hashtable<>();
/**
* Create a new naming context.
*/
public SimpleNamingContext() {
this("");
}
/**
* Create a new naming context with the given naming root.
*/
public SimpleNamingContext(String root) {
this.root = root;
this.boundObjects = new Hashtable<>();
}
/**
* Create a new naming context with the given naming root,
* the given name/object map, and the JNDI environment entries.
*/
public SimpleNamingContext(
String root, Hashtable<String, Object> boundObjects, @Nullable Hashtable<String, Object> env) {
this.root = root;
this.boundObjects = boundObjects;
if (env != null) {
this.environment.putAll(env);
}
}
// Actual implementations of Context methods follow
@Override
public NamingEnumeration<NameClassPair> list(String root) throws NamingException {
if (logger.isDebugEnabled()) {
logger.debug("Listing name/class pairs under [" + root + "]");
}
return new NameClassPairEnumeration(this, root);
}
@Override
public NamingEnumeration<Binding> listBindings(String root) throws NamingException {
if (logger.isDebugEnabled()) {
logger.debug("Listing bindings under [" + root + "]");
}
return new BindingEnumeration(this, root);
}
/**
* Look up the object with the given name.
* <p>Note: Not intended for direct use by applications.
* Will be used by any standard InitialContext JNDI lookups.
* @throws javax.naming.NameNotFoundException if the object could not be found
*/
@Override
public Object lookup(String lookupName) throws NameNotFoundException {
String name = this.root + lookupName;
if (logger.isDebugEnabled()) {
logger.debug("Static JNDI lookup: [" + name + "]");
}
if (name.isEmpty()) {
return new SimpleNamingContext(this.root, this.boundObjects, this.environment);
}
Object found = this.boundObjects.get(name);
if (found == null) {
if (!name.endsWith("/")) {
name = name + "/";
}
for (String boundName : this.boundObjects.keySet()) {
if (boundName.startsWith(name)) {
return new SimpleNamingContext(name, this.boundObjects, this.environment);
}
}
throw new NameNotFoundException(
"Name [" + this.root + lookupName + "] not bound; " + this.boundObjects.size() + " bindings: [" +
StringUtils.collectionToDelimitedString(this.boundObjects.keySet(), ",") + "]");
}
return found;
}
@Override
public Object lookupLink(String name) throws NameNotFoundException {
return lookup(name);
}
/**
* Bind the given object to the given name.
* Note: Not intended for direct use by applications
* if setting up a JVM-level JNDI environment.
* Use SimpleNamingContextBuilder to set up JNDI bindings then.
* @see org.springframework.context.testfixture.jndi.SimpleNamingContextBuilder#bind
*/
@Override
public void bind(String name, Object obj) {
if (logger.isInfoEnabled()) {
logger.info("Static JNDI binding: [" + this.root + name + "] = [" + obj + "]");
}
this.boundObjects.put(this.root + name, obj);
}
@Override
public void unbind(String name) {
if (logger.isInfoEnabled()) {
logger.info("Static JNDI remove: [" + this.root + name + "]");
}
this.boundObjects.remove(this.root + name);
}
@Override
public void rebind(String name, Object obj) {
bind(name, obj);
}
@Override
public void rename(String oldName, String newName) throws NameNotFoundException {
Object obj = lookup(oldName);
unbind(oldName);
bind(newName, obj);
}
@Override
public Context createSubcontext(String name) {
String subcontextName = this.root + name;
if (!subcontextName.endsWith("/")) {
subcontextName += "/";
}
Context subcontext = new SimpleNamingContext(subcontextName, this.boundObjects, this.environment);
bind(name, subcontext);
return subcontext;
}
@Override
public void destroySubcontext(String name) {
unbind(name);
}
@Override
public String composeName(String name, String prefix) {
return prefix + name;
}
@Override
public Hashtable<String, Object> getEnvironment() {
return this.environment;
}
@Override
@Nullable
public Object addToEnvironment(String propName, Object propVal) {
return this.environment.put(propName, propVal);
}
@Override
public Object removeFromEnvironment(String propName) {
return this.environment.remove(propName);
}
@Override
public void close() {
}
// Unsupported methods follow: no support for javax.naming.Name
@Override
public NamingEnumeration<NameClassPair> list(Name name) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public Object lookup(Name name) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public Object lookupLink(Name name) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public void bind(Name name, Object obj) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public void unbind(Name name) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public void rebind(Name name, Object obj) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public void rename(Name oldName, Name newName) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public Context createSubcontext(Name name) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public void destroySubcontext(Name name) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public String getNameInNamespace() throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public NameParser getNameParser(Name name) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public NameParser getNameParser(String name) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@Override
public Name composeName(Name name, Name prefix) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
private abstract static class AbstractNamingEnumeration<T> implements NamingEnumeration<T> {
private final Iterator<T> iterator;
private AbstractNamingEnumeration(SimpleNamingContext context, String proot) throws NamingException {
if (!proot.isEmpty() && !proot.endsWith("/")) {
proot = proot + "/";
}
String root = context.root + proot;
Map<String, T> contents = new HashMap<>();
for (String boundName : context.boundObjects.keySet()) {
if (boundName.startsWith(root)) {
int startIndex = root.length();
int endIndex = boundName.indexOf('/', startIndex);
String strippedName =
(endIndex != -1 ? boundName.substring(startIndex, endIndex) : boundName.substring(startIndex));
if (!contents.containsKey(strippedName)) {
try {
contents.put(strippedName, createObject(strippedName, context.lookup(proot + strippedName)));
}
catch (NameNotFoundException ex) {
// cannot happen
}
}
}
}
if (contents.size() == 0) {
throw new NamingException("Invalid root: [" + context.root + proot + "]");
}
this.iterator = contents.values().iterator();
}
protected abstract T createObject(String strippedName, Object obj);
@Override
public boolean hasMore() {
return this.iterator.hasNext();
}
@Override
public T next() {
return this.iterator.next();
}
@Override
public boolean hasMoreElements() {
return this.iterator.hasNext();
}
@Override
public T nextElement() {
return this.iterator.next();
}
@Override
public void close() {
}
}
private static final class NameClassPairEnumeration extends AbstractNamingEnumeration<NameClassPair> {
private NameClassPairEnumeration(SimpleNamingContext context, String root) throws NamingException {
super(context, root);
}
@Override
protected NameClassPair createObject(String strippedName, Object obj) {
return new NameClassPair(strippedName, obj.getClass().getName());
}
}
private static final class BindingEnumeration extends AbstractNamingEnumeration<Binding> {
private BindingEnumeration(SimpleNamingContext context, String root) throws NamingException {
super(context, root);
}
@Override
protected Binding createObject(String strippedName, Object obj) {
return new Binding(strippedName, obj);
}
}
}
|
package core.event.handlers.hero;
import cards.equipments.Equipment.EquipmentType;
import core.event.game.DodgeTargetEquipmentCheckEvent;
import core.event.handlers.AbstractEventHandler;
import core.heroes.skills.ZhugeliangTaichiOriginalHeroSkill;
import core.player.PlayerCompleteServer;
import core.server.game.BattleLog;
import core.server.game.GameDriver;
import core.server.game.GameInternal;
import core.server.game.controllers.AbstractSingleStageGameController;
import core.server.game.controllers.equipment.TaichiFormationGameController;
import exceptions.server.game.GameFlowInterruptedException;
public class ZhugeliangTaichiDodgeEquipmentCheckEventHandler extends AbstractEventHandler<DodgeTargetEquipmentCheckEvent> {
public ZhugeliangTaichiDodgeEquipmentCheckEventHandler(PlayerCompleteServer player) {
super(player);
}
@Override
public Class<DodgeTargetEquipmentCheckEvent> getEventClass() {
return DodgeTargetEquipmentCheckEvent.class;
}
@Override
protected void handleIfActivated(DodgeTargetEquipmentCheckEvent event, GameDriver game) throws GameFlowInterruptedException {
if (!this.player.getPlayerInfo().equals(event.getTarget())) {
return;
}
if (this.player.isEquipped(EquipmentType.SHIELD)) {
return;
}
game.pushGameController(new AbstractSingleStageGameController() {
@Override
protected void handleOnce(GameInternal game) throws GameFlowInterruptedException {
game.pushGameController(new TaichiFormationGameController(event.controller, player));
game.log(BattleLog.playerASkillPassivelyTriggered(player, new ZhugeliangTaichiOriginalHeroSkill(), ""));
}
});
}
}
|
package com.citibank.ods.modules.client.knowledgeexp.form;
@SuppressWarnings("serial")
public class KnowledgeExperienceListForm extends BaseKnowledgeExperienceListForm {
}
|
package com.zc.pivas.statistics.service;
import com.zc.pivas.statistics.bean.prescription.*;
import java.util.List;
/**
* 药单统计Service
*
* @author jagger
* @version 1.0
*/
public interface PrescriptionService {
/**
* 按批次查询药单状态
*
* @param medicSingleSearch
* @return
*/
BatchStatusBarBean queryBatchStatusBar(PrescriptionSearchBean medicSingleSearch);
List<YDBatchPieBean> queryBatchPieList(PrescriptionSearchBean medicSingleSearch);
List<PrescriptionStatusBean> queryBatchStatusListByID(PrescriptionSearchBean medicSingleSearch);
/**
* 按病区查询药单状态
*
* @param medicSingleSearch
* @return
*/
DeptStatusBarBean queryDeptStatusBar(PrescriptionSearchBean medicSingleSearch);
List<YDDeptPieBean> queryDeptPieList(PrescriptionSearchBean medicSingleSearch);
List<PrescriptionStatusBean> queryDeptStatusListByName(PrescriptionSearchBean medicSingleSearch);
}
|
package io.github.cottonmc.libcd.api.util;
// Copied from Jankson-Fabric 2.x
/**
* A DynamicOps instance for Jankson. Loosely based on Mojang's JsonOps for Gson.
*
* @deprecated Use upstream JanksonOps instead.
*/
@Deprecated
public class JanksonOps extends io.github.cottonmc.jankson.JanksonOps {
public static final JanksonOps INSTANCE = new JanksonOps(false);
protected JanksonOps(boolean compressed) {
super(compressed);
}
}
|
package com.libangliang.supermarket.Prevalent;
import com.libangliang.supermarket.Model.Users;
public class Prevalent {
//forget password and remember
public static Users currentOnlineUser;
public static final String userPhoneKey = "UserPhone";
public static final String userPasswordKey = "UserPassword";
}
|
import info.gridworld.actor.Critter;
import info.gridworld.actor.Actor;
import java.util.ArrayList;
import info.gridworld.grid.Location;
import java.awt.Color;
public class BlusterCritter extends Critter {
private int c;
public BlusterCritter (){
super();
c = 5;
}
public ArrayList<Actor> getActors(){
return getGrid().getNeighbors(getLocation());
//We have to somehow modify this to get all neighbors within two boxes.
}
public void processActors (ArrayList<Actor> actors) {
int crowd = 0;
for (Actor a : actors)
if (a instanceof Critter)
crowd++;
if (crowd < c)
brighten();
else
darken();
}
private void brighten(){
Color c = getColor(); //color of itself
int red = (int) (c.getRed() * 1.05);
int green = (int) (c.getGreen() * 1.05);
int blue = (int) (c.getBlue() * 1.05);
setColor(new Color(red, green, blue)); //sets the color of itself
}
//from Chameleon Critter
private void darken(){
Color c = getColor(); //color of itself
int red = (int) (c.getRed() * 0.95);
int green = (int) (c.getGreen() * 0.95);
int blue = (int) (c.getBlue() * 0.95);
setColor(new Color(red, green, blue)); //sets the color of itself
}
}
|
/**
* Copyright (C) Alibaba Cloud Computing, 2012
* All rights reserved.
*
* 版权所有 (C)阿里巴巴云计算,2012
*/
package com.aliyun.oss;
import static com.aliyun.oss.common.utils.CodingUtils.assertParameterNotNull;
import static com.aliyun.oss.common.utils.CodingUtils.assertStringNotNullOrEmpty;
import static com.aliyun.oss.internal.OSSUtils.OSS_RESOURCE_MANAGER;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.aliyun.oss.common.auth.ServiceCredentials;
import com.aliyun.oss.common.auth.ServiceSignature;
import com.aliyun.oss.common.comm.DefaultServiceClient;
import com.aliyun.oss.common.comm.RequestMessage;
import com.aliyun.oss.common.comm.ResponseMessage;
import com.aliyun.oss.common.comm.ServiceClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.common.utils.DateUtil;
import com.aliyun.oss.common.utils.HttpHeaders;
import com.aliyun.oss.common.utils.HttpUtil;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.internal.CORSOperation;
import com.aliyun.oss.internal.OSSBucketOperation;
import com.aliyun.oss.internal.OSSConstants;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.internal.OSSMultipartOperation;
import com.aliyun.oss.internal.OSSObjectOperation;
import com.aliyun.oss.internal.OSSUtils;
import com.aliyun.oss.internal.SignUtils;
import com.aliyun.oss.model.AbortMultipartUploadRequest;
import com.aliyun.oss.model.AccessControlList;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.BucketList;
import com.aliyun.oss.model.BucketLoggingResult;
import com.aliyun.oss.model.BucketReferer;
import com.aliyun.oss.model.BucketWebsiteResult;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CompleteMultipartUploadRequest;
import com.aliyun.oss.model.CompleteMultipartUploadResult;
import com.aliyun.oss.model.CopyObjectRequest;
import com.aliyun.oss.model.CopyObjectResult;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.InitiateMultipartUploadRequest;
import com.aliyun.oss.model.InitiateMultipartUploadResult;
import com.aliyun.oss.model.LifecycleRule;
import com.aliyun.oss.model.ListBucketsRequest;
import com.aliyun.oss.model.ListMultipartUploadsRequest;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.ListPartsRequest;
import com.aliyun.oss.model.MultipartUploadListing;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.OptionsRequest;
import com.aliyun.oss.model.PartListing;
import com.aliyun.oss.model.PolicyConditions;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.model.SetBucketCORSRequest;
import com.aliyun.oss.model.SetBucketCORSRequest.CORSRule;
import com.aliyun.oss.model.SetBucketLifecycleRequest;
import com.aliyun.oss.model.SetBucketLoggingRequest;
import com.aliyun.oss.model.SetBucketWebsiteRequest;
import com.aliyun.oss.model.UploadPartCopyRequest;
import com.aliyun.oss.model.UploadPartCopyResult;
import com.aliyun.oss.model.UploadPartRequest;
import com.aliyun.oss.model.UploadPartResult;
/**
* 访问阿里云开放存储服务(Open Storage Service, OSS)的入口类。
*/
public class OSSClient implements OSS {
// 用户身份信息。
private ServiceCredentials credentials = new ServiceCredentials();
// OSS 服务的地址。
private URI endpoint;
// 访问OSS服务的client
private ServiceClient serviceClient;
// OSS Operations.
private OSSBucketOperation bucketOperation;
private OSSObjectOperation objectOperation;
private OSSMultipartOperation multipartOperation;
private CORSOperation corsOperation;
/**
* 使用默认的OSS Endpoint构造一个新的{@link OSSClient}对象。
*
* @param accessKeyId
* 访问OSS的Access Key ID。
* @param accessKeySecret
* 访问OSS的Access Key Secret。
*/
public OSSClient(String accessKeyId, String accessKeySecret) {
this(OSSConstants.DEFAULT_OSS_ENDPOINT, accessKeyId, accessKeySecret, null);
}
/**
* 使用指定的OSS Endpoint构造一个新的{@link OSSClient}对象。
*
* @param endpoint
* OSS服务的Endpoint。必须以"http://"开头。
* @param accessKeyId
* 访问OSS的Access Key ID。
* @param accessKeySecret
* 访问OSS的Access Key Secret。
*/
public OSSClient(String endpoint, String accessKeyId, String accessKeySecret) {
this(endpoint, accessKeyId, accessKeySecret, null);
}
/**
* 使用指定的OSS Endpoint和配置构造一个新的{@link OSSClient}对象。
*
* @param endpoint
* OSS服务的Endpoint。必须以"http://"开头。
* @param accessKeyId
* 访问OSS的Access Key ID。
* @param accessKeySecret
* 访问OSS的Access Key Secret。
* @param config
* 客户端配置 {@link ClientConfiguration}。 如果为null则会使用默认配置。
*/
public OSSClient(String endpoint, String accessKeyId, String accessKeySecret, ClientConfiguration config) {
assertStringNotNullOrEmpty(endpoint, "endpoint");
try {
if (!endpoint.startsWith("http://")) {
throw new IllegalArgumentException(OSS_RESOURCE_MANAGER.getString("EndpointProtocolInvalid"));
}
this.endpoint = new URI(endpoint);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
this.credentials = new ServiceCredentials(accessKeyId, accessKeySecret);
this.serviceClient = new DefaultServiceClient(config != null ? config : new ClientConfiguration());
// 创建oss 操作类
bucketOperation = new OSSBucketOperation(this.endpoint, this.serviceClient, this.credentials);
objectOperation = new OSSObjectOperation(this.endpoint, this.serviceClient, this.credentials);
multipartOperation = new OSSMultipartOperation(this.endpoint, this.serviceClient, this.credentials);
corsOperation = new CORSOperation(this.endpoint, this.serviceClient, this.credentials);
}
/**
* 返回访问的OSS Endpoint。
*
* @return OSS Endpoint。
*/
public URI getEndpoint() {
return endpoint;
}
/**
* 返回使用的Access Key ID。
*
* @return 使用的Access Key ID。
*/
public String getAccessKeyId() {
return credentials.getAccessKeyId();
}
/**
* 返回使用的Access Key Secret。
*
* @return 使用的Access Key Secret。
*/
public String getAccessKeySecret() {
return credentials.getAccessKeySecret();
}
/*
* (non-Javadoc)
*
* @see com.aliyun.oss.OSS#createBucket(java.lang.String)
*/
@Override
public Bucket createBucket(String bucketName) throws OSSException, ClientException {
return this.createBucket(new CreateBucketRequest(bucketName));
}
/*
* (non-Javadoc)
*
* @see
* com.aliyun.oss.OSS#createBucket(com.aliyun.api.
* oss.model.ListObjectsRequest.CreateBucketRequest)
*/
@Override
public Bucket createBucket(CreateBucketRequest createBucketRequest) {
return bucketOperation.createBucket(createBucketRequest);
}
/*
* (non-Javadoc)
*
* @see com.aliyun.oss.OSS#deleteBucket(java.lang.String)
*/
@Override
public void deleteBucket(String bucketName) throws OSSException, ClientException {
bucketOperation.deleteBucket(bucketName);
}
/*
* (non-Javadoc)
*
* @see com.aliyun.oss.OSS#listBuckets()
*/
@Override
public List<Bucket> listBuckets() throws OSSException, ClientException {
BucketList bucketList = bucketOperation.listBuckets(new ListBucketsRequest(null, null, null));
List<Bucket> buckets = bucketList.getBucketList();
while (bucketList.isTruncated())
{
bucketList = bucketOperation.listBuckets(new ListBucketsRequest(null, bucketList.getNextMarker(), null));
buckets.addAll(bucketList.getBucketList());
}
return buckets;
}
/*
* (non-Javadoc)
*
* @see com.aliyun.oss.OSS#listBuckets(com.aliyun.oss.model.ListBucketsRequest)
*/
@Override
public BucketList listBuckets(ListBucketsRequest listBucketsRequest) throws OSSException, ClientException {
return bucketOperation.listBuckets(listBucketsRequest);
}
/*
* (non-Javadoc)
*
* @see com.aliyun.oss.OSS#listBuckets(java.lang.String,
* java.lang.String,java.lang.Integer)
*/
@Override
public BucketList listBuckets(String prefix, String marker, Integer maxKeys) throws OSSException, ClientException {
return bucketOperation.listBuckets(new ListBucketsRequest(prefix, marker, maxKeys));
}
/*
* (non-Javadoc)
*
* @see com.aliyun.oss.OSS#setBucketAcl(java.lang.String,
* com.aliyun.oss.model.CannedAccessControlList)
*/
@Override
public void setBucketAcl(String bucketName, CannedAccessControlList acl) throws OSSException, ClientException {
bucketOperation.setBucketAcl(bucketName, acl);
}
/*
* (non-Javadoc)
*
* @see com.aliyun.oss.OSS#getBucketAcl(java.lang.String)
*/
@Override
public AccessControlList getBucketAcl(String bucketName) throws OSSException, ClientException {
return bucketOperation.getBucketAcl(bucketName);
}
/*
* (non-Javadoc)
*
* @see com.aliyun.oss.OSS#setBucketReferer(java.lang.String,
* com.aliyun.oss.model.BucketReferer)
*/
@Override
public void setBucketReferer(String bucketName, BucketReferer referer) throws OSSException, ClientException {
bucketOperation.setBucketReferer(bucketName, referer);
}
/*
* (non-Javadoc)
*
* @see com.aliyun.oss.OSS#getBucketBucketReferer(java.lang.String)
*/
@Override
public BucketReferer getBucketReferer(String bucketName) throws OSSException, ClientException {
return bucketOperation.getBucketReferer(bucketName);
}
/*
* (non-Javadoc)
*
* @see com.aliyun.oss.OSS#getBucketLocation(java.lang.String)
*/
@Override
public String getBucketLocation(String bucketName) throws OSSException, ClientException {
return bucketOperation.getBucketLocation(bucketName);
}
/*
* (non-Javadoc)
*
* @see com.aliyun.oss.OSS#isBucketExist(java.lang.String)
*/
@Override
public boolean doesBucketExist(String bucketName) throws OSSException, ClientException {
return bucketOperation.bucketExists(bucketName);
}
/**
* 已过时。请使用{@link OSSClient#doesBucketExist(String)}。
*
* @param bucketName
* @return
* @throws OSSException
* @throws ClientException
*/
@Deprecated
public boolean isBucketExist(String bucketName) throws OSSException, ClientException {
return this.doesBucketExist(bucketName);
}
/*
* (non-Javadoc)
*
* @see com.aliyun.oss.OSS#listObjects(java.lang.String)
*/
@Override
public ObjectListing listObjects(String bucketName) throws OSSException, ClientException {
return listObjects(new ListObjectsRequest(bucketName, null, null, null, null));
}
/*
* (non-Javadoc)
*
* @see com.aliyun.oss.OSS#listObjects(java.lang.String,
* java.lang.String)
*/
@Override
public ObjectListing listObjects(String bucketName, String prefix) throws OSSException, ClientException {
return listObjects(new ListObjectsRequest(bucketName, prefix, null, null, null));
}
/*
* (non-Javadoc)
*
* @see
* com.aliyun.oss.OSS#listObjects(com.aliyun.oss
* .model.ListObjectsRequest)
*/
@Override
public ObjectListing listObjects(ListObjectsRequest listObjectsRequest) throws OSSException, ClientException {
return bucketOperation.listObjects(listObjectsRequest);
}
/*
* (non-Javadoc)
*
* @see com.aliyun.oss.OSS#putObject(java.lang.String,
* java.lang.String, java.io.InputStream,
* com.aliyun.oss.model.ObjectMetadata)
*/
@Override
public PutObjectResult putObject(String bucketName, String key, InputStream input, ObjectMetadata metadata)
throws OSSException, ClientException {
return objectOperation.putObject(bucketName, key, input, metadata);
}
@Override
public PutObjectResult putObject(URL signedUrl, String filePath, Map<String, String> customHeaders)
throws OSSException, ClientException {
return putObject(signedUrl, filePath, customHeaders, false);
}
@Override
public PutObjectResult putObject(URL signedUrl, String filePath, Map<String, String> customHeaders,
boolean useChunkEncoding) throws OSSException, ClientException {
if (!IOUtils.checkFile(filePath)) {
throw new IllegalArgumentException(String.format("Illegal file path %s", filePath));
}
FileInputStream requestContent = null;
try {
File fileToUpload = new File(filePath);
long fileSize = fileToUpload.length();
requestContent = new FileInputStream(fileToUpload);
return putObject(signedUrl, requestContent, fileSize, customHeaders, useChunkEncoding);
} catch (FileNotFoundException e) {
throw new ClientException(e);
} finally {
if (requestContent != null) {
try {
requestContent.close();
} catch (IOException e) {
//TODO:
}
}
}
}
@Override
public PutObjectResult putObject(URL signedUrl, InputStream requestContent, long contentLength,
Map<String, String> customHeaders) throws OSSException, ClientException {
return putObject(signedUrl, requestContent, contentLength, customHeaders, false);
}
@Override
public PutObjectResult putObject(URL signedUrl, InputStream requestContent, long contentLength,
Map<String, String> customHeaders, boolean useChunkEncoding) throws OSSException, ClientException {
return objectOperation.putObject(signedUrl, requestContent, contentLength, customHeaders, useChunkEncoding);
}
/*
* (non-Javadoc)
*
* @see com.aliyun.oss.OSS#copyObject(java.lang.String,
* java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public CopyObjectResult copyObject(String sourceBucketName, String sourceKey, String destinationBucketName,
String destinationKey) throws OSSException, ClientException {
return copyObject(new CopyObjectRequest(sourceBucketName, sourceKey, destinationBucketName, destinationKey));
}
/*
* (non-Javadoc)
*
* @see
* com.aliyun.oss.OSS#copyObject(com.aliyun.oss
* .model.CopyObjectRequest)
*/
@Override
public CopyObjectResult copyObject(CopyObjectRequest copyObjectRequest) throws OSSException, ClientException {
return objectOperation.copyObject(copyObjectRequest);
}
/*
* (non-Javadoc)
*
* @see com.aliyun.oss.OSS#getObject(java.lang.String,
* java.lang.String)
*/
@Override
public OSSObject getObject(String bucketName, String key) throws OSSException, ClientException {
return this.getObject(new GetObjectRequest(bucketName, key));
}
/*
* (non-Javadoc)
*
* @see
* com.aliyun.oss.OSS#getObject(com.aliyun.oss
* .model.GetObjectRequest, java.io.File)
*/
@Override
public ObjectMetadata getObject(GetObjectRequest getObjectRequest, File file) throws OSSException, ClientException {
return objectOperation.getObject(getObjectRequest, file);
}
/*
* (non-Javadoc)
*
* @see
* com.aliyun.oss.OSS#getObject(com.aliyun.oss
* .model.GetObjectRequest)
*/
@Override
public OSSObject getObject(GetObjectRequest getObjectRequest) throws OSSException, ClientException {
return objectOperation.getObject(getObjectRequest);
}
@Override
public OSSObject getObject(URL signedUrl, Map<String, String> customHeaders)
throws OSSException, ClientException
{
GetObjectRequest getObjectRequest = new GetObjectRequest(signedUrl, customHeaders);
return objectOperation.getObject(getObjectRequest);
}
/*
* (non-Javadoc)
*
* @see com.aliyun.oss.OSS#getObjectMetadata(java.lang.String,
* java.lang.String)
*/
@Override
public ObjectMetadata getObjectMetadata(String bucketName, String key) throws OSSException, ClientException {
return objectOperation.getObjectMetadata(bucketName, key);
}
/*
* (non-Javadoc)
*
* @see com.aliyun.oss.OSS#deleteObject(java.lang.String,
* java.lang.String)
*/
@Override
public void deleteObject(String bucketName, String key) throws OSSException, ClientException {
objectOperation.deleteObject(bucketName, key);
}
/*
* (non-Javadoc)
*
* @see
* com.aliyun.oss.OSS#generatePresignedUrl(java.lang.String,
* java.lang.String, java.util.Date)
*/
@Override
public URL generatePresignedUrl(String bucketName, String key, Date expiration) throws ClientException {
return generatePresignedUrl(bucketName, key, expiration, HttpMethod.GET);
}
/*
* (non-Javadoc)
*
* @see
* com.aliyun.oss.OSS#generatePresignedUrl(java.lang.String,
* java.lang.String, java.util.Date, com.aliyun.api.HttpMethod)
*/
@Override
public URL generatePresignedUrl(String bucketName, String key, Date expiration, HttpMethod method)
throws ClientException {
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, key);
request.setExpiration(expiration);
request.setMethod(method);
return generatePresignedUrl(request);
}
/*
* (non-Javadoc)
*
* @see
* com.aliyun.oss.OSS#generatePresignedUrl(com.aliyun.api
* .oss.model.GeneratePresignedUrlRequest)
*/
@Override
public URL generatePresignedUrl(GeneratePresignedUrlRequest request) throws ClientException {
assertParameterNotNull(request, "request");
if (request.getBucketName() == null) {
throw new IllegalArgumentException(OSS_RESOURCE_MANAGER.getString("MustSetBucketName"));
}
OSSUtils.ensureBucketNameValid(request.getBucketName());
if (request.getExpiration() == null) {
throw new IllegalArgumentException(OSS_RESOURCE_MANAGER.getString("MustSetExpiration"));
}
String bucketName = request.getBucketName();
String key = request.getKey();
String accessId = credentials.getAccessKeyId();
String accessKey = credentials.getAccessKeySecret();
HttpMethod method = request.getMethod() != null ? request.getMethod() : HttpMethod.GET;
String expires = String.valueOf(request.getExpiration().getTime() / 1000L);
String resourcePath = OSSUtils.makeResourcePath(key);
RequestMessage requestMessage = new RequestMessage();
ClientConfiguration cc = serviceClient.getClientConfiguration();
requestMessage.setEndpoint(OSSUtils.makeBukcetEndpoint(endpoint, bucketName, cc));
requestMessage.setMethod(method);
requestMessage.setResourcePath(resourcePath);
requestMessage.addHeader(HttpHeaders.DATE, expires);
if (request.getContentType() != null && request.getContentType().trim() != "") {
requestMessage.addHeader(HttpHeaders.CONTENT_TYPE, request.getContentType());
}
if (request.getContentMD5() != null && request.getContentMD5().trim() != "") {
requestMessage.addHeader(HttpHeaders.CONTENT_MD5, request.getContentMD5());
}
for (Map.Entry<String, String> h : request.getUserMetadata().entrySet()) {
requestMessage.addHeader(OSSHeaders.OSS_USER_METADATA_PREFIX + h.getKey(), h.getValue());
}
Map<String, String> responseHeadersParams = OSSUtils.getResponseHeaderParameters(request.getResponseHeaders());
if (responseHeadersParams.size() > 0) {
requestMessage.setParameters(responseHeadersParams);
}
if (request.getQueryParameter() != null && request.getQueryParameter().size() > 0) {
for (Map.Entry<String, String> entry : request.getQueryParameter().entrySet()) {
requestMessage.addParameter(entry.getKey(), entry.getValue());
}
}
String canonicalResource = "/" + ((bucketName != null) ? bucketName : "") + ((key != null ? "/" + key : ""));
String canonicalString = SignUtils.buildCanonicalString(method.toString(), canonicalResource, requestMessage,
expires);
String signature = ServiceSignature.create().computeSignature(accessKey, canonicalString);
Map<String, String> params = new HashMap<String, String>();
params.put(HttpHeaders.EXPIRES, expires);
params.put("OSSAccessKeyId", accessId);
params.put("Signature", signature);
params.putAll(requestMessage.getParameters());
// 生成URL
String queryString;
try {
queryString = HttpUtil.paramToQueryString(params, OSSConstants.DEFAULT_CHARSET_NAME);
} catch (UnsupportedEncodingException e) {
throw new ClientException(OSS_RESOURCE_MANAGER.getString("FailedToEncodeUri"), e);
}
String url = requestMessage.getEndpoint().toString();
if (!url.endsWith("/")) {
url += "/";
}
url += resourcePath + "?" + queryString;
try {
return new URL(url);
} catch (MalformedURLException e) {
throw new ClientException(e);
}
}
/*
* (non-Javadoc)
*
* @see
* com.aliyun.oss.OSS#abortMultipartUpload(com.aliyun.api
* .oss.model.AbortMultipartUploadRequest)
*/
@Override
public void abortMultipartUpload(AbortMultipartUploadRequest request) throws OSSException, ClientException {
multipartOperation.abortMultipartUpload(request);
}
/*
* (non-Javadoc)
*
* @see com.aliyun.oss.OSS#completeMultipartUpload(com.aliyun.
* api.oss.model.CompleteMultipartUploadRequest)
*/
@Override
public CompleteMultipartUploadResult completeMultipartUpload(CompleteMultipartUploadRequest request)
throws OSSException, ClientException {
return multipartOperation.completeMultipartUpload(request);
}
/*
* (non-Javadoc)
*
* @see com.aliyun.oss.OSS#initiateMultipartUpload(com.aliyun.
* api.oss.model.InitiateMultipartUploadRequest)
*/
@Override
public InitiateMultipartUploadResult initiateMultipartUpload(InitiateMultipartUploadRequest request)
throws OSSException, ClientException {
return multipartOperation.initiateMultipartUpload(request);
}
/*
* (non-Javadoc)
*
* @see
* com.aliyun.oss.OSS#listMultipartUploads(com.aliyun.api
* .oss.model.ListMultipartUploadsRequest)
*/
@Override
public MultipartUploadListing listMultipartUploads(ListMultipartUploadsRequest request) throws OSSException,
ClientException {
return multipartOperation.listMultipartUploads(request);
}
/*
* (non-Javadoc)
*
* @see
* com.aliyun.oss.OSS#listParts(com.aliyun.oss
* .model.ListPartsRequest)
*/
@Override
public PartListing listParts(ListPartsRequest request) throws OSSException, ClientException {
return multipartOperation.listParts(request);
}
/*
* (non-Javadoc)
*
* @see
* com.aliyun.oss.OSS#uploadPart(com.aliyun.oss
* .model.UploadPartRequest)
*/
@Override
public UploadPartResult uploadPart(UploadPartRequest request) throws OSSException, ClientException {
return multipartOperation.uploadPart(request);
}
/*
* (non-Javadoc)
*
* @see
* com.aliyun.oss.OSS#uploadPartCopy(com.aliyun.oss
* .model.UploadPartCopyRequest)
*/
@Override
public UploadPartCopyResult uploadPartCopy(UploadPartCopyRequest request) throws OSSException, ClientException {
return multipartOperation.uploadPartCopy(request);
}
@Override
public void setBucketCORS(SetBucketCORSRequest request) throws OSSException, ClientException {
corsOperation.setBucketCORS(request);
}
@Override
public List<CORSRule> getBucketCORSRules(String bucketName) throws OSSException, ClientException {
return corsOperation.getBucketCORSRules(bucketName);
}
@Override
public void deleteBucketCORSRules(String bucketName) throws OSSException, ClientException {
corsOperation.deleteBucketCORS(bucketName);
}
@Override
public ResponseMessage optionsObject(OptionsRequest request) throws OSSException, ClientException {
return corsOperation.optionsObject(request);
}
@Override
public void setBucketLogging(SetBucketLoggingRequest request)
throws OSSException, ClientException {
bucketOperation.setBucketLogging(request);
}
@Override
public BucketLoggingResult getBucketLogging(String bucketName) {
return bucketOperation.getBucketLogging(bucketName);
}
@Override
public void deleteBucketLogging(String bucketName) throws OSSException,
ClientException {
bucketOperation.deleteBucketLogging(bucketName);
}
@Override
public void setBucketWebsite(SetBucketWebsiteRequest setBucketWebSiteRequest)
throws OSSException, ClientException {
bucketOperation.setBucketWebsite(setBucketWebSiteRequest);
}
@Override
public BucketWebsiteResult getBucketWebsite(String bucketName)
throws OSSException, ClientException {
return bucketOperation.getBucketWebsite(bucketName);
}
@Override
public void deleteBucketWebsite(String bucketName) throws OSSException,
ClientException {
bucketOperation.deleteBucketWebsite(bucketName);
}
@Override
public String generatePostPolicy(Date expiration, PolicyConditions conds) {
String formatedExpiration = DateUtil.formatIso8601Date(expiration);
String jsonizedExpiration = String.format("\"expiration\":\"%s\"", formatedExpiration);
String jsonizedConds = conds.jsonize();
StringBuilder postPolicy = new StringBuilder();
postPolicy.append("{");
postPolicy.append(String.format("%s,%s", jsonizedExpiration, jsonizedConds));
postPolicy.append("}");
return postPolicy.toString();
}
@Override
public String calculatePostSignature(String postPolicy) {
try {
byte[] binaryData = postPolicy.getBytes(OSSConstants.DEFAULT_CHARSET_NAME);
String encPolicy = BinaryUtil.toBase64String(binaryData);
return ServiceSignature.create().computeSignature(getAccessKeySecret(), encPolicy);
} catch (UnsupportedEncodingException ex) {
throw new ClientException("Unsupported charset: " + ex.getMessage());
}
}
@Override
public void setBucketLifecycle(SetBucketLifecycleRequest setBucketLifecycleRequest) {
bucketOperation.setBucketLifecycle(setBucketLifecycleRequest);
}
@Override
public List<LifecycleRule> getBucketLifecycle(String bucketName) {
return bucketOperation.getBucketLifecycle(bucketName);
}
@Override
public void deleteBucketLifecycle(String bucketName) {
bucketOperation.deleteBucketLifecycle(bucketName);
}
}
|
package com.metoo.core.ip;
/**
*
* <p>
* Title: IPtest.java
* </p>
*
* <p>
* Description:
* </p>
*
* <p>
* Copyright: Copyright (c) 2014
* </p>
*
* <p>
* Company: 湖南创发科技有限公司 www.koala.com
* </p>
*
* @author erikzhang
*
* @date 2014-4-24
*
* @version koala_b2b2c v2.0 2015版
*/
public class IPtest {
public static void main(String[] args) {
// 指定纯真数据库的文件名,所在文件夹
IPSeeker ip = new IPSeeker("QQWry.Dat", "f:/");
String temp = "169.254.111.173";
// 测试IP 58.20.43.13
System.out.println(ip.getIPLocation(temp).getCountry() + ":"
+ ip.getIPLocation(temp).getArea());
}
}
|
package base;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
public class BaseTest {
protected static ContextForTests context;
protected static Dummy dummy;
@Before
@After
public void rollback() {
context.rollback();
}
@BeforeClass
public static void initializeDummy() {
context = ContextForTests.getInstance();
dummy = new Dummy(context.getConfiguration());
}
}
|
package com.androidvoyage.bmc.utils;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.Address;
import android.location.Geocoder;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.Editable;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Patterns;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.core.widget.NestedScrollView;
import com.androidvoyage.bmc.BCApplication;
import com.androidvoyage.bmc.common.CommonConstants;
import com.androidvoyage.bmc.interfaces.Callback;
import com.androidvoyage.bmc.R;
import com.google.android.material.snackbar.Snackbar;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import static android.content.Context.INPUT_METHOD_SERVICE;
import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE;
import static android.text.TextUtils.isEmpty;
import static java.util.Calendar.DATE;
import static java.util.Calendar.MONTH;
import static java.util.Calendar.YEAR;
public class CommonUtils {
public static final String TAG = CommonUtils.class.getSimpleName();
static final long DAY = 24 * 60 * 60 * 1000;
public static final int STORAGE_PERMISSION_CODE = 1010;
public static int getDisplayHeightInPixels(Activity activity) {
DisplayMetrics displayMetrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
return displayMetrics.heightPixels;
}
public static int getDisplayWidthInPixels(Activity activity) {
DisplayMetrics displayMetrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
return displayMetrics.widthPixels;
}
public static boolean inLastDay(Date aDate) {
return aDate.getTime() > System.currentTimeMillis() - DAY;
}
/**
* Gets date object from string in the format YYYY-MM-DDTHH:MM:SS.sssZ // 2018-04-22T05:27:05.523Z
* @param dateString
* @return date object if format was correct, returns null if format is not as specified here.
*/
/**
* This function is depracated in codebase. Please dont use it. It would be removed soon.
* TODO: Remove this function and replace it.
*/
/*@Deprecated
public static void getApiResponse(final Context context, String endpoints, int Request, JSONObject jsonObject, final VolleyCallback volleyCallback) {
String url = Endpoints.DOCSMART_DOMAIN + endpoints;
Log.d(TAG, "get : " + url);
Log.d(TAG, "get : " + jsonObject);
final JsonObjectRequest req = new JsonObjectRequest(Request, url, jsonObject,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
volleyCallback.onSuccess(response);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
try {
Log.e(TAG, "Error in volley " + error);
NetworkResponse networkResponse = error.networkResponse;
byte[] responseBytes = networkResponse.data;
String responseString = new String(responseBytes);
Log.e(TAG, "response error volley " + responseString);
} catch (Exception exp) {
}
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
String authHeader = "JWT " + Preferences.getToken();
Log.e(TAG, "Sending Auth HEader := " + authHeader);
params.put("Authorization", authHeader);
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(context);
queue.add(req);
}*/
//This method hides keyboard from the screen
public static void hideSoftKeyboard(View view, Context context) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
//This method checks if user is connected to internet
public static boolean isOnline(Context context) {
ConnectivityManager connMgr = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
}
//This method shows snackbar
public static void snackbar(Context context, ViewGroup viewGroup, String message) {
Snackbar snackbar = Snackbar.make(viewGroup, message, Snackbar.LENGTH_SHORT);
snackbar.show();
View snackBarView = snackbar.getView();
snackBarView.setBackgroundColor(context.getResources().getColor(R.color.colorPrimary));
}
/*public static void snackbar(Context context, ViewGroup viewGroup, String message, ErrorCode errorCode) {
Snackbar snackbar = Snackbar.make(viewGroup, message, Snackbar.LENGTH_SHORT);
snackbar.show();
View snackBarView = snackbar.getView();
snackBarView.setBackgroundColor(context.getResources().getColor(R.color.colorPrimary));
}*/
//This method shows Toast
public static void Toast(Context context, String message) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
//This method shows snackbar
public static void showSnackBar(View view, Context context, String message) {
Snackbar snackbar = Snackbar.make(view, message, Snackbar.LENGTH_LONG);
snackbar.getView().setBackgroundColor(ContextCompat.getColor(context, R.color.colorPrimary));
snackbar.show();
}
/*public static void showSnackBareErrorred(View view, Context context, String message) {
Snackbar snackbar = Snackbar.make(view, message, Snackbar.LENGTH_LONG);
snackbar.getView().setBackgroundColor(ContextCompat.getColor(context, R.color.Red));
snackbar.show();
}
public static void showSnackBarWithAction(View view, String message, String action, final Callback callback) {
Snackbar snackbar = Snackbar.make(view, message, Snackbar.LENGTH_LONG);
snackbar.setActionTextColor(Color.YELLOW);
snackbar.getView().setBackgroundColor(ContextCompat.getColor(App.getInstance(), R.color.colorPrimary));
TextView tv = snackbar.getView().findViewById(R.id.snackbar_text); //snackbar_text
tv.setTextColor(ContextCompat.getColor(App.getInstance(), R.color.white));
snackbar.setAction(action, new View.OnClickListener() {
@Override
public void onClick(View v) {
callback.invoke("OK");
}
});
snackbar.show();
}
public static void alertBoxComingSoon(Context context) {
//This method shows alert box saying Coming soon
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View dialogView = inflater.inflate(R.layout.layout_alert_box, null);
dialogBuilder.setView(dialogView);
TextView tv_coming_soon = dialogView.findViewById(R.id.tv_coming_soon);
dialogBuilder.setIcon(R.drawable.docsmart_logo_svg);
dialogBuilder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
AlertDialog b = dialogBuilder.create();
b.show();
}*/
public static void alertBoxInternetConnection(Context context) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle("No Internet Connection");
alertDialogBuilder.setMessage("You are offline please check your internet connection");
alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
/*public static void successDisaster(LinearLayout disasterpage, final Context context, String successfully_disaster_) {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View dialogView = inflater.inflate(R.layout.disaster_success, null);
dialogBuilder.setView(dialogView);
TextView tv_coming_soon = dialogView.findViewById(R.id.tv_coming_soon);
Button btn_positive = dialogView.findViewById(R.id.button_ok);
final AlertDialog b = dialogBuilder.create();
btn_positive.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
b.dismiss();
Intent i = new Intent(context, MainPageActivity.class);
context.startActivity(i);
}
});
b.show();
}
public static void showSuccessAlert(final Context context, String success_msg, final Callback<String> callback) {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View dialogView = inflater.inflate(R.layout.layout_create_event, null);
dialogBuilder.setView(dialogView);
TextView tv_alert_sent = dialogView.findViewById(R.id.tv_alert_sent);
tv_alert_sent.setText(success_msg);
Button btn_positive = dialogView.findViewById(R.id.button_ok);
final AlertDialog b = dialogBuilder.create();
btn_positive.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
b.dismiss();
callback.invoke("done");
}
});
b.show();
}
public static void SuccessAlertDialog(final Context context, String success_msg) {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View dialogView = inflater.inflate(R.layout.layout_create_event, null);
dialogBuilder.setView(dialogView);
TextView tv_alert_sent = dialogView.findViewById(R.id.tv_alert_sent);
tv_alert_sent.setText(success_msg);
Button btn_positive = dialogView.findViewById(R.id.button_ok);
final AlertDialog b = dialogBuilder.create();
btn_positive.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
b.dismiss();
}
});
b.show();
}*/
/*public static void cancelButton(final Context context) {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View dialogView = inflater.inflate(R.layout.button_cancel_button, null);
dialogBuilder.setView(dialogView);
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
dialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog b = dialogBuilder.create();
b.show();
}*/
public static void requestLocationPermission(Activity activity, Context context, int PERMISSION_REQUEST_CODE) {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_FINE_LOCATION)) {
Toast.makeText(context, "GPS permission allows us to access location data. Please allow in App Settings for additional functionality.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_CODE);
}
}
/*
public static void requestLocationPermission(Activity activity, Context context, String permissionName, int PERMISSION_REQUEST_CODE, Callback<Boolean> retry) {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.ACCESS_FINE_LOCATION)) {
showPermissionDetails(context, permissionName, false, retry);
} else {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_CODE);
}
}
*/
public static boolean checkPermission(Context context) {
int result = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION);
return result == PackageManager.PERMISSION_GRANTED;
}
/* public static boolean checkPermissionwithcoarse(Context context) {
int result = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION);
return result == PackageManager.PERMISSION_GRANTED;
}*/
/*public static void showPermissionDetails(Context context, String permissionName, boolean deniedPermanently, Callback<Boolean> retry){
String message = permissionName +" permission(s) are required to perform tasks and proceed.";
if(deniedPermanently) message = permissionName +" permission(s) are required to perform tasks and proceed. \nPlease goto Settings > Applications > " +
BCApplication.getAppContext().getResources().getString(R.string.app_name) + " > App info > permissions > and turn on the permission.";
Dialogs.createAlertDialog(context, "Please grant this permission", message,
(dialog, which) -> { if(retry != null) retry.invoke(which == Dialog.BUTTON_POSITIVE); }).show();
}*/
public static void setStatusBarColor(Context context, int color, boolean isLight) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
((Activity) context).getWindow().setStatusBarColor(ContextCompat.getColor(context, color));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (isLight) {
((Activity) context).getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}
}
}
public static void getNamefromDialog(Context context, String title, final EditText textView) {
final Dialog mDialog = new Dialog(context);
mDialog.setCancelable(false);
mDialog.setCanceledOnTouchOutside(false);
mDialog.setContentView(R.layout.dialog_edittext);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(mDialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
mDialog.getWindow().setAttributes(lp);
mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
if (!((Activity) context).isFinishing()) {
mDialog.show();
}
TextView tvTitleDialogEt = mDialog.findViewById(R.id.tv_title_dialog_et);
final EditText etDialogGetString = mDialog.findViewById(R.id.et_dialog_getString);
TextView tvCancelDialogEt = mDialog.findViewById(R.id.tv_cancel_dialog_et);
TextView tvOkayDialogEt = mDialog.findViewById(R.id.tv_okay_dialog_et);
tvTitleDialogEt.setText(title);
etDialogGetString.callOnClick();
tvOkayDialogEt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textView.setText(etDialogGetString.getText().toString().trim());
mDialog.dismiss();
}
});
tvCancelDialogEt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDialog.dismiss();
}
});
}
public static Uri getOutputMediaFileUri(int type, String imageDirectoryName) {
return Uri.fromFile(getOutputMediaFile(type, imageDirectoryName));
}
private static File getOutputMediaFile(int type, String imageDirectoryName) {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
imageDirectoryName);
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(imageDirectoryName, "Oops! Failed create "
+ imageDirectoryName + " directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
public static Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float) width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
public static void openAppSettings(Context context) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", context.getPackageName(), null);
intent.setData(uri);
context.startActivity(intent);
}
public static void openAppSettingsForPermission(Activity activity, int requestCode) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
intent.setData(uri);
activity.startActivityForResult(intent, requestCode);
}
public static void showHidePassword(EditText editText, View v) {
v.setSelected(!v.isSelected());
if (editText != null && editText.getText().toString().length() > 0) {
if (v.isSelected()) {
editText.setTransformationMethod(null);
editText.setSelection(editText.length());
} else {
editText.setTransformationMethod(new PasswordTransformationMethod());
editText.setSelection(editText.length());
}
}
}
/*public static void showDialogTwoButton(Context context, String title, String message, String strNegative, String strPositive, final DialogClickListener dialogClickListener) {
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View dialogView = inflater.inflate(R.layout.dialog_alert_sure, null);
dialogBuilder.setView(dialogView);
dialogBuilder.setCancelable(false);
final AlertDialog dialog = dialogBuilder.create();
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
if (!((Activity) context).isFinishing()) {
dialog.show();
}
TextView tvTitle = dialogView.findViewById(R.id.tv_title);
TextView tvDialogMessage = dialogView.findViewById(R.id.tv_dialog_message);
TextView tvCancel = dialogView.findViewById(R.id.tv_cancel);
TextView tvPositive = dialogView.findViewById(R.id.tv_positive);
tvTitle.setText(title);
tvDialogMessage.setText(message);
tvCancel.setText(strNegative);
tvPositive.setText(strPositive);
tvCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialogClickListener.onButtonClick(dialog, 0);
dialog.dismiss();
}
});
tvPositive.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialogClickListener.onButtonClick(dialog, 1);
dialog.dismiss();
}
});
}*/
/*public static void showDialogTwoButton(Context context, String title, String message, String strPositive, final DialogClickListener dialogClickListener) {
showDialogTwoButton(context, title, message, "Cancel", strPositive, dialogClickListener);
}*/
public static boolean checkNull(String text) {
return text != null && text.trim().length() > 0;
}
public static Double roundOff(Double value, int places) {
if (places < 0) throw new IllegalArgumentException();
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
public static float dp2px(int dip, Context context) {
float scale = context.getResources().getDisplayMetrics().density;
return dip * scale + 0.5f;
}
/*public static void showDialogOneButton(Context context, String title, String msg, String btnCaption, DialogInterface.OnDismissListener onDismissListener) {
final Dialog dialog = new Dialog(context, R.style.DialogSlideAnim);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
dialog.setContentView(R.layout.dialog_one_button);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
dialog.getWindow().setGravity(Gravity.CENTER);
if (!((Activity) context).isFinishing()) {
dialog.show();
}
TextView tvTitle = (TextView) dialog.findViewById(R.id.tv_title);
TextView tvMsg = (TextView) dialog.findViewById(R.id.tv_msg);
TextView tvDismiss = (TextView) dialog.findViewById(R.id.tv_dismiss);
tvTitle.setText(title);
tvMsg.setText(msg);
tvDismiss.setText(btnCaption);
tvDismiss.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (onDismissListener != null) {
onDismissListener.onDismiss(dialog);
}
dialog.dismiss();
}
});
}*/
public static void focusOnView(ScrollView svCenter, final View view) {
if (view != null) {
svCenter.post(new Runnable() {
@Override
public void run() {
view.getParent().requestChildFocus(view, view);
}
});
}
}
public static boolean focusOnView(final View view) {
if (view != null) {
view.post(new Runnable() {
@Override
public void run() {
view.getParent().requestChildFocus(view, view);
}
});
}
return view == null;
}
public static String getSingleImagePath(Context context, Intent data) {
if (data != null && data.getClipData() != null) {
return FileUtils.getPath(context, data.getClipData().getItemAt(0).getUri());
}
if (data != null && data.getData() != null) {
return FileUtils.getPath(context, data.getData());
}
return FileUtils.getPath(context, CommonUtils.getCaptureImageOutputUri(BCApplication.getAppContext()));
}
/*public static void showFilePreviewDialog(Context context, String url){
if(url.contains(".pdf")){
showDocDialog(context,url);
}else {
showImageDialog(context,url);
}
}*/
/* public static void showDocDialog(Context context, String url) {
if (url == null || url.length() == 0) {
Toast.makeText(context, "url is malformed.", Toast.LENGTH_SHORT).show();
return;
}
*//*new DocumentDialog(context, R.style.DialogSlideAnim,url).show();*//*
context.startActivity(new Intent(context, FilePreviewActivity.class).putExtra("PDF_URL", url));
}
public static void showImageDialog(Context context, String url) {
if (url == null || url.length() == 0) {
Toast.makeText(context, "url is malformed.", Toast.LENGTH_SHORT).show();
return;
}
final Dialog dialog = new Dialog(context, R.style.DialogSlideAnim);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
dialog.setContentView(R.layout.dialog_image_preview);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
dialog.getWindow().setGravity(Gravity.CENTER);
if (!((Activity) context).isFinishing()) {
dialog.show();
}
ProgressBar pbLoader = dialog.findViewById(R.id.pb_image_dialog);
dialog.findViewById(R.id.iv_cancel).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
}
});
pbLoader.setVisibility(View.VISIBLE);
ImageLoader.loadImageFromUrl(url, (ImageView) dialog.findViewById(R.id.iv_preview), R.drawable.profilephotos, new RequestListener<Drawable>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
pbLoader.setVisibility(View.GONE);
Toast.makeText(context, "Something went wrong!", Toast.LENGTH_SHORT).show();
return false;
}
@Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
pbLoader.setVisibility(View.GONE);
return false;
}
});
}*/
/*public static void showImagesDialog(Context context, ArrayList<String> center_images) {
if (center_images == null || center_images.size() == 0) {
Toast.makeText(context, "images not validationAddData.", Toast.LENGTH_SHORT).show();
return;
}
final Dialog dialog = new Dialog(context, R.style.DialogSlideAnim);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
dialog.setContentView(R.layout.dialog_image_vp_preview);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
dialog.getWindow().setGravity(Gravity.CENTER);
if (!((Activity) context).isFinishing()) {
dialog.show();
}
dialog.findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
}
});
RecyclerView rcvImages = dialog.findViewById(R.id.rcv_images);
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(4, LinearLayoutManager.VERTICAL);
rcvImages.setLayoutManager(staggeredGridLayoutManager);
rcvImages.setAdapter(new CenterImagesAdapter(context, center_images));
}*/
@SuppressLint("SimpleDateFormat")
public static String getTimeAMPMFormat(String s) {
try {
return new SimpleDateFormat("hh:mm a").format(new SimpleDateFormat("HH:mm").parse(s));
} catch (ParseException e) {
e.printStackTrace();
}
return "";
}
@SuppressLint("SimpleDateFormat")
public static String getTime24HourFormat(String s) {
try {
return new SimpleDateFormat("HH:mm").format(new SimpleDateFormat("hh:mm a").parse(s));
} catch (ParseException e) {
e.printStackTrace();
}
return "";
}
public static void setTextWatcherForEdittext(final EditText edittext, final TextView tvError) {
edittext.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (edittext.getText().toString().trim().length() > 0) {
tvError.setVisibility(View.GONE);
}
}
@Override
public void afterTextChanged(Editable editable) {
}
});
}
//This method sets scrolling inside/nested scroll
@SuppressLint("ClickableViewAccessibility")
public static void setNestedScrollView(NestedScrollView view, Context context) {
view.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
view.setFocusable(true);
view.setFocusableInTouchMode(true);
view.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
v.requestFocusFromTouch();
return false;
}
});
}
public static boolean validateStringForEmpty(String StringToValidate) {
return StringToValidate.equals("");
}
public static void hideKeyboard(@NonNull Activity activity) {
// Check if no view has focus:
View view = activity.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
public static void showKeyboard(Context context, EditText et) {
if (et != null) {
et.requestFocus();
InputMethodManager imm = (InputMethodManager) et.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
} else {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
public static String getAddressInString(Context context, double lat, double lng) {
// This method returns address in string format
String CurrentLocation = "";
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
if (addresses.size() >= 1) {
Address obj = addresses.get(0);
String add = obj.getAddressLine(0);
add = add + "\n" + obj.getCountryName();
add = add + "\n" + obj.getCountryCode();
add = add + "\n" + obj.getAdminArea();
add = add + "\n" + obj.getPostalCode();
add = add + "\n" + obj.getSubAdminArea();
add = add + "\n" + obj.getLocality();
add = add + "\n" + obj.getSubThoroughfare();
CurrentLocation = obj.getAddressLine(0);
String NearestRailwaystation = obj.getLocality();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
}
return CurrentLocation;
}
public static String getAreaNameForLocation(Context context, double lat, double lng) {
// This method returns address in string format
String CurrentAreaLocation = "";
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
if (addresses.size() >= 1) {
Address obj = addresses.get(0);
CurrentAreaLocation = obj.getSubAdminArea();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
}
return CurrentAreaLocation;
}
/*public static HashMap<String, Double> getLatitudeLongitude(Context context) {
Double Latitude = 0.0;
Double Longitude = 0.0;
HashMap<String, Double> HashMapLatLong = new HashMap<>();
GpsTrackerService gps = new GpsTrackerService(context);
if (gps.canGetLocation()) {
Latitude = gps.getLatitude();
Longitude = gps.getLongitude();
} else {
Toast.makeText(context, "Not Able to fetch your location", Toast.LENGTH_SHORT).show();
}
HashMapLatLong.put("Latitude", Latitude);
HashMapLatLong.put("Longitude", Longitude);
return HashMapLatLong;
}*/
public static boolean isInternetWorking(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//we are connected to a network
return connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED;
}
public static String getRealPathFromURI(Uri contentURI, Activity context) {
String[] projection = {MediaStore.Images.Media.DATA};
@SuppressWarnings("deprecation")
Cursor cursor = context.managedQuery(contentURI, projection, null,
null, null);
if (cursor == null)
return null;
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (cursor.moveToFirst()) {
String s = cursor.getString(column_index);
// cursor.close();
return s;
}
cursor.close();
return null;
}
public static void fetchDateTime(final Context context, final Callback<String> callback) {
int mYear, mMonth, mDay, mHours, mMins;
Calendar calender_sugar;
calender_sugar = Calendar.getInstance();
mYear = calender_sugar.get(Calendar.YEAR);
mMonth = calender_sugar.get(MONTH);
mDay = calender_sugar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dpd = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
int abc = 1;
String pp = "0" + abc;
monthOfYear = monthOfYear + 1;
dayOfMonth = dayOfMonth;
String m = String.valueOf(monthOfYear);
String d = String.valueOf(dayOfMonth);
if (monthOfYear < 10) {
m = "0" + monthOfYear;
}
if (dayOfMonth < 10) {
d = "0" + dayOfMonth;
} else {
d = dayOfMonth + "";
}
String date = d + "/" + m + "/" + year;
timepicker(context, date, callback);
}
}, mYear, mMonth, mDay);
dpd.show();
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, 0);
dpd.getDatePicker().setMinDate(calendar.getTime().getTime());
}
public static void fetchDateTime48(final Context context, final Callback<String> callback) {
int mYear, mMonth, mDay, mHours, mMins;
Calendar calender_sugar;
calender_sugar = Calendar.getInstance();
mYear = calender_sugar.get(Calendar.YEAR);
mMonth = calender_sugar.get(MONTH);
mDay = calender_sugar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dpd = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
int abc = 1;
String pp = "0" + abc;
monthOfYear = monthOfYear + 1;
dayOfMonth = dayOfMonth;
String m = String.valueOf(monthOfYear);
String d = String.valueOf(dayOfMonth);
if (monthOfYear < 10) {
m = "0" + monthOfYear;
}
if (dayOfMonth < 10) {
d = "0" + dayOfMonth;
} else {
d = dayOfMonth + "";
}
String date = d + "/" + m + "/" + year;
timepicker(context, date, callback);
}
}, mYear, mMonth, mDay);
dpd.show();
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, 0);
dpd.getDatePicker().setMinDate(System.currentTimeMillis() - (1000 * 60 * 60 * 48)/* minus 48 hours*/);
dpd.getDatePicker().setMaxDate(System.currentTimeMillis());
}
public static void fetchDateTime(final Long minDate, final long maxDate, final Context context, final Callback<String> callback) {
int mYear, mMonth, mDay, mHours, mMins;
Calendar calender_sugar;
calender_sugar = Calendar.getInstance();
mYear = calender_sugar.get(Calendar.YEAR);
mMonth = calender_sugar.get(MONTH);
mDay = calender_sugar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dpd = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
int abc = 1;
String pp = "0" + abc;
monthOfYear = monthOfYear + 1;
dayOfMonth = dayOfMonth;
String m = String.valueOf(monthOfYear);
String d = String.valueOf(dayOfMonth);
if (monthOfYear < 10) {
m = "0" + monthOfYear;
}
if (dayOfMonth < 10) {
d = "0" + dayOfMonth;
} else {
d = dayOfMonth + "";
}
String date = d + "/" + m + "/" + year;
CommonUtils.timepicker(context, date, callback);
}
}, mYear, mMonth, mDay);
dpd.show();
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, 0);
if (minDate != null) {
dpd.getDatePicker().setMinDate(minDate);
}
dpd.getDatePicker().setMaxDate(maxDate);
}
private static void timepicker(Context context, final String date, final Callback<String> callback) {
final int mHours, mMins;
Calendar calender_sugar;
calender_sugar = Calendar.getInstance();
mHours = calender_sugar.get(Calendar.HOUR_OF_DAY);
mMins = calender_sugar.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(context, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
String time = hourOfDay + ":" + minute + ":" + "00";
String dateTime11;
if (hourOfDay < 10) {
time = "0" + hourOfDay + ":" + minute;
}
if (minute < 10) {
time = hourOfDay + ":" + "0" + minute;
}
if (hourOfDay < 10 && minute < 10) {
time = "0" + hourOfDay + ":" + "0" + minute;
}
dateTime11 = DateTimeUtils.convertDateTimePickerToReadableDateTimeFormat(date + " " + time);
callback.invoke(dateTime11);
}
}, mHours, mMins, true);
timePickerDialog.show();
}
public static void fetchTime(final Context context, final Callback<String> callback, boolean amPm) {
final Calendar c = Calendar.getInstance();
TimePickerDialog timePickerDialog = new TimePickerDialog(context,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
callback.invoke(getTimeAMPMFormat(hourOfDay + ":" + minute));
}
}, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), amPm);
timePickerDialog.show();
}
public static void fetchDate(final Context context, final Callback<String> callback) {
int mYear, mMonth, mDay;
Calendar calender_sugar;
calender_sugar = Calendar.getInstance();
mYear = calender_sugar.get(Calendar.YEAR);
mMonth = calender_sugar.get(MONTH);
mDay = calender_sugar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dpd = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
int abc = 1;
String pp = "0" + abc;
monthOfYear = monthOfYear + 1;
dayOfMonth = dayOfMonth;
String m = String.valueOf(monthOfYear);
String d = String.valueOf(dayOfMonth);
if (monthOfYear < 10) {
m = "0" + monthOfYear;
}
if (dayOfMonth < 10) {
d = "0" + dayOfMonth;
} else {
d = dayOfMonth + "";
}
String date = d + "/" + m + "/" + year;
date = DateTimeUtils.convertDatePickerToReadableDateFormat(date);
callback.invoke(date);
}
}, mYear, mMonth, mDay);
dpd.show();
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, 0);
dpd.getDatePicker().setMaxDate(calendar.getTime().getTime());
}
public static void fetchDate(final Context context, final Callback<String> callback, int startYear, int startMonth, int startDate) {
DatePickerDialog dpd = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
monthOfYear = monthOfYear + 1;
String m = String.valueOf(monthOfYear);
String d = String.valueOf(dayOfMonth);
if (monthOfYear < 10) {
m = "0" + monthOfYear;
}
if (dayOfMonth < 10) {
d = "0" + dayOfMonth;
}
String date = d + "/" + m + "/" + year;
date = DateTimeUtils.convertDatePickerToReadableDateFormat(date);
callback.invoke(date);
}
}, startYear, startMonth, startDate);
dpd.show();
}
public static boolean isInternetAvailable(Context context) {
NetworkInfo info = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null) {
Log.d(TAG, "no internet connection");
return false;
} else {
if (info.isConnected()) {
Log.d(TAG, " internet connection available...");
return true;
} else {
Log.d(TAG, " internet connection");
return true;
}
}
}
public static void fromHtml(String text, TextView textView) {
if (isEmpty(text)) return;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
textView.setText(Html.fromHtml(text, Html.FROM_HTML_MODE_COMPACT));
} else {
textView.setText(Html.fromHtml(text));
}
}
public static SpannableString Spanableshow(CharSequence text, int startDuration, int endDuration, @ColorInt int textColor) {
SpannableString spannableString = new SpannableString(text);
ForegroundColorSpan colorSpan = new ForegroundColorSpan(textColor);
spannableString.setSpan(colorSpan, startDuration, endDuration, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableString;
}
public static File getExternalCacheDir(Context context) {
return context.getExternalCacheDir();
}
public static boolean isValidEmail(CharSequence target) {
if (target == null) {
return false;
} else {
return Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
public static boolean isValidName(String target) {
if (target == null) {
return false;
} else {
return target.matches("[A-z\\']*");
}
}
public static boolean isValidPhone(CharSequence target) {
if (target == null) {
return false;
} else {
return Patterns.PHONE.matcher(target).matches();
}
}
public static String capitalize(String s) {
if (s == null || s.length() == 0) {
return "";
}
char first = s.charAt(0);
if (Character.isUpperCase(first)) {
return s;
} else {
return Character.toUpperCase(first) + s.substring(1);
}
}
public static String capitalizeString(String string) {
char[] chars = string.toLowerCase().toCharArray();
boolean found = false;
for (int i = 0; i < chars.length; i++) {
if (!found && Character.isLetter(chars[i])) {
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i]) || chars[i] == '&' || chars[i] == '(' || chars[i] == '/') { // You can add other chars here
found = false;
}
}
return String.valueOf(chars);
}
public static String capitalizeEachWordInSentence(String sentence) {
if (sentence == null || sentence.length() == 0) {
return "";
}
String[] strArray = sentence.split(" ");
String newSentence = "";
StringBuilder buffer = new StringBuilder();
for (String s : strArray) {
buffer.append(newSentence);
buffer.append(" ");
buffer.append(capitalize(s));
}
return buffer.toString().trim();
}
public static int getDiffYears(Date first) {
Calendar a = Calendar.getInstance(Locale.getDefault());
a.setTime(first);
Calendar b = Calendar.getInstance(Locale.getDefault());
int diff = b.get(YEAR) - a.get(YEAR);
if (a.get(MONTH) > b.get(MONTH) ||
(a.get(MONTH) == b.get(MONTH) && a.get(DATE) > b.get(DATE))) {
// diff--;
}
return diff;
}
public static void cancelProgressDialog(ProgressDialog progress) {
if (progress.isShowing() && progress != null)
progress.cancel();
}
public static Address fetchaddress(Context context, double latitude, double longitude) {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(
latitude,
longitude,
1);
} catch (Exception ioException) {
Log.e("", "Error in getting address for the location");
}
if (addresses == null || addresses.size() == 0) {
Toast.makeText(context, "No address found for the location", Toast.LENGTH_SHORT).show();
return null;
} else {
return addresses.get(0);
}
}
/*public static void spnState(Context context, Spinner spinner, String filename) {
String json_string;
JSONObject jsonObj;
JSONArray jsonArray;
json_string = loadJSONFromAsset(filename);
ArrayList<String> messages = new ArrayList<String>();
{
try {
jsonObj = new JSONObject(json_string);
jsonArray = jsonObj.getJSONArray("indiastate");
String formule, url;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jObj = jsonArray.getJSONObject(i);
formule = jObj.getString("name");
messages.add(formule);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
CommonUtils.positionspinner(context, spinner, messages);
}*/
/*public static ArrayList<String> getStates(String filename){
String json_string;
JSONObject jsonObj;
JSONArray jsonArray;
json_string = loadJSONFromAsset(filename);
ArrayList<String> messages = new ArrayList<String>();
try {
jsonObj = new JSONObject(json_string);
jsonArray = jsonObj.getJSONArray("indiastate");
String formule, url;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jObj = jsonArray.getJSONObject(i);
formule = jObj.getString("name");
messages.add(formule);
}
} catch (JSONException e) {
e.printStackTrace();
}
return messages;
}*/
public static void CommontextWatcher(final Context context, final EditText editText, final String message) {
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (editText.getText().length() > 0) {
editText.setError(null);
} else {
editText.setError(message);
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
}
public static void downloadFile(String url, Context context) {
int startIndex = url.lastIndexOf('.');
int endIndex = url.length();
String fileName = "GovernmentLiscense" + url.substring(startIndex, endIndex);
String title = "Downloading " + fileName;
Uri uri = Uri.parse(url);
// Create request for android download manager
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |
DownloadManager.Request.NETWORK_MOBILE);
// set title and description
request.setTitle(title);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//set the local destination for download file to a path within the application's external files directory
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
request.setMimeType("*/*");
downloadManager.enqueue(request);
}
public static File createImageFile() throws IOException {
String timeStamp =
new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
String imageFileName = "IMG_" + timeStamp + "_";
File storageDir = Environment.getExternalStorageDirectory();
File image = File.createTempFile(
imageFileName, /* prefix */
null, /* suffix */
storageDir /* directory */
);
return image;
}
public static String getRealPathFromURIDB(Uri contentUri) {
Cursor cursor = null;
if (cursor == null) {
return contentUri.getPath();
} else {
cursor = BCApplication.getAppContext().getContentResolver().query(contentUri, null, null, null, null);
cursor.moveToFirst();
int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
String realPath = cursor.getString(index);
cursor.close();
return realPath;
}
}
/*public static void fetchDate(final Long minDate, final Long maxDate, int year, int month, int date, final Context context, final Callback<String> callback) {
int mYear, mMonth, mDay, mHours, mMins;
Calendar calender_sugar;
calender_sugar = Calendar.getInstance();
mYear = calender_sugar.get(Calendar.YEAR);
mMonth = calender_sugar.get(MONTH);
mDay = calender_sugar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dpd = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
int abc = 1;
String pp = "0" + abc;
monthOfYear = monthOfYear + 1;
dayOfMonth = dayOfMonth;
String m = String.valueOf(monthOfYear);
String d = String.valueOf(dayOfMonth);
if (monthOfYear < 10) {
m = "0" + monthOfYear;
}
if (dayOfMonth < 10) {
d = "0" + dayOfMonth;
} else {
d = dayOfMonth + "";
}
String date = year + "-" + m + "-" + d;
callback.invoke(date);
}
}, mYear, mMonth, mDay);
dpd.updateDate(year, month, date);
dpd.show();
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, 0);
if (minDate != null) {
dpd.getDatePicker().setMinDate(minDate);
}
if (maxDate != null)
dpd.getDatePicker().setMaxDate(maxDate);
}*/
public static void callIntent(Context context, String mobile) {
if (mobile != null && mobile.length() > 0) {
String uri = "tel:" + mobile.trim();
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uri));
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
context.startActivity(intent);
return;
}
Toast.makeText(context, "Invalid Phone Number", Toast.LENGTH_SHORT).show();
}
public static void messageIntent(Context context, String mobile, String msg) {
if (mobile != null && mobile.length() > 0) {
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.setData(Uri.parse("sms:" + mobile.trim()));
if (msg != null && msg.trim().length() > 0) {
sendIntent.putExtra("sms_body", msg.trim());
}
context.startActivity(sendIntent);
return;
}
Toast.makeText(context, "Invalid Phone Number", Toast.LENGTH_SHORT).show();
}
/**
* Create a chooser intent to select the source to get image from.<br>
* The source can be camera's (ACTION_IMAGE_CAPTURE) or gallery's (ACTION_GET_CONTENT).<br>
* All possible sources are added to the intent chooser.
*
* @param context used to access Android APIs, like content resolve, it is your
* activity/fragment/widget.
* @param title the title to use for the chooser UI
* @param includeDocuments if to include KitKat documents activity containing all sources
* @param includeCamera if to include camera intents
*/
public static Intent getPickImageChooserIntent(
@NonNull Context context,
CharSequence title,
boolean includeDocuments,
boolean includeCamera,
boolean multiSelect) {
List<Intent> allIntents = new ArrayList<>();
PackageManager packageManager = context.getPackageManager();
// collect all camera intents if Camera permission is available
if (!isExplicitCameraPermissionRequired(context) && includeCamera) {
allIntents.addAll(getCameraIntents(context, packageManager));
}
List<Intent> galleryIntents = getGalleryIntents(packageManager, Intent.ACTION_GET_CONTENT, includeDocuments, multiSelect);
if (galleryIntents.size() == 0) {
// if no intents found for get-content try pick intent action (Huawei P9).
galleryIntents = getGalleryIntents(packageManager, Intent.ACTION_PICK, includeDocuments, multiSelect);
}
allIntents.addAll(galleryIntents);
Intent target;
if (allIntents.isEmpty()) {
target = new Intent();
} else {
target = allIntents.get(allIntents.size() - 1);
allIntents.remove(allIntents.size() - 1);
}
// Create a chooser from the main intent
Intent chooserIntent = Intent.createChooser(target, title);
// Add all other intents
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, allIntents.toArray(new Parcelable[allIntents.size()]));
return chooserIntent;
}
/**
* Get all Camera intents for capturing image using device camera apps.
*/
public static List<Intent> getCameraIntents(
@NonNull Context context, @NonNull PackageManager packageManager) {
List<Intent> allIntents = new ArrayList<>();
// Determine Uri of camera image to save.
Uri outputFileUri = getCaptureImageOutputUri(context);
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(res.activityInfo.packageName);
if (outputFileUri != null) {
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
}
allIntents.add(intent);
}
return allIntents;
}
/**
* Get URI to image received from capture by camera.
*
* @param context used to access Android APIs, like content resolve, it is your
* activity/fragment/widget.
*/
public static Uri getCaptureImageOutputUri(@NonNull Context context) {
Uri outputFileUri = null;
File getImage = context.getExternalCacheDir();
if (getImage != null) {
outputFileUri = FileProvider.getUriForFile(context, CommonConstants.AUTHORITY, new File(getImage.getPath(), "pickImageResult.jpeg"));
}
return outputFileUri;
}
/**
* Check if explicetly requesting camera permission is required.<br>
* It is required in Android Marshmellow and above if "CAMERA" permission is requested in the
* manifest.<br>
* See <a
* href="http://stackoverflow.com/questions/32789027/android-m-camera-intent-permission-bug">StackOverflow
* question</a>.
*/
public static boolean isExplicitCameraPermissionRequired(@NonNull Context context) {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& hasPermissionInManifest(context, "android.permission.CAMERA")
&& context.checkSelfPermission(Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED;
}
/**
* Check if the app requests a specific permission in the manifest.
*
* @param permissionName the permission to check
* @return true - the permission in requested in manifest, false - not.
*/
public static boolean hasPermissionInManifest(
@NonNull Context context, @NonNull String permissionName) {
String packageName = context.getPackageName();
try {
PackageInfo packageInfo =
context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
final String[] declaredPermisisons = packageInfo.requestedPermissions;
if (declaredPermisisons != null && declaredPermisisons.length > 0) {
for (String p : declaredPermisisons) {
if (p.equalsIgnoreCase(permissionName)) {
return true;
}
}
}
} catch (PackageManager.NameNotFoundException e) {
}
return false;
}
/**
* Get all Gallery intents for getting image from one of the apps of the device that handle
* images.
*/
public static List<Intent> getGalleryIntents(@NonNull PackageManager packageManager, String action, boolean includeDocuments, boolean multiSelect) {
List<Intent> intents = new ArrayList<>();
Intent galleryIntent = new Intent(action);
/*if (action.equals(Intent.ACTION_GET_CONTENT)) {
galleryIntent.setType("image/*");
*//*galleryIntent.setType("application/pdf");*//*
} else {
galleryIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
}*/
String[] mimeTypes = {"image/*", "application/pdf"};
galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
galleryIntent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "*/*");
if (mimeTypes.length > 0) {
galleryIntent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
}
} else {
String mimeTypesStr = "";
for (String mimeType : mimeTypes) {
mimeTypesStr += mimeType + "|";
}
galleryIntent.setType(mimeTypesStr.substring(0, mimeTypesStr.length() - 1));
}
List<ResolveInfo> listGallery = packageManager.queryIntentActivities(galleryIntent, 0);
for (ResolveInfo res : listGallery) {
Intent intent = new Intent(galleryIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(res.activityInfo.packageName);
if (multiSelect)
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intents.add(intent);
}
// remove documents intent
if (!includeDocuments) {
for (Intent intent : intents) {
if (intent.getComponent().getClassName().equals("com.android.documentsui.DocumentsActivity")) {
intents.remove(intent);
break;
}
}
}
return intents;
}
//Requesting permission
public static boolean requestStoragePermission(Context context, int requestCode) {
if ((ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) &&
(ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)) {
return true;
}
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
openAppSettingsForPermission((Activity) context,requestCode);
return false;
}
//And finally ask for the permission
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, requestCode);
return false;
}
private static List<Intent> getOtherIntentList(Context context) {
List<Intent> allIntents = new ArrayList<>();
Intent intentPDF = new Intent(Intent.ACTION_GET_CONTENT);
intentPDF.setType("application/pdf");
intentPDF.addCategory(Intent.CATEGORY_OPENABLE);
Intent intentTxt = new Intent(Intent.ACTION_GET_CONTENT);
intentTxt.setType("text/plain");
intentTxt.addCategory(Intent.CATEGORY_OPENABLE);
Intent intentXls = new Intent(Intent.ACTION_GET_CONTENT);
intentXls.setType("application/x-excel");
intentXls.addCategory(Intent.CATEGORY_OPENABLE);
PackageManager packageManager = context.getPackageManager();
List activitiesPDF = packageManager.queryIntentActivities(intentPDF,
0);
boolean isIntentSafePDF = activitiesPDF.size() > 0;
List activitiesTxt = packageManager.queryIntentActivities(intentTxt,
0);
boolean isIntentSafeTxt = activitiesTxt.size() > 0;
List activitiesXls = packageManager.queryIntentActivities(intentXls,
0);
boolean isIntentSafeXls = activitiesXls.size() > 0;
if (isIntentSafePDF)
allIntents.add(getContentResolvedIntent(context, intentPDF, true));
if (isIntentSafeTxt)
allIntents.add(getContentResolvedIntent(context, intentTxt, true));
if (isIntentSafeXls)
allIntents.add(getContentResolvedIntent(context, intentXls, true));
return allIntents;
}
private static Intent getContentResolvedIntent(Context context, Intent inputIntent, boolean multiSelect) {
PackageManager packageManager = context.getPackageManager();
Intent intent = null;
List<ResolveInfo> listGallery = packageManager.queryIntentActivities(inputIntent, 0);
for (ResolveInfo res : listGallery) {
intent = new Intent(inputIntent);
if (multiSelect)
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
}
return intent;
}
public static Intent getPickOtherChooserIntent(@NonNull Context context, CharSequence title) {
List<Intent> allIntents = new ArrayList<>();
allIntents.addAll(getOtherIntentList(context));
Intent target;
if (allIntents.isEmpty()) {
target = new Intent();
} else {
target = allIntents.get(allIntents.size() - 1);
allIntents.remove(allIntents.size() - 1);
}
// Create a chooser from the main intent
Intent chooserIntent = Intent.createChooser(target, title);
// Add all other intents
chooserIntent.putExtra(
Intent.EXTRA_INITIAL_INTENTS, allIntents.toArray(new Parcelable[allIntents.size()]));
return chooserIntent;
}
/*public static Address currentLocation(Context context) {
LocationTrack gpstracker = new LocationTrack(context);
List<Address> addressList = new ArrayList<>();
Address address = null;
double longitude = gpstracker.getLongitude();
double latitude = gpstracker.getLatitude();
try {
Geocoder geocoder;
geocoder = new Geocoder(context, Locale.getDefault());
addressList = geocoder.getFromLocation(latitude, longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5
} catch (IOException e) {
e.printStackTrace();
}
if (addressList != null && addressList.size() > 0) {
address = addressList.get(0);
Preferences.saveCurrentAddress(address);
} else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle("Please select location");
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
return address;
}*/
/*public static void currentLocationWithFused(Activity context, final Callback<Address> callback) {
if (CommonUtils.checkPermission(context)) {
FusedLocationProviderClient fusedLocationClient;
fusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
final Address[] tempaddress = {null};
LocationTrack gpstracker = new LocationTrack(context);
if (!gpstracker.canGetLocation()) {
gpstracker.showSettingsAlert();
} else {
fusedLocationClient.getLastLocation().addOnSuccessListener(context, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
Geocoder geocoder;
geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
tempaddress[0] = addresses.get(0);
} catch (IOException e) {
e.printStackTrace();
}
callback.invoke(tempaddress[0]);
}
}
})
.addOnFailureListener(context, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
}
}
// TODO : Below lines are commented to check if they are really required. Developer should handle this requesting permission in activity
// else {
// CommonUtils.requestLocationPermission(context, context, 1212);
// }
}*/
/*public static boolean checkblankETForTextShow(Context context, EditText editText, int str_error_message,TextView error_editText) {
if (editText.getText().toString().matches("")) {
error_editText.setVisibility(View.VISIBLE);
error_editText.setText(context.getString(str_error_message));
return false;
} else {
return true;
}
}*/
/*public static void openMapsWithDirection(Context context, double latitude, double longitude){
String uri = "http://maps.google.com/maps?f=d&hl=en" +
// "&saddr="+latitude1+","+longitude1+
"&daddr="+latitude+","+longitude;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);
}*/
public static void soonToast(Context context){
Toast.makeText(context, "Coming soon...", Toast.LENGTH_SHORT).show();
}
}
|
package com.zc.pivas.titileshow.service;
import com.zc.base.orm.mybatis.paging.JqueryStylePaging;
import com.zc.base.orm.mybatis.paging.JqueryStylePagingResults;
import com.zc.pivas.titileshow.bean.ConfigTitleBean;
import com.zc.pivas.titileshow.bean.ConfigTitleSubBean;
import java.util.List;
import java.util.Map;
/**
* 医嘱/药单列表配置
*
* @author kunkka
* @version 1.0
*/
public interface ConfigTitleService {
/***
* 查询医嘱/药单列表
* @param bean 对象
* @param jquryStylePaging 分页参数
* @return 分页数据
* @exception Exception e
*/
JqueryStylePagingResults<ConfigTitleBean> getShowTilteList(ConfigTitleBean bean, JqueryStylePaging jquryStylePaging)
throws Exception;
/**
* 根据条件查询数量
*
* @param bean 查询对象
* @return 数量
*/
int getConfigTitleTotal(ConfigTitleBean bean);
/**
* 药品标签详情
*
* @return
*/
List<ConfigTitleSubBean> displayTitleDetail(Long configId);
boolean checkConfigTitleName(ConfigTitleBean bean);
List<ConfigTitleBean> checkUpdateConfigTitleName(ConfigTitleBean bean);
void addConfigTitle(ConfigTitleBean bean);
/**
* 修改配置费/材料费表数据
*
* @param bean 需要修改的数据
*/
void updateConfTitle(ConfigTitleBean bean);
void delConfigTitle(Long confId);
List<ConfigTitleBean> getALlConfigTitle(Integer confType, String userName);
String getAllAccount();
List<String> getExitAccounts(Map<String, Object> map);
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.dizitart.nitrite.datagate.impl.factory;
import org.dizitart.nitrite.datagate.impl.service.DatagateUserService;
import org.dizitart.nitrite.datagate.impl.service.DatagateUserServiceImpl;
/**
*
* @author tareq
*/
public class DatagateUserServiceFactory {
private static DatagateUserServiceFactory instance = getInstance();
private DatagateUserServiceFactory() {
}
public static final DatagateUserServiceFactory getInstance() {
if (instance == null) {
instance = new DatagateUserServiceFactory();
}
return instance;
}
public DatagateUserService get() {
return new DatagateUserServiceImpl();
}
}
|
package pwnbrew.utilities;
///*
//
//Copyright (C) 2013-2014, Securifera, Inc
//
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification,
//are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Securifera, Inc nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
//AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
//OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
//CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
//SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
//ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//================================================================================
//
//Pwnbrew is provided under the 3-clause BSD license above.
//
//The copyright on this package is held by Securifera, Inc
//
//*/
//
//
///*
// * Symbol.java
// *
// * Created on June 7, 2013, 6:58:43 PM
// */
//
//package pwnbrew.misc;
//
//
///**
// * This enumeration is a set of all of the non-alphanumeric characters appearing
// * on the standard English keyboard.
// *
// */
//public enum Symbol {
//
// Ampersand( '&' ), Apostrophe( '\'' ), Asterisk( '*' ), At( '@' ), BackSlash( '\\' ), // NO_UCD (unused code)
// Backtick( '`' ), BraceOpen( '{' ), BraceClose( '}' ), BracketOpen( '[' ), BracketClose( ']' ), // NO_UCD (unused code)
// Caret( '^' ), Colon( ':' ), Comma( ',' ), Dollar( '$' ), Equals( '=' ), // NO_UCD (unused code)
// ExclamationMark( '!' ), GreaterThan( '>' ), Hyphen( '-' ), LessThan( '<' ), NewLine( '\n' ), // NO_UCD (unused code)
// Number( '#' ), Percent( '%' ), ParenthesesOpen( '(' ), ParenthesesClose( ')' ), Period( '.' ), // NO_UCD (unused code)
// Pipe( '|' ), Plus( '+' ), QuestionMark( '?' ), Quote( '\"' ), Semicolon( ';' ), // NO_UCD (unused code)
// Space( ' ' ), Slash( '/' ), Tilde( '~' ), Underscore( '_' ); // NO_UCD (unused code)
//
// private final char CHAR;
//
//
// // ==========================================================================
// /**
// * Creates a new instance of {@link Symbol}.
// * @param symbol the symbol
// */
// private Symbol( char symbol ) {
// CHAR = symbol;
// }/* END CONSTRUCTOR( char ) */
//
//
// // ==========================================================================
// /**
// * Returns the symbol's character.
// * @return the symbol's character
// */
// public char getChar() {
// return CHAR;
// }/* END getChar() */
//
//
// // ==========================================================================
// /**
// * Returns the symbol as a String.
// * @return the symbol as a String
// */
// public String asString() {
// return "" + CHAR;
// }/* END asString() */
//
//
// // ==========================================================================
// /**
// * Determines if the given {@code char} is this symbol.
// *
// * @param c
// * @return {@code true} if the given {@code char} is of this symbol.
// */
// public boolean is( char c ) {
// return ( CHAR == c );
// }/* END is( char ) */
//
//
// // ==========================================================================
// /**
// * Returns the name of the {@link Symbol}.
// *
// * @return the name of the {@code Symbol}
// */
// @Override //Object
// public String toString() {
// return name();
// }/* END toString() */
//
//}/* END ENUM Symbol */
|
package com.project.crew_types;
import java.util.HashMap;
import com.project.Crew;
import com.project.RaceID;
import com.project.StatID;
public class BugBitch extends Crew {
private static byte statVariance = 10;
public static String[] names = {"Sandy","Sam","Jesse","Ste","Frank","Charlie"};
private static float raceRelationVariance = 0.2f;
public BugBitch(int social, int combat, int pilot, int engineering,int gunner,int science, int stress, int hunger,
char gender,boolean visible) {
super(social, combat, pilot, engineering, gunner, science, stress,hunger, gender,RaceID.bugBitch,visible);
}
public BugBitch(boolean random,boolean visible) {
super(getRandomStat(statVariance),getRandomStat(statVariance), getRandomStat(statVariance), getRandomStat(statVariance), getRandomStat(statVariance), 0, 0, getRandomStat(statVariance), getRandomGender(), RaceID.bugBitch, visible);
generateRaceTable();
}
public BugBitch(boolean visible) {
super(RaceID.bugBitch,visible);
this.setGender(getRandomGender());//15,35,30,20,15,20,0,0
if(this.getGender()=='m') {
stats.put(StatID.social, getRandomWeightedStat(statVariance,(byte)15));
stats.put(StatID.combat, getRandomWeightedStat(statVariance,(byte)35));
stats.put(StatID.gunner, getRandomWeightedStat(statVariance,(byte)30));
stats.put(StatID.engineering, getRandomWeightedStat(statVariance,(byte)20));
stats.put(StatID.science, getRandomWeightedStat(statVariance,(byte)15));
stats.put(StatID.pilot, getRandomWeightedStat(statVariance,(byte)20));
stats.put(StatID.stress, (byte)0);
stats.put(StatID.hunger, (byte)0);
}
else {//25,40,25,25,35,20,0,0
stats.put(StatID.social, getRandomWeightedStat(statVariance,(byte)25));
stats.put(StatID.combat, getRandomWeightedStat(statVariance,(byte)40));
stats.put(StatID.pilot, getRandomWeightedStat(statVariance,(byte)25));
stats.put(StatID.engineering, getRandomWeightedStat(statVariance,(byte)25));
stats.put(StatID.gunner, getRandomWeightedStat(statVariance,(byte)35));
stats.put(StatID.science, getRandomWeightedStat(statVariance,(byte)20));
stats.put(StatID.stress, (byte)0);
stats.put(StatID.hunger, (byte)0);
}
this.setName(names[rand.nextInt(names.length)]);
generateRaceTable();
}
private void generateRaceTable() {
this.raceRelations = new HashMap<>();
this.raceRelations.put(RaceID.bugBitch,getRandomWeightedRaceRelation(raceRelationVariance, 1f));
this.raceRelations.put(RaceID.octoBitch,getRandomWeightedRaceRelation(raceRelationVariance, 0.1f));
this.raceRelations.put(RaceID.ent,getRandomWeightedRaceRelation(raceRelationVariance, 0.5f));
this.raceRelations.put(RaceID.blueLizard, getRandomWeightedRaceRelation(raceRelationVariance,0.3f));
this.raceRelations.put(RaceID.yellowLizard,getRandomWeightedRaceRelation(raceRelationVariance, 0.2f));
this.raceRelations.put(RaceID.robot,getRandomWeightedRaceRelation(raceRelationVariance, 0.3f));
this.raceRelations.put(RaceID.moleBitch,getRandomWeightedRaceRelation(raceRelationVariance,0.2f));
}
}
|
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.Before;
public class BusStopTest {
BusStop busStop;
Person person;
Bus bus;
@Before
public void before(){
person = new Person("James");
busStop = new BusStop("Buchanan Bus Station");
bus = new Bus(42);
}
@Test
public void hasName(){
assertEquals("Buchanan Bus Station", busStop.getBusStopName());
}
@Test
public void busCount(){
assertEquals(0, busStop.getBusStopQueueNumbers());
}
@Test
public void addPassenger(){
busStop.addQueuer(person);
assertEquals(1, busStop.getBusStopQueueNumbers());
}
@Test
public void removePassenger(){
busStop.addQueuer(person);
busStop.removeAllQueuer();
assertEquals(0, busStop.getBusStopQueueNumbers());
}
@Test public void isBusStopEmpty(){
BusStop busStop2 = new BusStop("Whatever");
assertEquals(true, busStop2.isBusStopEmpty());
}
}
|
public class Box extends CollectionBoard {
public int width, height;
public int indexX;
public int indexY;
private int i = 0;
public Box(int dimension, int height, int width) {
this.dimension = dimension;
this.height = height;
this.width = width;
s = new Square[width * height];
}
public void addToStructure(Square sq) {
s[i] = sq;
i++;
}
public boolean checkPossiblity(int num){
for(int i = 0; i < s.length; i ++){
if(s[i].getValue() == num){
return false;
}
}
return true;
}
public int getIndexX(){
return indexX;
}
public int getIndexY(){
return indexY;
}
}
|
package esi.atl.gg39864.blokus.model;
/**
* this Enumeration is the enumeration of the Color of the Piece
*
* @author chris home
*/
public enum Color {
GREEN,RED, YELLOW, BLUE;
}
|
package com.tscloud.common.framework.service.impl;
import com.tscloud.common.framework.Exception.ServiceException;
import com.tscloud.common.framework.domain.TrackableEntity;
import com.tscloud.common.framework.mapper.BaseInterfaceMapper;
import com.tscloud.common.framework.rest.view.Page;
import com.tscloud.common.framework.service.IBaseInterfaceService;
import com.tscloud.common.utils.IDGenerator;
import com.tscloud.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Context;
import java.util.Date;
import java.util.List;
import java.util.Map;
public abstract class BaseInterfaceServiceImpl<Entity extends TrackableEntity> implements IBaseInterfaceService<Entity> {
protected Logger log = LoggerFactory.getLogger(getClass());
@Context
protected HttpServletResponse response;
@Context
protected HttpServletRequest request;
public Page findByPage(Page page, Map<String, Object> map) throws ServiceException {
try {
page.setTotal(this.getBaseInterfaceMapper().getCount(map));
map.put("startRowNum", page.getStartRowNum());
map.put("pageSize", page.getPageSize());
map.put("endRowNum", page.getEndRowNum());
page.setRows(this.getBaseInterfaceMapper().findByPage(map));
} catch (Exception e) {
throw new ServiceException(e.getMessage(), e);
}
return page;
}
public String save(Entity entity) throws ServiceException {
String id = IDGenerator.getID();
try {
if (StringUtils.isBlank(entity.getId()) || entity.getId().equalsIgnoreCase("0")) {
entity.setId(id);
}
entity.setCreateDate(new Date());
this.getBaseInterfaceMapper().save(entity);
} catch (Exception e) {
throw new ServiceException(e.getMessage(), e);
}
return id;
}
public boolean update(Entity entity) throws ServiceException {
try {
entity.setUpdateDate(new Date());
this.getBaseInterfaceMapper().update(entity);
} catch (Exception e) {
throw new ServiceException(e.getMessage(), e);
}
return true;
}
public boolean deleteById(String id) throws ServiceException {
try {
this.getBaseInterfaceMapper().deleteById(id);
} catch (Exception e) {
throw new ServiceException(e.getMessage(), e);
}
return true;
}
public Entity findById(String id) throws ServiceException {
Entity entity = null;
try {
entity = this.getBaseInterfaceMapper().findById(id);
} catch (Exception e) {
throw new ServiceException(e.getMessage(), e);
}
return entity;
}
public List<Entity> findAll() throws ServiceException {
List<Entity> list = null;
try {
list = this.getBaseInterfaceMapper().findAll();
} catch (Exception e) {
throw new ServiceException(e.getMessage(), e);
}
return list;
}
public List<Entity> findByMap(Map<String, Object> map) throws ServiceException {
List<Entity> list = null;
try {
list = this.getBaseInterfaceMapper().findByMap(map);
} catch (Exception e) {
throw new ServiceException(e.getMessage(), e);
}
return list;
}
/**
* 抽象方法需要实现, 得到基础服务接口
*
* @return
*/
public abstract BaseInterfaceMapper<Entity> getBaseInterfaceMapper();
}
|
package com.zhku.my21days.controller;
import java.util.Calendar;
import java.util.Collection;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.zhku.my21days.util.CurrentUser;
@Controller
@RequestMapping("/login")
public class LoginController {
@RequestMapping("/toIndex")
public String toIndex(HttpServletRequest request,HttpServletResponse response){
String username=CurrentUser.getUserName();
Calendar curdate=Calendar.getInstance();
StringBuilder time=new StringBuilder();
time.append(curdate.get(curdate.YEAR)).append("年").append(curdate.get(curdate.MONTH)+1).append("月").append(curdate.get(curdate.DAY_OF_MONTH)).append("日");
String week=null;
int day=curdate.get(curdate.DAY_OF_WEEK);
if (day == 2) {
time.append(",").append("星期一");
} else if (day == 3) {
time.append(",").append("星期二");
} else if (day == 4) {
time.append(",").append("星期三");
} else if (day == 5) {
time.append(",").append("星期四");
} else if (day == 6) {
time.append(",").append("星期五");
} else if (day == 7) {
time.append(",").append("星期六");
} else if (day == 1) {
time.append(",").append("星期日");
}
String role=CurrentUser.getUserRole();
request.setAttribute("date", time);
request.setAttribute("user", username);
request.setAttribute("role", role);
return "/index";
}
@RequestMapping("/toMain")
public String toMain(HttpServletRequest request,HttpServletResponse response){
return "/main1";
}
}
|
package com.gaoshin.top;
import java.text.ParseException;
import java.util.Date;
import org.quartz.CronExpression;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewActivity extends ShortcutActivity {
private WebView web;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
web = new WebView(this);
setContentView(web);
web.getSettings().setJavaScriptEnabled(true);
web.getSettings().setAllowFileAccess(true);
web.addJavascriptInterface(new WebViewJavascriptInterface(), "Device");
web.setWebChromeClient(new WebChromeClient());
web.setWebViewClient(new GenericWebViewClient());
Intent intent = getIntent();
String url = intent.getData().toString();
web.loadUrl(url);
}
public class GenericWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return true;
}
}
public class WebViewJavascriptInterface {
public void exit() {
finish();
}
public void email(String to, String subject, String msg) {
String action = "android.intent.action.SENDTO";
Uri uri = Uri.parse("mailto:" + to);
Intent intent = new Intent(action, uri);
intent.putExtra("android.intent.extra.TEXT", msg);
WebViewActivity.this.startActivity(intent);
}
public String getConfig(String key, String def) {
return getApp().getConfService().get(key, def).getValue();
}
public void setConfig(String key, String value) {
Configuration conf = getApp().getConfService().get(key, value);
conf.setValue(value);
getApp().getConfService().save(conf);
}
public String getCronExecutionList(String cronExpression) {
try {
StringBuilder sb = new StringBuilder();
CronExpression cron = new CronExpression("0 " + cronExpression);
Date after = new Date();
int i = 0;
for (; i < 10; i++) {
after = cron.getTimeAfter(after);
if (after == null)
break;
sb.append(after.toString()).append("\n");
}
if (sb.length() == 0) {
return "Invalid format or time has passed";
} else {
return sb.toString() + (i == 10 ? "......" : "");
}
} catch (ParseException e) {
return "Invalid format";
}
}
}
}
|
package com.tac.kulik.waveaudiovizualization.util;
import android.content.Context;
import android.util.TypedValue;
/**
* Created by kulik on 31.01.17.
*/
public class ScreenUtils {
public static int dp2px(Context context, int dp) {
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics());
return px;
}
}
|
package com.mkdutton.labfive;
import java.io.Serializable;
/**
* Created by Matt on 10/9/14.
*/
public class SavedLocation implements Serializable {
public static final long serialVersionUID = 86753098675309L;
private String mTitle;
private String mNote;
private double mLat;
private double mLong;
private String mImagePath;
public SavedLocation(String _title, String _note, double _lat, double _long, String _imagePath) {
this.mTitle = _title;
this.mNote = _note;
this.mLat = _lat;
this.mLong = _long;
this.mImagePath = _imagePath;
}
public String getmTitle() {
return mTitle;
}
public void setmTitle(String mTitle) {
this.mTitle = mTitle;
}
public String getmNote() {
return mNote;
}
public void setmNote(String mNote) {
this.mNote = mNote;
}
public double getmLat() {
return mLat;
}
public void setmLat(double mLat) {
this.mLat = mLat;
}
public double getmLong() {
return mLong;
}
public void setmLong(double mLong) {
this.mLong = mLong;
}
public String getmImagePath() {
return mImagePath;
}
public void setmImagePath(String mImagePath) {
this.mImagePath = mImagePath;
}
}
|
package com.rednovo.ace.common;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.rednovo.ace.data.events.BaseEvent;
import de.greenrobot.event.EventBus;
/**
* 定时刷新直播间观众列表的广播
*/
public class RefreshAudienceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
EventBus.getDefault().post(new BaseEvent(Globle.KEY_ALARM_REQUEST_AUDIENCE));
}
}
|
/* Ara - capture species and specimen data
*
* Copyright (C) 2009 INBio (Instituto Nacional de Biodiversidad)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.inbio.ara.persistence.reports;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
*
* @author esmata
*/
@Entity
@Table(name = "dwc_category")
public class DwcCategory implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "category_id")
private Long categoryId;
@Basic(optional = false)
@Column(name = "category_name")
private String categoryName;
@Basic(optional = false)
@Column(name = "category_keyword")
private String categoryKeyword;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "elementCategoryId", fetch = FetchType.LAZY)
private List<DwcElement> dwcElementCollection;
public DwcCategory() {
}
public DwcCategory(Long categoryId) {
this.categoryId = categoryId;
}
public DwcCategory(Long categoryId, String categoryName, String categoryKeyword) {
this.categoryId = categoryId;
this.categoryName = categoryName;
this.categoryKeyword = categoryKeyword;
}
public Long getCategoryId() {
return categoryId;
}
public void setCategoryId(Long categoryId) {
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getCategoryKeyword() {
return categoryKeyword;
}
public void setCategoryKeyword(String categoryKeyword) {
this.categoryKeyword = categoryKeyword;
}
public List<DwcElement> getDwcElementCollection() {
return dwcElementCollection;
}
public void setDwcElementCollection(List<DwcElement> dwcElementCollection) {
this.dwcElementCollection = dwcElementCollection;
}
@Override
public int hashCode() {
int hash = 0;
hash += (categoryId != null ? categoryId.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof DwcCategory)) {
return false;
}
DwcCategory other = (DwcCategory) object;
if ((this.categoryId == null && other.categoryId != null) || (this.categoryId != null && !this.categoryId.equals(other.categoryId))) {
return false;
}
return true;
}
@Override
public String toString() {
return "org.inbio.ara.persistence.reports.DwcCategory[categoryId=" + categoryId + "]";
}
}
|
public class Solution {
int totalCities;
int totalProvinces;
int[] parent;
int[] rank;
public int findCircleNum(int[][] isConnected) {
totalCities = isConnected.length;
totalProvinces = isConnected.length;
rank = new int[isConnected.length];
initializeParent();
mapProvinces(isConnected);
return totalProvinces;
}
public void mapProvinces(int[][] isConnected) {
for (int r = 0; r < totalCities; r++) {
for (int c = 0; c < totalCities; c++) {
if (r != c && isConnected[r][c] == 1) {
union(r, c);
}
}
}
}
public int findParent(int index) {
if (parent[index] != index) {
parent[index] = findParent(parent[index]);
}
return parent[index];
}
public void initializeParent() {
parent = new int[totalCities];
for (int i = 0; i < totalCities; i++) {
parent[i] = i;
}
}
public void union(int indexOne, int indexTwo) {
int indexOneParent = findParent(indexOne);
int indexTwoParent = findParent(indexTwo);
if (indexOneParent != indexTwoParent) {
totalProvinces--;
if (rank[indexOneParent] < rank[indexTwoParent]) {
parent[indexOneParent] = indexTwoParent;
} else if (parent[indexOneParent] > parent[indexTwoParent]) {
parent[indexTwoParent] = indexOneParent;
} else {
parent[indexOneParent] = indexTwoParent;
rank[indexOneParent]++;
}
}
}
}
|
package com.ebanq.web.pageobjects.accounts;
import com.codeborne.selenide.Condition;
import com.ebanq.web.elements.EbanqSelect;
import com.ebanq.web.model.Account;
import com.ebanq.web.pageobjects.BasePage;
import org.openqa.selenium.By;
import static com.codeborne.selenide.Selenide.*;
import static com.ebanq.web.other.Urls.CREATE_ACCOUNTS_PAGE;
import com.ebanq.web.elements.EbanqInput;
public class CreateNewAccountPage extends BasePage {
@Override
public CreateNewAccountPage isPageOpened() {
$(By.xpath("//div[contains(text(), 'Create New Account')]")).shouldBe(Condition.visible);
return this;
}
public CreateNewAccountPage openPage() {
open(CREATE_ACCOUNTS_PAGE);
return this;
}
public CreateNewAccountPage fillRequiredFields(Account account) {
new EbanqSelect("Account type")
.selectValue(account.getAccountType());
new EbanqInput("Account number")
.write(account.getAccountNumber());
new EbanqSelect("User")
.selectValue(account.getUser());
new EbanqSelect("Status")
.selectValue(account.getStatus());
new EbanqInput("Initial Balance")
.write(account.getInitialBalance());
return this;
}
public void clickCreateButton() {
$(By.xpath("//button[contains(text(), 'Create')]")).click();
isSuccessNotificationDisplayed();
}
public void isSuccessNotificationDisplayed() {
$(By.xpath("//*[contains(text(), 'Account has been successfully created')]")).shouldBe(Condition.visible);
}
public void isErrorNotificationDisplayed() {
$(By.xpath("//*[contains(text(), 'There are errors on the form. Please fix them and try submitting again.')]")).shouldBe(Condition.visible);
}
}
|
import java.util.ArrayList;
public class GridModel {
public final static String GRID_PROP = "Grid";
private int rows;
private int columns;
private GridPanel gridPanel;
private ArrayList<ArrayList<Cell>> grid;
public GridModel() {
this(10,10);
}
public GridModel(int rows, int columns) {
this.rows = rows;
this.columns = columns;
initGridList();
}
//Init arraylist and set all points as EMPTY
private void initGridList() {
grid = new ArrayList<ArrayList<Cell>>();
for (int y = 0; y < rows; y++) {
grid.add(new ArrayList<Cell>());
for (int x = 0; x < columns; x++) {
grid.get(y).add(Cell.EMPTY);
}
}
}
public void setCell(int x, int y, Cell cellType) {
if (!(this.grid.get(y).get(x).equals(cellType))) {
this.grid.get(y).set(x, cellType);
gridPanel.propertyChange(x, y, cellType);
}
}
public Cell getCell(int x, int y) {
return this.grid.get(y).get(x);
}
public int getRows() {
return this.rows;
}
public int getColumns() {
return this.columns;
}
public void setGridPanel(GridPanel gridPanel) {
this.gridPanel = gridPanel;
}
public String toString() {
String ret = "";
for (int y = 0; y < rows; y++) {
for (int x = 0; x < columns; x++) {
ret += (grid.get(y).get(x) + " ");
}
ret += "\n";
}
return ret;
}
public static void main(String[] args) {
GridModel gm = new GridModel();
System.out.println(gm);
}
}
|
package com.stk123.task.thread.pool;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ThreadPool {
private ExecutorService exec;
private CompletionService pool;
private ThreadPool(int poolSize){
exec = Executors.newFixedThreadPool(poolSize);
pool = new ExecutorCompletionService(exec);
}
public ThreadPool getInstance(int poolSize){
return new ThreadPool(poolSize);
}
public Future addTask(Callable task){
return pool.submit(task);
}
public Object getResult() throws Exception {
return pool.take().get();
}
public void shutdown(){
exec.shutdown();
}
}
|
package com.himanshu.springboot2.foundation.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import java.util.Map;
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true, securedEnabled=true)
public abstract class BaseSecurityConfigurer extends WebSecurityConfigurerAdapter {
private final String secureUrlRegex;
@Autowired
private AuthenticationProvider authenticationProvider;
public BaseSecurityConfigurer(String secureUrlRegex) {
this.secureUrlRegex = secureUrlRegex;
}
@Override
@Autowired
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
//Caused by: java.lang.IllegalArgumentException: role should not start with 'ROLE_' since it is automatically inserted. Got 'ROLE_ADMIN'
//Hence removing ROLE_
@Override
protected void configure(HttpSecurity http) throws Exception {
//super.configure(http);
http.addFilterAfter(new BasicAuthenticationFilter(authenticationManagerBean()), UsernamePasswordAuthenticationFilter.class)
.httpBasic()
.and()
.formLogin()
.and()
//.formLogin().loginPage("/login").loginProcessingUrl("/authenticate").failureUrl("/login-error").defaultSuccessUrl("/dashboard").usernameParameter("j_username").passwordParameter("j_password")
//.and()
//.logout().logoutUrl("/logout").logoutSuccessUrl("/login").invalidateHttpSession(true).deleteCookies("true")
//.and()
.authorizeRequests()
.antMatchers("/login**").permitAll()
//below access enables hawtio integration
.antMatchers("/actuator", "/actuator/jolokia", "/actuator/jolokia/**").permitAll()
.regexMatchers(secureUrlRegex).authenticated()
.anyRequest().authenticated()
/*.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.antMatchers("/api/**").hasRole("USER")
.antMatchers("/shared/**", "/friends/**", "/events/**", "/share/**", "/profile/**", "/dashboard/**").hasAnyRole("USER", "ADMIN")
.antMatchers("/reg/**", "/getting-started/**", "/contact-us/**", "/forgot-password/**").permitAll()*/
.and()
.csrf().disable()
/*.exceptionHandling()
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))*/;
}
}
|
package com.duanc.controller.phonecenter;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.duanc.api.BrandAndModelService;
import com.duanc.controller.BaseController;
import com.duanc.model.dto.BrandDTO;
import com.duanc.model.dto.ModelDTO;
import com.duanc.utils.JSONResult;
import com.duanc.utils.Pagination;
@Controller
@RequestMapping(value = "/authc")
public class ModelMngController extends BaseController{
@Autowired
private BrandAndModelService brandAndModelService;
@RequestMapping(value = "/model-mng")
@RequiresPermissions(value = {"manager:model-mng:search"})
public String showModel(Model model, BrandDTO brandDTO, Pagination pagination) {
if(brandDTO.getId() != null) {
pagination = brandAndModelService.getModelDataList(brandDTO.getId(), pagination);
model.addAttribute("pagination", pagination);
}
model.addAttribute("brandDTO", brandDTO);
initBrand(model);
return "phone-center/model-mng";
}
@RequestMapping(value = "/ajax-add-model", method = RequestMethod.POST)
@ResponseBody
public String addModel(ModelDTO modelDTO, Integer brandId) {
if(brandId != null && modelDTO.getModelName() != null && !StringUtils.isEmpty(modelDTO.getModelName())) {
if(brandAndModelService.addModel(modelDTO.getModelName(), brandId)){
JSONResult jr = new JSONResult();
jr.setSuccess(true);
jr.setMessage("添加成功");
String json = JSON.toJSONString(jr);
return json;
}
}
return null;
}
@RequestMapping(value = "/ajax-del-model", method = RequestMethod.POST)
@ResponseBody
public String delModel(ModelDTO modelDTO) {
if(modelDTO.getId() != null ) {
if(brandAndModelService.deleteModelById(modelDTO.getId())){
JSONResult jr = new JSONResult();
jr.setSuccess(true);
jr.setMessage("删除成功");
String json = JSON.toJSONString(jr);
return json;
}
}
return null;
}
@RequestMapping(value = "/ajax-update-model", method = RequestMethod.POST)
@ResponseBody
public String updateModel(ModelDTO modelDTO) {
if(modelDTO.getId() != null ) {
if(brandAndModelService.updateModel(modelDTO)){
JSONResult jr = new JSONResult();
jr.setSuccess(true);
jr.setMessage("修改成功");
String json = JSON.toJSONString(jr);
return json;
}
}
return null;
}
}
|
package com.esum.hotdeploy.component;
import com.esum.hotdeploy.DeploymentException;
import com.esum.hotdeploy.descriptor.ApplicationDescriptor;
public class ApplicationWrapper implements Application {
private Application delegate;
protected ApplicationWrapper(Application delegate) {
this.delegate = delegate;
}
public void dispose() throws DeploymentException {
delegate.dispose();
}
public ClassLoader getDeploymentClassLoader() {
return delegate.getDeploymentClassLoader();
}
public void init() throws DeploymentException {
final ClassLoader originalCl = Thread.currentThread().getContextClassLoader();
try {
ClassLoader appCl = getDeploymentClassLoader();
if (appCl != null) {
Thread.currentThread().setContextClassLoader(appCl);
}
delegate.init();
} finally {
Thread.currentThread().setContextClassLoader(originalCl);
}
}
public void install() throws DeploymentException {
final ClassLoader originalCl = Thread.currentThread().getContextClassLoader();
try {
ClassLoader appCl = getDeploymentClassLoader();
if (appCl != null) {
Thread.currentThread().setContextClassLoader(appCl);
}
delegate.install();
} finally {
Thread.currentThread().setContextClassLoader(originalCl);
}
}
public void redeploy() throws DeploymentException {
delegate.redeploy();
}
public void start() throws DeploymentException {
final ClassLoader originalCl = Thread.currentThread().getContextClassLoader();
try {
ClassLoader appCl = getDeploymentClassLoader();
if (appCl != null) {
Thread.currentThread().setContextClassLoader(appCl);
}
delegate.start();
} finally {
Thread.currentThread().setContextClassLoader(originalCl);
}
}
public void stop() throws DeploymentException {
final ClassLoader originalCl = Thread.currentThread().getContextClassLoader();
try {
ClassLoader appCl = getDeploymentClassLoader();
if (appCl != null) {
Thread.currentThread().setContextClassLoader(appCl);
}
delegate.stop();
} finally {
Thread.currentThread().setContextClassLoader(originalCl);
}
}
public String getAppName() {
return delegate.getAppName();
}
public ApplicationDescriptor getDescriptor() {
return delegate.getDescriptor();
}
@Override
public String toString() {
return String.format("%s(%s)", getClass().getName(), delegate);
}
public Application getDelegate() {
return delegate;
}
}
|
package com.union.express.commons.model.agingcycle;
import com.union.express.web.stowagecore.agingcycle.model.AgingCycle;
import java.util.Date;
/**
* Created by Administrator on 2016/11/17 0017.
*/
public class VDiscount {
private String id;
private String agingCycleId;
private double discount;
private Date startTime;
private AgingCycle agingCycle;
public AgingCycle getAgingCycle() {
return agingCycle;
}
public void setAgingCycle(AgingCycle agingCycle) {
this.agingCycle = agingCycle;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAgingCycleId() {
return agingCycleId;
}
public void setAgingCycleId(String agingCycleId) {
this.agingCycleId = agingCycleId;
}
public double getDiscount() {
return discount;
}
public void setDiscount(double discount) {
this.discount = discount;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
}
|
package com.hrm.provider;
import java.util.Map;
import org.apache.ibatis.jdbc.SQL;
import com.hrm.domain.Dept;
import com.hrm.domain.Job;
public class JobDynaSqlProvider {
//动态查找
public String selectJob(final Job job){
return new SQL(){{
SELECT("*");
FROM("job_inf");
if(job.getName()!=null&&!job.getName().equals("")){
WHERE("name like '%'+#{name}+'%'");
}
if(job.getRemark()!=null&&!job.getRemark().equals("")){
WHERE("remark like '%'+#{remark}+'%'");
}
}}.toString();
}
//页面
//select top pageSize*
//from job_inf
//where id not in(select top (pageNow-1)*pageSize id from Job_inf)
public String countJob(final Map params){
return new SQL(){{
Job job=(Job)params.get("job");
Integer pageSize=(Integer) params.get("pageSize");
Integer pageNow=(Integer) params.get("pageNow");
String sql1=" top "+pageSize+" *";
SELECT(sql1);
FROM("job_inf");
if(job!=null){
if(job.getName()!=null&&!job.getName().equals("")){
WHERE("name like '%'+#{job.name}+'%'");
}
if(job.getRemark()!=null&&!job.getRemark().equals("")){
WHERE("remark like '%'+#{job.remark}+'%'");
}
}
String sql2="id not in(select top "+(pageNow-1)*pageSize +" id from Job_inf)";
WHERE(sql2);
}}.toString();
}
//动态插入
public String insertJob(final Job job){
return new SQL(){{
INSERT_INTO("job_inf");
if(job.getName()!=null&&!job.getName().equals("")){
VALUES("name","#{name}");
}
if(job.getRemark()!=null&&!job.getRemark().equals("")){
VALUES("remark","#{remark}");
}
}}.toString();
}
//动态更新
public String updateJob(final Job job){
return new SQL(){{
UPDATE("job_inf");
if(job.getName()!=null&&!job.getName().equals("")){
SET("name=#{name}");
}
if(job.getRemark()!=null&&!job.getRemark().equals("")){
SET("remark=#{remark}");
}
WHERE("id=#{id}");
}}.toString();
}
}
|
package com.csc.capturetool.myapplication.base;
import java.lang.ref.WeakReference;
/**
* Created by SirdarYangK on 2018/11/2
* des:
*/
public class BasePresenter<V> {
protected WeakReference<V> weak;
protected V mView;
public void attachView(V view) {
weak = new WeakReference<V>(view);
mView = weak.get();
}
public boolean isViewAttached() {
return mView != null;
}
public void detachView() {
if (mView != null) {
mView = null;
}
}
}
|
public class featureDemo4{
public static void main(){
pub name =20;
}
}
|
/*
* 5.4.3
*/
public class Shine2 extends Turtle{
public static void main(String[] args){
Turtle.startTurtle(new Shine2());
}
public void start(){
int i=1;
while(i<20){
rt(100);
fd(50);
i=i+1;
}
}
}
|
package Peer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import static java.lang.System.exit;
public class MainGUI extends JFrame implements ActionListener {
private JButton search; //Buttons
private JButton dLoad;
private JButton close;
private JList jl; // List that will show found files
private JLabel label; //Label "File Name
private JTextField tf, tf2; // Two textfields: one is for typing a file name, the other is just to show the selected file
private DefaultListModel listModel; // Used to select items in the list of found files
private String str[] = {"Info1", "Info2", "Info3", "Info4", "Info5"}; // Files information
private Peer peer;
public MainGUI(Peer peer) {
super("Example GUI");
this.peer = peer;
setLayout(null);
setSize(500, 600);
label = new JLabel("File name:");
label.setBounds(50, 50, 80, 20);
add(label);
tf = new JTextField();
tf.setBounds(130, 50, 220, 20);
add(tf);
search = new JButton("Search");
search.setBounds(360, 50, 80, 20);
search.addActionListener(this);
add(search);
listModel = new DefaultListModel();
jl = new JList(listModel);
JScrollPane listScroller = new JScrollPane(jl);
listScroller.setBounds(50, 80, 360, 300);
add(listScroller);
dLoad = new JButton("Download");
dLoad.setBounds(200, 400, 130, 20);
dLoad.addActionListener(this);
add(dLoad);
tf2 = new JTextField();
tf2.setBounds(200, 430, 130, 20);
add(tf2);
close = new JButton("Close");
close.setBounds(360, 470, 80, 20);
close.addActionListener(this);
add(close);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == search) { // If search button is pressed show 25 randomly generated file info in text area
String fileName = tf.getText();
List<String> result;
try {
result = peer.search(fileName.split("\\|")[0]);
} catch (IOException e1) {
e1.printStackTrace();
return;
}
listModel.clear();
if (result == null || result.size() <= 0) {
tf2.setText("File not found");
} else {
for (String line : result) {
listModel.addElement(line);
}
}
} else if (e.getSource() == dLoad) { // If download button is pressed get the selected value from the list and show it in text field
boolean status = false;
try {
status = peer.downloadFile(jl.getSelectedValue().toString().split("\\|")[0]);
} catch (Exception e1) {
e1.printStackTrace();
}
if (status) {
tf2.setText("Downloaded completed");
} else {
tf2.setText("Downloaded failed");
}
} else if (e.getSource() == close) { // If close button is pressed exit
peer.closeConnection();
exit(0);
}
}
public static void main(String[] args) throws Exception {
String workingDir = args[0];
String FTAddress = args[1];
int FTPort = Integer.parseInt(args[2]);
int PeerPort = Integer.parseInt(args[3]);
Peer peer = new Peer(workingDir, PeerPort);
peer.connect(FTAddress, FTPort);
if (!peer.registerOnFT()) {
System.out.println("Couldn't connect to server");
exit(1);
}
MainGUI ex = new MainGUI(peer);
ex.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Close the window if x button is pressed
}
}
|
package com.emed.shopping.dao.mapper.admin.user;
import com.emed.shopping.dao.model.admin.user.ShopPermission;
import com.emed.shopping.util.CommonMapper;
/**
* @Author: 周润斌
* @Date: create in 上午 11:42 2018/1/26 0026
* @Description:
*/
public interface ShopPermissionMapper extends CommonMapper<ShopPermission> {
}
|
package com.junzhao.shanfen.adapter;
import android.content.Context;
import android.view.View;
import android.widget.TextView;
import com.junzhao.base.base.MLAdapterBase2;
import com.junzhao.shanfen.R;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
/**
* Created by Administrator on 2018/3/19.
*/
public class LZNewFriendAdapter extends MLAdapterBase2<String> {
public LZNewFriendAdapter(Context context, int viewXml) {
super(context, viewXml);
}
@ViewInject(R.id.tv_name)
public TextView tv_name;
@Override
protected void setItemData(View view, String data, int position) {
ViewUtils.inject(this, view);
tv_name.setText(data);
}
}
|
package kr.ac.kopo.project02.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import kr.ac.kopo.project02.vo.AccountVO;
import kr.ac.kopo.project02.vo.ClientVO;
import kr.ac.kopo.project02.vo.TransactionVO;
import kr.ac.kopo.util.ConnectionFactory;
import kr.ac.kopo.util.JDBCClose;
public class BankingDAO {
//로그인
public ClientVO loginDAO(ClientVO newClient) throws Exception {
Connection conn = null;
PreparedStatement pstmt = null;
ClientVO client = new ClientVO();
try {
conn = new ConnectionFactory().getConnection();
StringBuilder sql = new StringBuilder();
sql.append("SELECT * FROM CLIENTS ");
sql.append(" WHERE ID = ? AND PW = ? ");
pstmt = conn.prepareStatement(sql.toString());
pstmt.setString(1, newClient.getId());
pstmt.setString(2, newClient.getPw());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
String id = rs.getString("ID");
String pw = rs.getString("PW");
String name = rs.getString("NAME");
String birth_dt = rs.getString("BIRTH_DT");
String regist_dt = rs.getString("REGIST_DT");
String lac_dt = rs.getString("LAC_DT");
client = new ClientVO(id, pw, name, birth_dt, regist_dt, lac_dt);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCClose.close(conn, pstmt);
}
return client;
}
// 계좌 생성
public void addDAO(AccountVO newAccount) throws Exception {
Connection conn = null;
PreparedStatement pstmt = null;
PreparedStatement pstmt2 = null;
try {
conn = new ConnectionFactory().getConnection();
conn.setAutoCommit(false); //오토커밋 끄고
StringBuilder sql = new StringBuilder();
StringBuilder sql2 = new StringBuilder();
sql.append("INSERT INTO ACCOUNTS (BCODE, ACCOUNT_NO, ACCOUNT_ID, BALANCE, ALIAS) ");
sql.append(
" VALUES('101', TO_CHAR(SYSDATE,'YY') || TO_CHAR(SYSDATE,'DDD') || TO_CHAR(SYSTIMESTAMP,'HHMMSSFF1'), ? , ? , ? ) ");
pstmt = conn.prepareStatement(sql.toString());
pstmt.setString(1, newAccount.getAccount_id());
pstmt.setLong(2, newAccount.getBalance());
pstmt.setString(3, newAccount.getAlias());
pstmt.executeUpdate();
// 회원테이블에 최근 생성 날짜 정보 추가
sql2.append("UPDATE CLIENTS SET LAC_DT = SYSDATE WHERE ID = ? ");
pstmt2 = conn.prepareStatement(sql2.toString());
pstmt2.setString(1, newAccount.getAccount_id());
pstmt2.executeUpdate();
conn.commit();
} catch (Exception e) {
conn.rollback();
e.printStackTrace();
} finally {
JDBCClose.close(pstmt);
JDBCClose.close(conn, pstmt2);
}
}
// 계좌 별칭 수정
public int updateDAO(AccountVO newAccount) throws Exception {
Connection conn = null;
PreparedStatement pstmt = null;
int check = 0;
try {
conn = new ConnectionFactory().getConnection();
StringBuilder sql = new StringBuilder();
sql.append("UPDATE ACCOUNTS SET ALIAS = ? ");
sql.append(" WHERE ACCOUNT_ID = ? AND ACCOUNT_NO = ? ");
pstmt = conn.prepareStatement(sql.toString());
pstmt.setString(1, newAccount.getAlias());
pstmt.setString(2, newAccount.getAccount_id());
pstmt.setString(3, newAccount.getAccount_no());
check = pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCClose.close(conn, pstmt);
}
return check;
}
// 계좌 삭제
public int deleteDAO(AccountVO newAccount) throws Exception {
Connection conn = null;
PreparedStatement pstmt = null;
int check = 0;
try {
conn = new ConnectionFactory().getConnection();
StringBuilder sql = new StringBuilder();
sql.append("UPDATE ACCOUNTS SET BALANCE = NULL, ALIAS = '폐기' ");
sql.append(" WHERE ACCOUNT_ID = ? AND BCODE = '101' AND ACCOUNT_NO = ? AND BALANCE = 0 ");
pstmt = conn.prepareStatement(sql.toString());
pstmt.setString(1, newAccount.getAccount_id());
pstmt.setString(2, newAccount.getAccount_no());
check = pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCClose.close(conn, pstmt);
}
return check;
}
// 계좌 조회
public List<AccountVO> searchDAO(AccountVO newAccount) throws Exception {
List<AccountVO> list = new ArrayList<>();
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = new ConnectionFactory().getConnection();
StringBuilder sql = new StringBuilder();
sql.append("SELECT B.BNAME, A.ACCOUNT_NO, A.ACCOUNT_ID, A.BALANCE, A.ALIAS FROM ACCOUNTS A, BANKCODE B ");
sql.append(" WHERE 1=1 ");
sql.append(" AND A.BCODE = B.CODE ");
sql.append(" AND A.ACCOUNT_ID = ? ");
sql.append(" AND A.BALANCE IS NOT NULL ");
// null이 아니면 부분 출력
if (!(newAccount.getBcode() == null || newAccount.getBcode().equals(""))) {
sql.append(" AND A.BCODE = ? ");
}
pstmt = conn.prepareStatement(sql.toString());
pstmt.setString(1, newAccount.getAccount_id());
if (!(newAccount.getBcode() == null || newAccount.getBcode().equals(""))) {
pstmt.setString(2, newAccount.getBcode());
}
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
String bcode = rs.getString("BNAME");
String account_no = rs.getString("ACCOUNT_NO");
String account_id = rs.getString("ACCOUNT_ID");
long balance = rs.getLong("BALANCE");
String alias = rs.getString("ALIAS");
AccountVO account = new AccountVO(bcode, account_no, account_id, balance, alias);
list.add(account);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCClose.close(conn, pstmt);
}
return list;
}
// 거래 내역 조회
public List<TransactionVO> transDAO(AccountVO newAccount) throws Exception {
List<TransactionVO> list = new ArrayList<>();
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = new ConnectionFactory().getConnection();
StringBuilder sql = new StringBuilder();
sql.append("SELECT A.T_ID, A.ACCOUNT_NO, B.ACCOUNT_ID , A.T_TYPE, A.T_AMOUNT, A.T_DT, A.BALANCE ");
sql.append(" FROM TRANSACTION_HISTORY A, ACCOUNTS B ");
sql.append(" WHERE 1=1 ");
sql.append(" AND A.ACCOUNT_NO = B.ACCOUNT_NO ");
sql.append(" AND B.ACCOUNT_ID = ? ");
sql.append(" ORDER BY A.T_DT DESC ");
pstmt = conn.prepareStatement(sql.toString());
pstmt.setString(1, newAccount.getAccount_id());
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
String t_id = rs.getString("T_ID");
String account_no = rs.getString("ACCOUNT_NO");
String t_type = rs.getString("T_TYPE");
long t_amount = rs.getLong("T_AMOUNT");
String t_dt = rs.getString("T_DT");
long balance = rs.getLong("BALANCE");
TransactionVO tarnsaction = new TransactionVO(t_id, account_no, t_type, t_amount, t_dt, balance);
list.add(tarnsaction);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCClose.close(conn, pstmt);
}
return list;
}
// 계좌이체
public int transferDAO(AccountVO newAccount) throws Exception {
Connection conn = null;
PreparedStatement pstmt = null;
PreparedStatement pstmt2 = null;
PreparedStatement pstmt3 = null;
int check = 0;
try {
conn = new ConnectionFactory().getConnection();
conn.setAutoCommit(false); //오토커밋 끄고
StringBuilder sql = new StringBuilder();
StringBuilder sql2 = new StringBuilder();
StringBuilder sql3 = new StringBuilder();
//account 테이블
sql.append("UPDATE ACCOUNTS SET BALANCE = BALANCE - ? ");
sql.append(" WHERE ACCOUNT_NO = ? AND ACCOUNT_ID = ? ");
sql2.append("UPDATE ACCOUNTS SET BALANCE = BALANCE + ? ");
sql2.append(" WHERE ACCOUNT_NO = ? ");
//transaction 테이블
sql3.append("INSERT ALL ");
sql3.append(" INTO TRANSACTION_HISTORY (T_ID, ACCOUNT_NO, T_TYPE, T_AMOUNT, T_DT, BALANCE) ");
sql3.append(" VALUES(TH_SEQ.NEXTVAL, ? , '출금', ? , TO_CHAR(SYSDATE,'YYYY-MM-DD HH:MI:SS') ");
sql3.append(" , (SELECT BALANCE FROM ACCOUNTS WHERE ACCOUNT_NO = ? AND ACCOUNT_ID = ? )) ");
sql3.append(" INTO TRANSACTION_HISTORY (T_ID, ACCOUNT_NO, T_TYPE, T_AMOUNT, T_DT, BALANCE) ");
sql3.append(" VALUES(TH_SEQ.NEXTVAL, ? , '입금', ? , TO_CHAR(SYSDATE,'YYYY-MM-DD HH:MI:SS') ");
sql3.append(" , (SELECT BALANCE FROM ACCOUNTS WHERE ACCOUNT_NO = ? )) ");
sql3.append(" SELECT * FROM DUAL ");
//account 테이블
pstmt = conn.prepareStatement(sql.toString());
pstmt.setLong(1, newAccount.getBalance());
pstmt.setString(2, newAccount.getAccount_no());
pstmt.setString(3, newAccount.getAccount_id());
int a = pstmt.executeUpdate();
pstmt2 = conn.prepareStatement(sql2.toString());
pstmt2.setLong(1, newAccount.getBalance());
pstmt2.setString(2, newAccount.getAlias());//별명에 대상계좌 담아옴
int b = pstmt2.executeUpdate();
//transaction 테이블
pstmt3 = conn.prepareStatement(sql3.toString());
pstmt3.setString(1, newAccount.getAccount_no());
pstmt3.setLong(2, newAccount.getBalance());
pstmt3.setString(3, newAccount.getAccount_no());
pstmt3.setString(4, newAccount.getAccount_id());
pstmt3.setString(5, newAccount.getAlias());//별명에 대상계좌 담아옴
pstmt3.setLong(6, newAccount.getBalance());
pstmt3.setString(7, newAccount.getAlias());//별명에 대상계좌 담아옴
int c = pstmt3.executeUpdate();
conn.commit();
check = a + b + c;
} catch (Exception e) {
conn.rollback();
check = 0;
System.out.println("-> 거래 오류 발생. 트랜잭션 취소");
//e.printStackTrace();
} finally {
JDBCClose.close(pstmt);
JDBCClose.close(pstmt2);
JDBCClose.close(conn, pstmt3);
}
return check;
}
// 입출금
public int dewiDAO(AccountVO newAccount) throws Exception {
Connection conn = null;
PreparedStatement pstmt = null;
PreparedStatement pstmt2 = null;
int check = 0;
try {
conn = new ConnectionFactory().getConnection();
conn.setAutoCommit(false); //오토커밋 끄고
StringBuilder sql = new StringBuilder();
StringBuilder sql2 = new StringBuilder();
sql.append("UPDATE ACCOUNTS ");
if(newAccount.getAlias().equals("입금")) {
sql.append(" SET BALANCE = BALANCE + ? ");
} else if(newAccount.getAlias().equals("출금")) {
sql.append(" SET BALANCE = BALANCE - ? ");
}
sql.append(" WHERE ACCOUNT_NO = ? AND ACCOUNT_ID = ? ");
pstmt = conn.prepareStatement(sql.toString());
pstmt.setLong(1, newAccount.getBalance());
pstmt.setString(2, newAccount.getAccount_no());
pstmt.setString(3, newAccount.getAccount_id());
int a = pstmt.executeUpdate();
sql2.append("INSERT INTO TRANSACTION_HISTORY (T_ID, ACCOUNT_NO, T_TYPE, T_AMOUNT, T_DT, BALANCE) ");
sql2.append(" VALUES(TH_SEQ.NEXTVAL, ?, ?, ?, ");
sql2.append(" TO_CHAR(SYSDATE,'YYYY-MM-DD HH:MI:SS'), ");
sql2.append(" (SELECT BALANCE FROM ACCOUNTS WHERE ACCOUNT_NO = ? AND ACCOUNT_ID = ? )) ");
pstmt2 = conn.prepareStatement(sql2.toString());
pstmt2.setString(1, newAccount.getAccount_no());
pstmt2.setString(2, newAccount.getAlias());//임시로 타입으로 사용
pstmt2.setLong(3, newAccount.getBalance());//임시로 금액으로 사용
pstmt2.setString(4, newAccount.getAccount_no());
pstmt2.setString(5, newAccount.getAccount_id());
int b = pstmt2.executeUpdate();
conn.commit();
check = a + b;
} catch (Exception e) {
conn.rollback();
check = 0;
System.out.println("-> 거래 오류 발생. 트랜잭션 취소");
//e.printStackTrace();
} finally {
JDBCClose.close(pstmt);
JDBCClose.close(conn, pstmt2);
}
return check;
}
}
|
package arien_coba5;
public class Arien_coba5 {
public static void main(String[] args) {
int c;
for (c = 1; c <= 13; c++) {
System.out.println(c);
}
}
}
|
package org.apache.cassandra.db;
import java.nio.ByteBuffer;
import org.apache.cassandra.net.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xerial.snappy.Snappy;
public class AppliedOperations
{
//WL TODO reduce the granularity of synchronization here
public static synchronized void addPendingOp(ByteBuffer locatorKey, long timestamp)
{
throw new UnsupportedOperationException();
}
public static synchronized void addAppliedOp(ByteBuffer locatorKey, long timestamp)
{
throw new UnsupportedOperationException();
}
}
|
package junseong.android.myapplication.room;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.Query;
import java.util.List;
import junseong.android.myapplication.model.ItemModel;
@Dao
public interface ArticleDAO {
@Query("SELECT * FROM article")
List<ItemModel> getAll();
@Insert
void insertAll(ItemModel... users);
@Query("DELETE FROM article")
void deleteAll();
}
|
package com.pronix.android.apssaataudit;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.pronix.android.apssaataudit.Dal.DalWorksiteDetails;
import com.pronix.android.apssaataudit.common.Constants;
import com.pronix.android.apssaataudit.db.DBManager;
import com.pronix.android.apssaataudit.pojo.Habitations;
import com.pronix.android.apssaataudit.pojo.Villages;
import com.pronix.android.apssaataudit.render.CommonSpinnerAdapter;
import java.util.ArrayList;
public class DoortoDoorF5Ativity extends BaseActivity {
Button btn_search;
EditText et_WorkCode;
AutoCompleteTextView actv_WorkId;
private ArrayList<String> checkList = new ArrayList<String>();
private ArrayList<String> checkList2 = new ArrayList<String>();
TextView tv_PanchayatTotal, tv_PanchayatCompleted, tv_VillageTotal, tv_VillageCompleted;
TextView tv_PanchayatName;
Spinner sp_VillageCode;
ArrayList<Villages> villagesArrayList = new ArrayList<>();
ArrayList<String> workCodesArralist = new ArrayList<>();
String assemblyCode = "";
DalWorksiteDetails dalWorksiteDetails;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLayoutInflater().inflate(R.layout.activity_doortodoor5a, frame_base);
dalWorksiteDetails = new DalWorksiteDetails();
initializeControls();
et_WorkCode = (EditText) findViewById(R.id.householdCode);
et_WorkCode.setEnabled(false);
btn_search= (Button) findViewById(R.id.btn_search);
btn_search.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!et_WorkCode.getText().toString().equalsIgnoreCase("")){
checkData();
}else{
Toast.makeText(DoortoDoorF5Ativity.this,"Please enter work code",Toast.LENGTH_SHORT).show();
}
}
});
//Checking if items are there in Format4A table
checkDataForm5aTable();
}
public void initializeControls()
{
sp_VillageCode = (Spinner) findViewById(R.id.sp_VillageCode);
villagesArrayList = dalWorksiteDetails.getVillages(String.valueOf(Constants.PANCHAYATID));
tv_PanchayatTotal = (TextView) findViewById(R.id.tv_panchayatTotal);
tv_PanchayatCompleted = (TextView) findViewById(R.id.tv_panchayatCompleted);
tv_VillageTotal = (TextView) findViewById(R.id.tv_VillageTotal);
tv_VillageCompleted = (TextView) findViewById(R.id.tv_VillageCompleted);
actv_WorkId = (AutoCompleteTextView) findViewById(R.id.actv_WorkId);
tv_PanchayatName = (TextView) findViewById(R.id.tv_PanchayatName);
tv_PanchayatName.setText("Panchayat : " + Constants.PANCHAYATNAME);
String[] value = dalWorksiteDetails.getTotalRecords(String.valueOf(Constants.PANCHAYATID));
assemblyCode = dalWorksiteDetails.getworkCode(String.valueOf(Constants.DISTRICTID), String.valueOf(Constants.MANDALID), String.valueOf(Constants.PANCHAYATID));
tv_PanchayatTotal.setText(value[0]);
tv_PanchayatCompleted.setText(value[1]);
CommonSpinnerAdapter adapter = new CommonSpinnerAdapter(this, villagesArrayList);
sp_VillageCode.setAdapter(adapter);
sp_VillageCode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String districtCode = villagesArrayList.get(i).getDistrictCode();
String mandalCode = villagesArrayList.get(i).getMandalCode();
String panchayatCode = String.valueOf(Constants.PANCHAYATID);
String villageCode = villagesArrayList.get(i).getVillageCode();
districtCode = (districtCode.length() > 1 ? districtCode : "0" + districtCode);
mandalCode = mandalCode.length() > 1 ? mandalCode : "0" + mandalCode;
villageCode = villageCode.length() > 1 ? villageCode : "0" + villageCode;
panchayatCode = panchayatCode.length() > 1 ? panchayatCode : "0" + panchayatCode;
String[] value = dalWorksiteDetails.getVillageWiseTotalRecords(villagesArrayList.get(i).getVillageCode());
et_WorkCode.setText(districtCode + assemblyCode + mandalCode + panchayatCode + villageCode);
tv_VillageTotal.setText(value[0]);
tv_VillageCompleted.setText(value[1]);
workCodesArralist = dalWorksiteDetails.getworkCodes(villagesArrayList.get(i).getVillageCode(), String.valueOf(Constants.PANCHAYATID));
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(DoortoDoorF5Ativity.this, android.R.layout.select_dialog_item, workCodesArralist);
actv_WorkId.setThreshold(1);
actv_WorkId.setAdapter(adapter);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void checkData() {
try {
//opening the database
String workCardIdstr = et_WorkCode.getText().toString() + "" + actv_WorkId.getText().toString();
//we used rawQuery(sql, selectionargs) for fetching all the employees
Cursor cursorEmployees = DBManager.getInstance().getRawQuery("SELECT * FROM worksite WHERE work_code IN ('" + workCardIdstr + "')");
//if the cursor has some data
if (cursorEmployees.moveToFirst()) {
//looping through all the records
do {
checkList.add(cursorEmployees.getString(1));
} while (cursorEmployees.moveToNext());
}
//closing the cursor
cursorEmployees.close();
System.out.println("-----------checking employees with work code array size: " + checkList.size());
if (checkList.size() == 0) {
Toast.makeText(DoortoDoorF5Ativity.this, "Please enter valid Work code", Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(DoortoDoorF5Ativity.this, Format5ARow.class);
intent.putExtra("work_code", workCardIdstr);
startActivity(intent);
DoortoDoorF5Ativity.this.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
finish();
}
}catch (SQLException error){
System.out.println("error: "+error.toString());
}
}
public void checkDataForm5aTable(){
Cursor cursorFormat5A = DBManager.getInstance().getRawQuery("SELECT * FROM format5A");
//if the cursor has some data
if (cursorFormat5A.moveToFirst()) {
//looping through all the records
do {
checkList2.add(cursorFormat5A.getString(19));
System.out.println("date: "+cursorFormat5A.getString(19));
} while (cursorFormat5A.moveToNext());
}
//closing the cursor
cursorFormat5A.close();
System.out.println("Format 5A Size: "+checkList2.size());
}
}
|
package nz.ac.aut.prog2.minesweeper.model;
import org.junit.After;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
/**
* Test framework for the Mine class.
*
* @author Anne Philpott and Stefan Marks
* @version v1.0 - 2012.06: Created
*/
public class MineTest
{
private MineWorld world;
private Position position;
private Mine testMine;
/**
* Default constructor for the test class.
*/
public MineTest()
{
}
/**
* Sets up the test fixture.
*
* Called before every test case method.
*/
@Before
public void setUp()
{
world = new MineWorld(6, 6);
position = new Position(world, 4,3);
testMine = new Mine(position);
}
/**
* Tears down the test fixture.
*
* Called after every test case method.
*/
@After
public void tearDown()
{
testMine = null;
world = null;
position = null;
}
/**
* Test of getStringRepresentation method, of class Mine.
*/
@Test
public void testGetStringRepresentation()
{
assertEquals("X", testMine.getStringRepresentation());
}
}
|
package io.github.biezhi.java8.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
/**
* 原子变量
* <p>
* AtomicInteger
* LongAdder
* LongAccumulator
*
* @author biezhi
* @date 2018/3/5
*/
public class AtomicExample {
public static void main(String[] args) {
AtomicInteger atomicInt = new AtomicInteger(0);
ExecutorService executor = Executors.newFixedThreadPool(2);
IntStream.range(0, 1000)
.forEach(i -> executor.submit(atomicInt::incrementAndGet));
stop(executor);
System.out.println(atomicInt.get());
}
public static void stop(ExecutorService executor) {
try {
System.out.println("attempt to shutdown executor");
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
System.err.println("tasks interrupted");
} finally {
if (!executor.isTerminated()) {
System.err.println("cancel non-finished tasks");
}
executor.shutdownNow();
System.out.println("shutdown finished");
}
}
}
|
package ac.a14ehsr.platform;
import java.io.IOException;
import java.util.Arrays;
import ac.a14ehsr.exception.TimeoutException;
import ac.a14ehsr.platform.visualizer.Visualizer;
import ac.a14ehsr.player.HumanPlayer;
import ac.a14ehsr.player.Player;
import java.awt.Color;
public class TronBattle extends Game {
public static final int DEATH = 0;
public static final int ALIVE = 1;
public static final int UP = 1;
public static final int RIGHT = 2;
public static final int DOWN = 3;
public static final int LEFT = 4;
private static final int NOT_ACHIEVED = -1;
private static final int WALL = -2;
private int width;
private int height;
private int[][] board; // 1 <= x <= width, 1 <= y <= height
private int[][] nowPosition; // position of players. nowPosition[player] = {x,y}
private int[][] initialPosition; // position of players. nowPosition[player] = {x,y}
private int aliveCount;
private int deathCount;
public TronBattle(int numberOfPlayers, int numberOfGames, long timelimit, boolean isVisible, int outputLevel, Player[] players, int width, int height) {
super(numberOfPlayers, numberOfGames, timelimit, isVisible, outputLevel, players);
this.width = width;
this.height = height;
board = makeBoard();
//*
if(isVisible) {
setVisualizer(new Visualizer(width, height));
}
//*/
}
public TronBattle(int numberOfPlayers, Player[] players, Visualizer visualizer) {
super(numberOfPlayers, 1, 3000, true, 3, players);
this.width = 30;
this.height = 20;
board = makeBoard();
setVisualizer(visualizer);
}
/**
* 盤を作成する
* 四辺は壁とする
*/
public int[][] makeBoard() {
int[][] board = new int[height + 2][width + 2];
for(int[] a : board) {
Arrays.fill(a, NOT_ACHIEVED);
}
for(int x = 0; x <= width+1; x++) {
board[0][x] = WALL;
board[height + 1][x] = WALL;
}
for(int y = 0; y <= height+1; y++) {
board[y][0] = WALL;
board[y][width + 1] = WALL;
}
return board;
}
@Override
void initialize() throws IOException {
board = makeBoard();
initialPosition = new int[numberOfPlayers][2];
nowPosition = new int[numberOfPlayers][2];
for(int p = 0; p < numberOfPlayers; p++) {
int[] tmp = new int[]{-1,-1};
boolean check;
do {
check = true;
tmp = new int[]{(int)(Math.random() * width) + 1, (int)(Math.random() * height) + 1};
for(int k = 0; k < p; k++) {
if(tmp[0] == nowPosition[k][0] && tmp[1] == nowPosition[k][1]) {
check = false;
break;
}
}
} while(!check);
initialPosition[p] = tmp.clone();
nowPosition[p] = tmp.clone();
if(isVisible) {
int code = players[p].getCode();
visualizer.setColor(code, nowPosition[code][0], nowPosition[code][1]);
visualizer.setBorder(nowPosition[code][0], nowPosition[code][1], Color.WHITE, 3);
visualizer.resetNameColor();
}
board[tmp[1]][tmp[0]] = players[p].getCode();
}
for(Player player : players) {
player.setStatus(ALIVE);
player.setGamePoint(numberOfPlayers);
//*
if(player.isHuman()) {
((HumanPlayer)player).setBoard(board, nowPosition);
}
//*/
}
aliveCount = numberOfPlayers;
deathCount = 0;
}
@Override
boolean isContinue() {
if(numberOfPlayers == 1) {
return players[0].getStatus() != DEATH;
}
return Arrays.stream(players).filter(player -> player.getStatus() == ALIVE).count() > 1;
}
@Override
void sendGameInfo() throws IOException {
super.sendGameInfo();
for(Player player : players) {
player.sendNum(width);
player.sendNum(height);
}
}
String positionToString(Player player) {
int[] position = nowPosition[player.getCode()];
return String.format("%10s:(%2d %2d)", player.getName(), position[0], position[1]);
}
@Override
void play() {
for(int p = 0; p < numberOfPlayers; p++) {
Player player = players[p];
if(player.getStatus() == DEATH) {
continue;
}
for(int k = 0; k < numberOfPlayers; k++) {
try{
player.sendNumArray(getPlayerSendNumPair(players[k]));
} catch(IOException e) {
System.out.println("送信時エラー");
e.printStackTrace();
kill(players[k]);
}
}
if(outputLevel == 3) {
for(int k = 0; k < numberOfPlayers; k++) {
System.out.print(positionToString(players[k]) + " ");
}
System.out.println();
}else if(outputLevel == 4) {
show();
}
int code = player.getCode();
if(isVisible) {
visualizer.setNameBorder(p, Color.WHITE);
}
visualizer.setBorder(nowPosition[code][0], nowPosition[code][1], Color.WHITE, 6);
int direction = put(player);
if(nowPosition[code][0] != -1 && isVisible) {
visualizer.setColor(code, nowPosition[code][0], nowPosition[code][1]);
visualizer.setBorder(nowPosition[code][0], nowPosition[code][1], Color.WHITE, 3);
try{
Thread.sleep(10);
}catch(Exception e) {
e.printStackTrace();
}
}
if(isVisible) {
visualizer.setNameBorder(p, Color.BLACK);
}
}
//Arrays.stream(players).forEach(p -> System.err.print(p.getGamePoint() + " "));
//System.err.println();
if(aliveCount == 1) {
//System.err.println("優勝者判定");
//Arrays.stream(players).filter(p -> p.getStatus() == ALIVE).forEach(System.out::println);
int[] points = {1,3,6,10,15,25};
Arrays.stream(players).filter(p -> p.getStatus() == ALIVE).forEach(p -> p.setGamePoint(points[deathCount]));
//Arrays.stream(players).forEach(p -> System.err.print(p.getGamePoint() + " "));
}
}
int[] getPlayerSendNumPair(Player player) {
if(player.getStatus() == DEATH) {
//System.err.println("p:" + player.getCode() + " : {-1}");
return new int[]{-1,-1,-1,-1};
}
int pCode = player.getCode();
return new int[]{initialPosition[pCode][0], initialPosition[pCode][1], nowPosition[pCode][0], nowPosition[pCode][1]};
}
int put(Player player) {
if(player.getStatus() == DEATH) {
//System.err.println("もともと死んでる");
return DEATH;
}
int direction = DEATH;
try {
direction = player.receiveNum(timelimit+1000, timelimit);
}catch(Exception e) {
e.printStackTrace();
kill(player);
return DEATH;
}
int playerCode = player.getCode();
int x = nowPosition[playerCode][0];
int y = nowPosition[playerCode][1];
switch(direction) {
case UP:
y++;
break;
case DOWN:
y--;
break;
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
default:
if(outputLevel >= 2){
System.out.println("存在しない移動パターンの値が入力されました | プレイヤー:" + player.getName());
}
kill(player);
return DEATH;
}
if(y < 0 || y > board.length || x < 0 || x > board[y].length || board[y][x] == WALL) {
if(outputLevel >= 2){
System.out.println("ボードの範囲外に移動しようとしました | プレイヤー:" + player.getName());
}
kill(player);
return DEATH;
}
if(board[y][x] != NOT_ACHIEVED) {
if(outputLevel >= 2){
System.out.println("獲得済みのマスに移動しようとしました | プレイヤー:" + player.getName());
}
kill(player);
return DEATH;
}
int code = player.getCode();
board[y][x] = code;
visualizer.setBorder(nowPosition[code][0], nowPosition[code][1], Color.BLACK, 1);
nowPosition[player.getCode()] = new int[]{x,y};
return direction;
}
/**
* playerに行動不能等の状態を付与
* プレイヤーの現在座標を{-1,-1}に変更し,
* プレイヤーが獲得した盤面を解放する
* @param player
*/
void kill(Player player) {
int[] points = {1,3,6,10,15,25};
player.setStatus(DEATH);
player.setGamePoint(points[deathCount++]);
aliveCount--;
if(isVisible) {
visualizer.setBorder(nowPosition[player.getCode()][0], nowPosition[player.getCode()][1], Color.BLACK, 1);
}
nowPosition[player.getCode()] = new int[]{-1,-1};
if(isVisible) {
try {
Thread.sleep(300);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
deletePlayer(player);
}
@Override
void calcGameResult() {
for(Player player : players) {
player.setSumPoint(player.getSumPoint() + (numberOfPlayers - player.getGamePoint()));
}
}
@Override
void show() {
System.out.print("|");
for(int x = 1; x <= width; x++) {
System.out.print("---");
}
System.out.println("|");
for(int y = 1; y <= height; y++) {
System.out.print("|");
for(int x = 1; x <= width; x++) {
System.out.printf("%2d ",board[y][x]);
}
System.out.println("|");
}
System.out.print("|");
for(int x = 1; x <= width; x++) {
System.out.print("---");
}
System.out.println("|");
}
@Override
void showGameResult() {
if(outputLevel >= 2) {
System.out.print("GAME POINT: ");
for(Player player : players) {
System.out.printf("%10s ",player.getName());
}
System.out.print(" | ");
for(Player player : players) {
System.out.printf("%2d ",player.getGamePoint());
}
System.out.println();
}
}
void sendSize() throws IOException {
for(Player player : players) {
player.sendNum(width);
player.sendNum(height);
}
}
/**
* playerが獲得した盤面を解放する
* @param player
*/
public void deletePlayer(Player player) {
int code = player.getCode();
for(int y = 1; y <= height; y++) {
for(int x = 1; x <= width; x++) {
if(board[y][x] == code) {
board[y][x] = -1;
if(isVisible) {
visualizer.relese(player.getCode(), x, y);
visualizer.setNameColor(player.getCode(), Color.BLACK);
}
}
}
}
if(isVisible) {
visualizer.validate();
try {
Thread.sleep(300);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
|
package com.edasaki.rpg.mobs;
import java.util.HashMap;
public enum MobAttribute {
RAPID("rapid"), // rapidfire
PASSIVE("passive"), // passive mob
RANGED("ranged"), // no melee
ARROW1("arrow1"), // tier 1 arrow shooter
ARROW2("arrow2"), // tier 2 arrow shooter
ARROW3("arrow3"), // tier 3 arrow shooter
ARROW4("arrow4"), // tier 4 arrow shooter
ARROW5("arrow5"), // tier 5 arrow shooter
HYPERGOLEM("hypergolem"), // hyper golem
LOWKNOCKBACK("lowknockback"), // mob only gets knocked back a bit
ANGRYWOLF("angrywolf"), // red eye wolf
TAMED("tamed"), // tamed mob
LOWWANDER("lowwander"), // returns to original loc every 10 sec
POISON1("poison1"), // inflict level 1 poison for 5 seconds
BABY("baby"),
CHICKEN1("chicken1"), //chicken mount
HORSE1("horse1"), //med speed horse mount
HUSK("husk"), // husk
STRAY("stray"), //stray
WITHER("wither"), //wither,
SLIME1("slime1"), // small slime
SLIME2("slime2"), // med slime
SLIME3("slime3"), // large slime
SLIME4("slime4"), // giant slime
SLIME5("slime5"), // giant slime
SLIME6("slime6"), // giant slime
SLIME7("slime7"), // giant slime
SLIME8("slime8"), // giant slime
NODROP("nodrop"), // does not drop randomly generated items
SLOW1("slow1"), // kinda slow
SLOW2("slow2"), // pretty slow
SLOW3("slow3"), // really slow
FAST1("fast1"), // kinda fast
FAST2("fast2"), // pretty fast
FAST3("fast3"), // ultra fast
BOSS("boss"), // has gold boss name
ANGELWINGS("angelwings"), //
INVISIBLE("invisible"),
RANDOMPASSIVE("randompassive"), //passive, but they run around randomly
;
private static HashMap<String, MobAttribute> map = new HashMap<String, MobAttribute>();
static {
for (MobAttribute ma : MobAttribute.values())
map.put(ma.id, ma);
}
private String id;
MobAttribute(String id) {
this.id = id;
}
public static MobAttribute get(String s) {
return map.get(s);
}
}
|
package cn.v5cn.v5cms.dao;
import cn.v5cn.v5cms.entity.Site;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by ZYW on 2014/6/30.
*/
@Repository("siteDao")
public interface SiteDao extends JpaRepository<Site,Long> {
/**
* ==============================================================
*
* 后端方法
*
* ==============================================================
**/
/**
* 根据站点ID查询站点。
* */
Site findBySiteId(Long siteId);
/**
* 根据运行状态值查询站点
* */
List<Site> findByIsclosesite(int isclosesite);
/**
* 根据域名查询域名的个数
* */
long countByDomainAndSiteIdNot(String domain,Long siteId);
/**
* ==============================================================
*
* 前端方法
*
* ==============================================================
**/
/**
* 根据域名查询站点信息。
* @param domain 域名,例如:wwww.explatem.com
* */
Site findByDomain(String domain);
}
|
package com.hjc.java_common_tools.guava;
import org.junit.Test;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
/**
* http://www.cnblogs.com/peida/p/3224706.html
*
*/
public class EventBus_Study {
@Test
public void testSingleListener() throws Exception {
EventBus eventBus = new EventBus("test");
MyEventListener listener = new MyEventListener();
eventBus.register(listener);
eventBus.post(new TestEvent("你好,何健超"));
eventBus.post(new TestEvent("你好,java"));
eventBus.post(new TestEvent("你好,world"));
System.out.println("LastMessage:" + listener.getLastMessage());
}
@Test
public void testMultipleEvents() throws Exception {
EventBus eventBus = new EventBus("test");
MultipleListener multiListener = new MultipleListener();
eventBus.register(multiListener);
eventBus.post(new Integer(100));
eventBus.post(new Integer(200));
eventBus.post(new Integer(300));
eventBus.post(new Long(800));
eventBus.post(new Long(800990));
eventBus.post(new Long(800882934));
System.out.println("LastInteger:" + multiListener.getLastInteger());
System.out.println("LastLong:" + multiListener.getLastLong());
}
}
class TestEvent {
private final String message;
public TestEvent(String message) {
this.message = message;
System.out.println("event message:" + message);
}
public String getMessage() {
return message;
}
}
class MyEventListener {
public String lastMessage;
@Subscribe
public void listen(TestEvent event) {
lastMessage = event.getMessage();
System.out.println("Message:" + lastMessage);
}
public String getLastMessage() {
return lastMessage;
}
}
class MultipleListener {
public Integer lastInteger;
public Long lastLong;
@Subscribe
public void listenInteger(Integer event) {
lastInteger = event;
System.out.println("event Integer:" + lastInteger);
}
@Subscribe
public void listenLong(Long event) {
lastLong = event;
System.out.println("event Long:" + lastLong);
}
public Integer getLastInteger() {
return lastInteger;
}
public Long getLastLong() {
return lastLong;
}
}
|
package lxy.liying.circletodo.operation;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewFlipper;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import lxy.liying.circletodo.R;
import lxy.liying.circletodo.adapter.CalendarAdapter;
import lxy.liying.circletodo.adapter.YearAdapter;
import lxy.liying.circletodo.app.App;
import lxy.liying.circletodo.ui.CalendarActivity;
/**
* =======================================================
* 版权:©Copyright LiYing 2015-2016. All rights reserved.
* 作者:liying
* 日期:2016/8/15 19:46
* 版本:1.0
* 描述:年份选择器
* 备注:
* =======================================================
*/
public class YearSelector implements View.OnClickListener {
private CalendarActivity activity;
private CalendarAdapter calendarAdapter;
private ViewFlipper flipper;
private GridView gridView;
private TextView currentMonth;
public YearSelector(CalendarActivity activity, CalendarAdapter calendarAdapter, ViewFlipper flipper,
GridView gridView, TextView currentMonth) {
this.activity = activity;
this.calendarAdapter = calendarAdapter;
this.flipper = flipper;
this.gridView = gridView;
this.currentMonth = currentMonth;
}
@Override
public void onClick(View v) {
AlertDialog.Builder builder = App.getAlertDialogBuilder(activity);
View view = activity.getLayoutInflater().inflate(R.layout.dialog_year_list, null);
ListView lvYearList = (ListView) view.findViewById(R.id.lvYearList);
TextView tvGoCurrentMonth = (TextView) view.findViewById(R.id.tvGoCurrentMonth);
YearAdapter adapter = new YearAdapter(activity);
lvYearList.setAdapter(adapter);
lvYearList.setSelection(activity.year_c - 1970);
builder.setView(view);
final AlertDialog dialog = builder.create();
dialog.show();
lvYearList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
flipper.removeAllViews();
activity.year_c = position + 1970;
activity.month_c = 1;
CalendarActivity.jumpMonth = 0;
calendarAdapter.setData(0, activity.year_c, activity.month_c);
activity.addGridView();
gridView.setAdapter(calendarAdapter);
flipper.addView(gridView, 0);
activity.addTextToTopTextView(currentMonth);
dialog.dismiss();
}
});
// 转到本月
tvGoCurrentMonth.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
flipper.removeAllViews();
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d", Locale.getDefault());
CalendarActivity.currentDate = sdf.format(date); // 当期日期
activity.year_c = Integer.parseInt(CalendarActivity.currentDate.split("-")[0]);
activity.month_c = Integer.parseInt(CalendarActivity.currentDate.split("-")[1]);
CalendarActivity.jumpMonth = 0;
calendarAdapter.setData(0, activity.year_c, activity.month_c);
activity.addGridView();
gridView.setAdapter(calendarAdapter);
flipper.addView(gridView, 0);
activity.addTextToTopTextView(currentMonth);
dialog.dismiss();
}
});
}
}
|
package uiElements;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import utils.exception.ImageException;
public class ImageScaled extends JLabel {
public ImageScaled(){
super("");
}
public ImageScaled(String file, int w, int h){
super("");
try {
this.setIcon(resize(file, w, h));
} catch (ImageException e) {
this.setText("Err");
}
}
private ImageIcon resize(String file, int w, int h) throws ImageException{
BufferedImage img;
Image dimg;
double ratio;
try {
img = ImageIO.read(new File(file));
ratio = 1;
if (img.getWidth() > w) ratio = img.getWidth()/w;
if (img.getHeight() > h && ratio < img.getHeight()/h) ratio = img.getHeight()/h;
dimg = img.getScaledInstance((int)Math.round(img.getWidth()/ratio), (int)Math.round(img.getHeight()/ratio), Image.SCALE_SMOOTH);
return new ImageIcon(dimg);
} catch (IOException e) {
throw new ImageException(ImageException.FILENOTFOUND, file);
}
}
}
|
package com.eshop.config;
import com.eshop.exception.LoginException;
import com.eshop.exception.NoAddressException;
import com.eshop.exception.NoProductInBasketException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import java.lang.ClassCastException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
@ControllerAdvice
public class ExceptionControllerAdvice {
private static String ATTR_NAME = "errMsg";
private static String VIEW_NAME = "error";
private Logger logger = Logger.getLogger("logger");
@ExceptionHandler(IllegalArgumentException.class)
public ModelAndView handleMyException2(IllegalArgumentException mex) {
ModelAndView model = new ModelAndView();
model.addObject(ATTR_NAME, "Sorry, not enough amount of product");
logger.info("Attempt to login with exisring email");
logger.log(Level.WARNING, "Not enough amount of product");
model.setViewName(VIEW_NAME);
return model;
}
@ExceptionHandler(LoginException.class)
public ModelAndView handleMyException3(LoginException mex) {
ModelAndView model = new ModelAndView();
model.addObject(ATTR_NAME, "Sorry, user with such email already exists." +
"Please, enter another login.");
model.setViewName(VIEW_NAME);
logger.info("Attempt to login with exisring email");
return model;
}
@ExceptionHandler(NoAddressException.class)
public ModelAndView handleMyException4(NoAddressException mex) {
ModelAndView model = new ModelAndView();
model.addObject(ATTR_NAME, mex.getMessage());
model.setViewName(VIEW_NAME);
logger.info("Attempt to register without address");
return model;
}
@ExceptionHandler(NoProductInBasketException.class)
public ModelAndView handleMyException4(NoProductInBasketException mex) {
ModelAndView model = new ModelAndView();
model.addObject(ATTR_NAME, "You should choose any product first");
model.setViewName(VIEW_NAME);
logger.info("Attempt to make with empty basket");
return model;
}
@ExceptionHandler(ClassCastException.class)
public ModelAndView handleMyException(ClassCastException mex) {
ModelAndView model = new ModelAndView();
model.addObject(ATTR_NAME, "Please, sign in first!");
model.setViewName(VIEW_NAME);
return model;
}
@ExceptionHandler(Exception.class)
public ModelAndView handleException(Exception ex) {
logger.log(Level.ALL, ex.getMessage());
ModelAndView model = new ModelAndView();
model.addObject(ATTR_NAME, "Sorry, something went wrong :(");
model.setViewName(VIEW_NAME);
return model;
}
@ExceptionHandler(SQLException.class)
public ModelAndView handleExceptionFromDB(SQLException ex) {
logger.log(Level.ALL, ex.getMessage());
ModelAndView model = new ModelAndView();
model.addObject(ATTR_NAME, "Can't delete category with existing products");
model.setViewName(VIEW_NAME);
return model;
}
}
|
package go.app.greeter;
public abstract class GreeterBase implements IGreeter {
@Override
public String greet(String name, String language) {
String greeting = "Invalid language";
if (language.equals("afr")) {
greeting = "Goeie dag, " + name;
} else if ("eng".equals(language)) {
greeting = "Good day, " + name;
} else if ("xhosa".equals(language)) {
greeting = "Molo, " + name;
}
if (!greeting.equals("Invalid language")) {
updateCount(name);
}
return greeting;
}
public abstract void updateCount(String name);
}
|
package lab6;
import java.io.IOException;
import java.util.LinkedList;
class Main {
public static void main(String[] args)throws IOException {
Graph gh = Graph.fromFile("./lab6/graphData");
gh.printGraph();
// ArrayList<Integer> path = gh.DFS(1);
// System.out.println("DFS from 1: ");
// System.out.println(path);
Graph kruskal = gh.kruskalMST();
System.out.println("Minimum spanning tree: ");
System.out.println("Kruskals: ");
kruskal.printGraph();
System.out.println("Prims: ");
Graph prims= gh.primsMst();
prims.printGraph();
}
}
|
package com.mall.backend.web;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ImgServlet
*/
@WebServlet("/ImgServlet")
public class ImgServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取请求参数imgurl
String imgurl = request.getParameter("imgurl");
//表单验证
//执行逻辑
String realPath = this.getServletContext().getRealPath(imgurl);
FileInputStream fis = null;
try{
//创建文件输入流,读取图片内容
fis = new FileInputStream(realPath);
//获取向response缓冲区写入内容输出流对象
ServletOutputStream sos = response.getOutputStream();
byte[] array = new byte[100];
int len = fis.read(array);
while(len!=-1){
sos.write(array, 0, len);
len = fis.read(array);
}
}catch(IOException e){
e.printStackTrace();
}finally{
try {
fis.close();
} catch (Exception e2) {
e2.printStackTrace();
}finally{
fis=null;
}
}
}
/**
* @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.okayboom.particlesim;
public interface Simulator {
SimResult simulate(SimSettings settings);
}
|
package models;
import java.util.List;
import javax.persistence.Entity;
import org.joda.time.DateTime;
import play.data.Form;
import play.db.ebean.Model;
import play.db.ebean.Model.Finder;
@Entity
public class T_vessel_schedule extends Model{
public String terminal_id;
public String vsl_cod;
public String vvd;
public String vvd_year;
public String opr;
public String in_vvd_opr;
public String out_vvd_opr;
public String berth_no;
public String cct;
public String etb;
public String etd;
public String atb;
public String atd;
public String load_cnt;
public String dis_cnt;
public String shift_cnt;
public String vvd_status;
public String vsl_name;
public String route;
public static Finder<Long, T_vessel_schedule> find = new Finder(String.class, T_vessel_schedule.class);
public static List<T_vessel_schedule> all(){
// DateTime dt = new DateTime();
// String today = "" + dt.now().getYear() + String.format("%02d", dt.now().getMonthOfYear()) + String.format("%02d", dt.now().getDayOfMonth());
// String fromTime = "" + String.format("%02d", dt.now().getHourOfDay() - 1) + String.format("%02d", dt.now().getMinuteOfHour()) + String.format("%02d", dt.now().getSecondOfMinute());
// String toTime = "" + String.format("%02d", dt.now().getHourOfDay()) + String.format("%02d", dt.now().getMinuteOfHour()) + String.format("%02d", dt.now().getSecondOfMinute());
// System.out.println("Today : " + today);
// return find.where().orderBy("terminal_id").findList();
return find.all();
}
public static List<T_vessel_schedule> terminal(String tml, String vcod, String vvd, String year, String opr,
String in_vvd_opr, String out_vvd_opr, String berth_no, String cct, String etb, String etd,
String atb, String atd, String vvd_status, String vsl_name, String route){
if(tml == null) tml = "%%%";
if(vcod == null) vcod = "%%%";
if(vvd == null) vvd = "%%%";
if(year == null) year = "%%%";
if(opr == null) opr = "%%%";
if(in_vvd_opr == null) in_vvd_opr = "%%%";
if(out_vvd_opr == null) out_vvd_opr = "%%%";
if(berth_no == null) berth_no = "%%%";
if(cct == null) cct = "%%%";
if(etb == null) etb = "%%%";
if(etd == null) etd = "%%%";
if(atb == null) atb = "%%%";
if(atd == null) atd = "%%%";
if(vvd_status == null) vvd_status = "%%%";
if(vsl_name == null) vsl_name = "%%%";
if(route == null) route = "%%%";
List<T_vessel_schedule> berthInfo = find.where().like("terminal_id", tml).like("vsl_cod", vcod).like("vvd", vvd)
.like("vvd_year", year).like("opr", opr).like("in_vvd_opr", in_vvd_opr)
.like("out_vvd_opr", out_vvd_opr).like("berth_no", berth_no).like("cct", cct)
.like("etb", etb).like("etd", etd).like("atb", atb)
.like("atd", atd).like("vvd_status", vvd_status).like("vsl_name", vsl_name).like("route", route)
.orderBy("terminal_id").findList();
// .findPagingList(25).setFetchAhead(false).getPage(1).getList();
return berthInfo;
}
public static List<T_vessel_schedule> terminal(Form<T_vessel_schedule> filledForm){
T_vessel_schedule cls = filledForm.get();
//http://hnctech73.iptime.org:9000/berthJson?vvd_status=&atd=&cct=&etb=&etd=&in_vvd_opr=&opr=&out_vvd_opr=&route=&terminal_id=&vsl_name=&vvd=&atb=
// System.out.println("====================================================");
// System.out.println("terminal_id:" + filledForm.field("terminal_id").value());
// System.out.println("opr:" + filledForm.field("opr").value());
// System.out.println("vvd:" + filledForm.field("vvd").value());
// System.out.println("in_vvd_opr:" + filledForm.field("in_vvd_opr").value());
// System.out.println("out_vvd_opr:" + filledForm.field("out_vvd_opr").value());
// System.out.println("vsl_name:" + filledForm.field("vsl_name").value());
// System.out.println("route:" + filledForm.field("route").value());
// System.out.println("vvd_status:" + filledForm.field("vvd_status").value());
// System.out.println("cct:" + filledForm.field("cct").value());
// System.out.println("etb:" + filledForm.field("etb").value());
// System.out.println("etd:" + filledForm.field("etd").value());
// System.out.println("atb:" + filledForm.field("atb").value());
// System.out.println("atd:" + filledForm.field("atd").value());
cls.terminal_id = filledForm.field("terminal_id").value();
cls.opr = filledForm.field("opr").value();
cls.vvd = filledForm.field("vvd").value();
cls.in_vvd_opr = filledForm.field("in_vvd_opr").value();
cls.out_vvd_opr = filledForm.field("out_vvd_opr").value();
cls.vsl_name = filledForm.field("vsl_name").value();
cls.route = filledForm.field("route").value();
cls.vvd_status = filledForm.field("vvd_status").value();
cls.cct = filledForm.field("cct").value();
cls.etb = filledForm.field("etb").value();
cls.etd = filledForm.field("etd").value();
cls.atb = filledForm.field("atb").value();
cls.atd = filledForm.field("atd").value();
cls = T_vessel_schedule.chkNullVar(cls);
// System.out.println("====================================================");
// System.out.println("terminal_id:" + cls.terminal_id);
// System.out.println("opr:" + cls.opr);
// System.out.println("vvd:" + cls.vvd);
// System.out.println("in_vvd_opr:" + cls.in_vvd_opr);
// System.out.println("out_vvd_opr:" + cls.out_vvd_opr);
// System.out.println("vsl_name:" + cls.vsl_name);
// System.out.println("route:" + cls.route);
// System.out.println("vvd_status:" + cls.vvd_status);
// System.out.println("cct:" + cls.cct);
// System.out.println("etb:" + cls.etb);
// System.out.println("etd:" + cls.etd);
// System.out.println("atb:" + cls.atb);
// System.out.println("atd:" + cls.atd);
List<T_vessel_schedule> berthInfo =
find.where().like("terminal_id", cls.terminal_id)
.like("opr", cls.opr).like("vvd", cls.vvd).like("in_vvd_opr", cls.in_vvd_opr)
.like("out_vvd_opr", cls.out_vvd_opr).like("vsl_name", cls.vsl_name)
.like("route", cls.route).like("vvd_status", cls.vvd_status).like("cct", cls.cct)
.like("etb", cls.etb).like("etd", cls.etd)
.like("atb", cls.atb).like("atd", cls.atd)
.findList();
return berthInfo;
}
public static T_vessel_schedule chkNullVar(T_vessel_schedule cls){
if(cls.terminal_id.equals(null) || cls.terminal_id.equals("")) cls.terminal_id = "%%%";
if(cls.opr.equals(null) || cls.opr.equals("")) cls.opr = "%%%";
if(cls.vvd.equals(null) || cls.vvd.equals("")) cls.vvd = "%%%";
if(cls.in_vvd_opr.equals(null) || cls.in_vvd_opr.equals("")) cls.in_vvd_opr = "%%%";
if(cls.out_vvd_opr.equals(null) || cls.out_vvd_opr.equals("")) cls.out_vvd_opr = "%%%";
if(cls.vsl_name.equals(null) || cls.vsl_name.equals("")) cls.vsl_name = "%%%";
if(cls.route.equals(null) || cls.route.equals("")) cls.route = "%%%";
if(cls.vvd_status.equals(null) || cls.vvd_status.equals("")) cls.vvd_status = "%%%";
if(cls.cct.equals(null) || cls.cct.equals("")) cls.cct = "%%%";
if(cls.etb.equals(null) || cls.etb.equals("")) cls.etb = "%%%";
if(cls.etd.equals(null) || cls.etd.equals("")) cls.etd = "%%%";
if(cls.atb.equals(null) || cls.atb.equals("")) cls.atb = "%%%";
if(cls.atd.equals(null) || cls.atd.equals("")) cls.atd = "%%%";
return cls;
}
}
|
/*
* Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
* Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
* Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
* Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
* Vestibulum commodo. Ut rhoncus gravida arcu.
*/
package cn.huangqiqiang.halbumexample;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import cn.huangqiqiang.halbum.activity.AlbumPreviewActivity;
import cn.huangqiqiang.halbum.common.FunctionConfig;
import cn.huangqiqiang.halbum.common.FunctionOptions;
import cn.huangqiqiang.halbum.common.PictureConfig;
import cn.huangqiqiang.halbum.entity.LocalMedia;
import cn.huangqiqiang.halbumexample.adapter.GridImageAdapter;
import cn.huangqiqiang.halbumexample.dialog.PhotoDialog;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, PictureConfig.OnSelectResultCallback {
private RecyclerView recyclerView;
ImageView mImageView;
private TextView tv_select_num;
GridImageAdapter mAdapter;
CheckBox mCbCamera;
CheckBox mCbIosStart;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_select_num = (TextView) findViewById(R.id.tv_select_num);
mCbCamera = (CheckBox) findViewById(R.id.cb_camera);
mCbIosStart = (CheckBox) findViewById(R.id.cb_IOS_start);
findViewById(R.id.ibtn_minus).setOnClickListener(this);
findViewById(R.id.ibtn_plus).setOnClickListener(this);
findViewById(R.id.btn_start_up_album).setOnClickListener(this);
findViewById(R.id.btn_start_up_camera).setOnClickListener(this);
recyclerView = (RecyclerView) findViewById(R.id.recycler);
GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
recyclerView.setLayoutManager(gridLayoutManager);
mAdapter = new GridImageAdapter();
recyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
@Override
public void onItemClick(int position, View v) {
}
});
mAdapter.setOnAddPicClickListener(new GridImageAdapter.onAddPicClickListener() {
@Override
public void onAddPicClick(int type, int position) {
if (type == 0) {
if (mCbIosStart.isChecked()) {
startDialog();
} else {
startPhoto();
}
} else if (type == 1) {
mAdapter.getList().remove(position);
mAdapter.notifyDataSetChanged();
} else if (type == 3) {
startActivity(new Intent(MainActivity.this, AlbumPreviewActivity.class)
.putExtra(FunctionConfig.FOLDER_DETAIL_POSITION, position)
.putExtra(FunctionConfig.FOLDER_NAME, "")
.putParcelableArrayListExtra(FunctionConfig.IMAGES, (ArrayList<? extends Parcelable>) mAdapter.getList())
);
}
}
});
}
private void startDialog() {
PhotoDialog photoDialog = new PhotoDialog(this, new PhotoDialog.PhotoCallback() {
@Override
public void getPhotoGallery() {
FunctionOptions.Builder builder = new FunctionOptions.Builder();
builder.setMaxSelectNum(maxSelectNum).setDisplayCamera(mCbCamera.isChecked());
PictureConfig.getInstance().openPhoto(MainActivity.this, builder, MainActivity.this);
}
@Override
public void getPhotoCamera() {
FunctionOptions.Builder builder = new FunctionOptions.Builder();
builder.setMaxSelectNum(maxSelectNum).setDisplayCamera(mCbCamera.isChecked()).setStartUpCamera(true);
PictureConfig.getInstance().openPhoto(MainActivity.this, builder, MainActivity.this);
}
@Override
public void getVideo() {
FunctionOptions.Builder builder = new FunctionOptions.Builder();
builder.setMaxSelectNum(maxSelectNum).setDisplayCamera(mCbCamera.isChecked()).setAlbumType(FunctionConfig.TYPE_VIDEO);
PictureConfig.getInstance().openPhoto(MainActivity.this, builder, MainActivity.this);
}
});
photoDialog.show();
}
private void startPhoto() {
FunctionOptions.Builder builder = new FunctionOptions.Builder();
builder.setMaxSelectNum(maxSelectNum).setDisplayCamera(mCbCamera.isChecked());
PictureConfig.getInstance().openPhoto(MainActivity.this, builder, this);
}
private int maxSelectNum = 9;// 图片最大可选数量
@Override
public void onClick(View v) {
FunctionOptions.Builder builder = new FunctionOptions.Builder();
switch (v.getId()) {
case R.id.ibtn_minus:
if (maxSelectNum > 1) {
maxSelectNum--;
}
tv_select_num.setText(maxSelectNum + "");
mAdapter.setSelectMax(maxSelectNum);
break;
case R.id.ibtn_plus:
maxSelectNum++;
tv_select_num.setText(maxSelectNum + "");
mAdapter.setSelectMax(maxSelectNum);
break;
case R.id.btn_start_up_camera:
builder.setMaxSelectNum(maxSelectNum).setDisplayCamera(mCbCamera.isChecked()).setStartUpCamera(true);
PictureConfig.getInstance().openPhoto(MainActivity.this, builder, this);
break;
case R.id.btn_start_up_album:
builder.setMaxSelectNum(maxSelectNum).setDisplayCamera(mCbCamera.isChecked());
PictureConfig.getInstance().openPhoto(MainActivity.this, builder, this);
break;
}
}
@Override
public void onSelectSuccess(List<LocalMedia> resultList) {
mAdapter.setList(resultList);
mAdapter.notifyDataSetChanged();
}
@Override
public void onSelectSuccess(LocalMedia media) {
}
}
|
package com.group35.terrificthermostat35;
/**
* Created by s163390 on 23-6-2017.
*/
public class ListItem {
String name = "name";
public void getList(){}
public void getNewWeekProgram(){}
public void getWeekProgram(String name){}
public void saveWeekProgram(){}
public String getName(){ return name;
}
}
|
import java.util.Scanner;
public class Converter {
public static void main(String[] args){
//Create the scanner
Scanner sc = new Scanner(System.in);
System.out.print("Please input a tempereture in degrees Farenheit: ");
int tempF = sc.nextInt();
//If you don't cast tempF to double, you get round off errors
double tempC = (5 * ((double)tempF - 32)) /9;
//Use format to bring the decimal
System.out.printf(tempF + " degrees Fahrenheit is %.1f degrees Celcius",tempC);
}
}
|
package io.wisoft.accounttutorial.controller;
import io.wisoft.accounttutorial.dto.ResetPasswordRequest;
import io.wisoft.accounttutorial.service.PasswordResetService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@RestController
@RequiredArgsConstructor
public class PasswordRestController {
private final PasswordResetService service;
@PostMapping("/api/resetpassword")
public void resetPassword(@Valid @RequestBody ResetPasswordRequest request) {
service.resetPassword(request.getEmail());
}
}
|
package org.vanilladb.comm.protocols.p2pcounting;
import org.vanilladb.comm.protocols.events.ProcessListInit;
import net.sf.appia.core.Layer;
import net.sf.appia.core.Session;
import net.sf.appia.core.events.SendableEvent;
public class P2pCountingLayer extends Layer {
public P2pCountingLayer() {
// Events that the protocol will create
evProvide = new Class[] {
};
// Events that the protocol requires to work
// This is a subset of the accepted events
evRequire = new Class[] {
ProcessListInit.class,
SendableEvent.class
};
// Events that the protocol will accept
evAccept = new Class[] {
ProcessListInit.class,
SendableEvent.class
};
}
@Override
public Session createSession() {
return new P2pCountingSession(this);
}
}
|
package edu.cb.wordpair.rhodes.maddux;
import edu.jenks.dist.cb.wordpair.*;
import java.util.*;
public class WordPairList extends AbstractWordPairList{
public static void main(String[] args) {
WordPairList test = new WordPairList(new String[] {"the", "red", "fox", "the", "red"});
test.printArr(test.allPairs);
System.out.println(test.numMatches());
}
public WordPairList(String[] arr) {
allPairs = new ArrayList<WordPair>();
for(int i = 0; i < arr.length; i++) {
for(int j = i+1; j < arr.length; j++) {
WordPair curr = new WordPair(arr[i], arr[j]);
allPairs.add(curr);
}
}
}
public int numMatches() {
int match = 0;
for(WordPair w : allPairs) {
if(w.getFirst().equals(w.getLast())) {
match++;
}
}
return match;
}
public void printArr(List<WordPair> arr) {
for(int i = 0; i < arr.size()-1; i++) {
System.out.print(arr.get(i).getFirst() + ":" + arr.get(i).getLast() + ", ");
}
System.out.print(arr.get(arr.size()-1).getFirst()+ ":" + arr.get(arr.size()-1).getLast());
System.out.println();
}
}
|
package in.stevemann.tictactoe.services;
import in.stevemann.tictactoe.entities.Player;
import in.stevemann.tictactoe.entities.QPlayer;
import in.stevemann.tictactoe.pojos.PlayerInputDto;
import in.stevemann.tictactoe.repositories.PlayerRepository;
import in.stevemann.tictactoe.utils.CopyNonNullUtil;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;
@Service
@AllArgsConstructor
public class PlayerService {
private final PlayerRepository playerRepository;
// Move to application properties or DB
private final String computerUsername = "computer";
public Player findPlayerByUsername(String username) {
return playerRepository.findOne(
QPlayer.player.enabled.isTrue()
.and(QPlayer.player.username.eq(username))
).orElse(null);
}
public Player getPlayerByUsername(String username) {
Player player = findPlayerByUsername(username);
if (player == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Player not found.");
return player;
}
public boolean playerExistsByUserName(String username) {
return playerRepository.exists(
QPlayer.player.enabled.isTrue()
.and(QPlayer.player.username.eq(username))
);
}
public Player newPlayer(String name, String username) {
if (playerExistsByUserName(username))
throw new ResponseStatusException(HttpStatus.CONFLICT, "Username already exists.");
Player player = new Player();
player.setName(name);
player.setUsername(username);
player.setAutomated(false);
return playerRepository.save(player);
}
public Player deletePlayer(String username) {
Player player = getPlayerByUsername(username);
player.setEnabled(false);
return playerRepository.save(player);
}
public Player updatePlayer(PlayerInputDto playerInputDto) {
Player player = getPlayerByUsername(playerInputDto.getUsername());
CopyNonNullUtil.copyNonNullProperties(playerInputDto, player);
return playerRepository.save(player);
}
public Player getAutomatedPlayer() {
Player automatedPlayer = findPlayerByUsername(computerUsername);
if (automatedPlayer == null) {
Player player = new Player();
player.setName("Computer");
player.setUsername(computerUsername);
player.setAutomated(true);
return playerRepository.save(player);
}
return automatedPlayer;
}
}
|
package swe.acco.assignment1.test.interfaces;
public interface Connector {
void add(int a, int b);
void mul(int a,int b);
void sub(int a,int b);
void div(int a,int b);
}
|
/**
* #dynamic-programming #lcs lcs s and reverse of s.
*
* <p>abccbaazo
*
* <p>tfft tff
*
* <p>abca acba
*
* <p>ozaabccbaazo ozaabccba
*/
import java.util.Scanner;
class Aibohphobia {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
char[] arr1 = s.toCharArray();
int n = arr1.length;
char[] arr2 = new char[n];
for (int i = 0; i < n; i++) {
arr2[n - 1 - i] = arr1[i];
}
int lcs = getLcs(arr1, arr2, n);
System.out.println(n - lcs);
}
public static int getLcs(char[] arr1, char[] arr2, int sz) {
int[][] L = new int[sz + 1][sz + 1];
for (int i = 0; i <= sz; i++) {
for (int j = 0; j <= sz; j++) {
if (i == 0 || j == 0) {
L[i][j] = 0;
} else if (arr1[i - 1] == arr2[j - 1]) {
L[i][j] = L[i - 1][j - 1] + 1;
} else {
L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]);
}
}
}
return L[sz][sz];
}
}
|
package com.company;
public class ContaSalario extends Conta{
private String empregador;
public ContaSalario(int numeroDaConta, int agencia, String banco, double saldo, String empregador) {
super(numeroDaConta, agencia, banco, saldo);
this.empregador = empregador;
}
@Override
public double getSaldo() {
return this.saldo;
}
@Override
public String toString() {
return "ContaSalario{" +
"saldo=" + saldo +
", saque=" + saque +
", deposito=" + deposito +
'}';
}
@Override
public double getSaque() throws Exception {
if(this.saque != this.saldo){
System.out.println("O saque só deve ser feito de maneira inteira");
throw new Exception("SAQUE FEITO FORA DO PADRÃO");
}
return getSaldo() - this.saque;
}
// utilizei de uma regra real de conta salário, supondo que quem consulta não é o empregador
@Override
public double getDeposito() throws Exception{
throw new Exception("SEM AUTORIZAÇÃO PARA FAZER DEPOSITOS");
}
}
|
package com.cjf.web.service;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import com.cjf.entity.Category;
import com.cjf.entity.Order;
import com.cjf.entity.Product;
import com.cjf.service.ProductService;
import com.cjf.service.Impl.ProductServiceImpl;
import com.google.gson.Gson;
public class AdminServlet extends BaseServlet {
private static final long serialVersionUID = 1L;
public void delProduct (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
//获取要删除的pid
String pid = request.getParameter("pid");
//传递pid到service层
ProductService productService=new ProductServiceImpl();
productService.delProductByPid(pid);
response.sendRedirect(request.getContextPath()+"/admin?method=queryAllProduct");
}
//queryAllProduct
public void queryAllProduct(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
//传递请求到service层
ProductService productService=new ProductServiceImpl();
List<Product> productList = null;
try {
productList = productService.findAllProduct();
} catch (SQLException e) {
e.printStackTrace();
}
//将productList放到request域
request.setAttribute("productList", productList);
request.getRequestDispatcher("/admin/product/list.jsp").forward(request, response);
}
//findOrderInfoByOid
public void findOrderInfoByOid(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String oid = request.getParameter("oid");
ProductService productService=new ProductServiceImpl();
List<Map<String,Object>> orderItems= productService.findAllOrderItemByOid(oid);
Gson gson =new Gson();
String json = gson.toJson(orderItems);
//设置 编码
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(json);
}
public void queryAllOrders(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
ProductService productService=new ProductServiceImpl();
List<Order> orderList = productService.findAllOrder();
request.setAttribute("orderList", orderList);
request.getRequestDispatcher("/admin/order/list.jsp").forward(request, response);
}
//异步加载所有分类
public void findAllCategory(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
ProductService productService=new ProductServiceImpl();
List<Category> categoryList = productService.findCategoryList();
Gson gson=new Gson();
String json = gson.toJson(categoryList);
response.setContentType("text/html;charset=UTF-8");
response.getWriter().write(json);
}
}
|
/*
* Copyright (c) 2018. Krzysztof Nowak "knowaknet"
*/
package com.bignerdranch.android.geoquiz;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.widget.Button;
import android.widget.TextView;
public class CheatActivity extends AppCompatActivity {
private static final String EXTRA_ANSWER_IS_TRUE = "com.bignerdranch.android.geoquiz.answer_is_true";
private static final String EXTRA_ANSWER_HAS_BEEN_SHOWN = "com.bignerdranch.android.geoquiz.answer_shown";
private static final String STATE_KEY_ANSWER_HAS_BEEN_SHOWN = "shown";
private boolean mAnswerIsTrue;
private Button mShowAnswer;
private TextView mAnswer;
private boolean mAnswerHasBeenShown = false;
public static Intent newIntent(Context packageContext, boolean answerIsTrue){
Intent cheatIntent = new Intent(packageContext, CheatActivity.class);
cheatIntent.putExtra(EXTRA_ANSWER_IS_TRUE, answerIsTrue);
return cheatIntent;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
loadState(savedInstanceState);
setupWidgets();
setupWidgetEvents();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(STATE_KEY_ANSWER_HAS_BEEN_SHOWN, mAnswerHasBeenShown);
}
private void loadState(Bundle savedInstanceState) {
if(savedInstanceState == null)
return;
mAnswerHasBeenShown = savedInstanceState.getBoolean(STATE_KEY_ANSWER_HAS_BEEN_SHOWN, false);
setAnswerShownResult(mAnswerHasBeenShown);
}
private void setupWidgets() {
mShowAnswer = findViewById(R.id.btn_show_answer);
mAnswer = findViewById(R.id.answer_view_text);
}
private void setupWidgetEvents(){
mShowAnswer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAnswer.setText( mAnswerIsTrue ? R.string.btn_label_true : R.string.btn_label_false );
setAnswerShownResult(true);
// animation test; require API 21
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
int cx = mShowAnswer.getWidth() / 2;
int cy = mShowAnswer.getHeight() / 2;
float radius = mShowAnswer.getWidth();
Animator anim = ViewAnimationUtils.createCircularReveal(mShowAnswer, cx, cy, radius, 0);
anim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
mShowAnswer.setVisibility(View.INVISIBLE);
}
});
anim.start();
} else {
mShowAnswer.setVisibility(View.INVISIBLE);
}
}
});
}
private void setAnswerShownResult(boolean whetherUserShownAnswer) {
if(whetherUserShownAnswer) {
mAnswerHasBeenShown = true;
Intent intent = new Intent();
//noinspection ConstantConditions
intent.putExtra(EXTRA_ANSWER_HAS_BEEN_SHOWN, whetherUserShownAnswer);
setResult(RESULT_OK, intent);
}
}
public static boolean wasAnswerShown(Intent result){
return result.getBooleanExtra(EXTRA_ANSWER_HAS_BEEN_SHOWN, false);
}
}
|
package com.egswebapp.egsweb.interceptor;
import com.egswebapp.egsweb.dto.response.ErrorResponse;
import com.egswebapp.egsweb.excpetions.ServiceException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ExceptionAdvice {
@ExceptionHandler(ServiceException.class)
public ResponseEntity<Object> handleFields(ServiceException ex) {
if (ex.getErrorResponses()!=null) {
return new ResponseEntity<>(ex.getErrorResponses(), ex.getStatus());
} else {
ErrorResponse response = new ErrorResponse();
response.setMessage(ex.getMessage());
response.setFields(ex.getStatus().name());
return new ResponseEntity<>(response, ex.getStatus());
}
}
}
|
package br.sc.senai.lovely.mb;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import br.sc.senai.lovely.dominio.Funcionario;
import br.sc.senai.lovely.model.FuncionarioRn;
@ManagedBean
public class FuncionarioMb {
private List<Funcionario> funcionarios;
private Funcionario funcionario;
private FuncionarioRn rn;
@PostConstruct
public void init(){
rn = new FuncionarioRn();
funcionario = new Funcionario();
}
public List<Funcionario> getFuncionarios() throws Exception {
if(funcionarios == null){
funcionarios = rn.listar();
}
return funcionarios;
}
public void setFuncionarios(List<Funcionario> funcionarios) {
this.funcionarios = funcionarios;
}
public Funcionario getFuncionario() {
return funcionario;
}
public void setFuncionario(Funcionario funcionario) {
this.funcionario = funcionario;
}
public FuncionarioRn getRn() {
return rn;
}
public void setRn(FuncionarioRn rn) {
this.rn = rn;
}
public String salvar(){
try {
rn.salvar(funcionario);
} catch (Exception e) {
e.printStackTrace();
return "";
}
return "listarFuncionario";
}
public String excluir(String idParam){
Long idFuncionario = Long.parseLong(idParam);
try {
rn.excluir(idFuncionario);
funcionarios = null;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public String editar(String idParam) throws Exception{
Long id = Long.parseLong(idParam);
funcionario = rn.buscarPorId(id);
return "cadastroFuncionario";
}
}
|
package com.hcl.neo.eloader.microservices.exceptions;
import com.hcl.neo.eloader.microservices.model.ErrorResponse;
public class ServiceException extends Exception {
private static final long serialVersionUID = 1L;
private String code;
private String message;
public ServiceException(String message) {
super(message);
this.message = message;
this.code = "500";
}
public ServiceException(Throwable e) {
super(e);
this.message = e.getMessage();
this.code = "500";
}
public ServiceException(String message, Throwable e) {
super(message, e);
this.message = message;
this.code = "500";
}
public String getErrorCode() {
return this.code;
}
public void setErrorCode(String errorCode) {
this.code = errorCode;
}
public String getErrorMessage() {
return null == this.message ? "Internal server exception occured." : this.message;
}
public void setErrorMessage(String errorMessage) {
this.message = errorMessage;
}
@Override
public String toString() {
return "ServiceException [errorCode=" + code + ", errorMessage="
+ message + "]";
}
public String toJsonString() {
ErrorResponse response = new ErrorResponse();
response.setErrorCode(getErrorCode());
response.setErrorMessage(getErrorMessage());
return response.toJsonString();
}
}
|
/****************************************************************************
* Created by: Younes Elfeitori
* Created on: 26 Oct 2018
* This is a program about stack class that can import to other class
****************************************************************************/
import java.util.ArrayList;
public class MrCoxallStack {
ArrayList<Integer> list = new ArrayList<Integer> ();
public void push(int userInput) {
list.add(userInput);
}
public void pop(int userInput) {
list.remove(list.size()-1);
}
public void print() {
System.out.print(list);
}
public void count() {
System.out.println("The length of the arrayList is " + list.size());
}
}
|
package Enum;
public class Enum {
public static final int SEGUNDA = 1;
public static final int TERCA = 2;
public static final int QUARTA= 3;
public static final int QUINTA = 4;
public static final int SEXTA= 5;
public static final int SABADO= 6;
public static final int DOMINGO= 7;
}
|
package ejercicio39;
/**
* @author Javier
*/
public class jefe extends empleado {
String departamento;
public jefe(String dni, String nombre, double sueldo, String departamento) {
super(dni, nombre, sueldo);
this.departamento = departamento;
}
public jefe() {
}
public void mostrar() {
super.mostrar();
System.out.println("Departamento que dirige: " + getDepartamento());
}
public String getDepartamento() {
return departamento;
}
public void setDepartamento(String departamento) {
this.departamento = departamento;
}
}
|
package com.kingnode.gou.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* 商品图片
*/
@Entity @Table(name="product_picture") public class ProductPicture extends BaseEntity{
private static final long serialVersionUID=7729773785078498063L;
private Long productId;//商品id
private String productType;//商品类型 1.表示商品,2.表示商品详情
private String pictureLocation;//图片位置
private Integer pictureSort;//图片排序
private String pictureName;//图片名称
private String pictureType;//图片类型
private String pictureUrl;//图片URL
private Long pictureSize;//图片大小
public Long getProductId(){
return productId;
}
public String getProductType(){
return productType;
}
public void setProductType(String productType){
this.productType=productType;
}
public void setProductId(Long productId){
this.productId=productId;
}
public String getPictureLocation(){
return pictureLocation;
}
public void setPictureLocation(String pictureLocation){
this.pictureLocation=pictureLocation;
}
public Integer getPictureSort(){
return pictureSort;
}
public void setPictureSort(Integer pictureSort){
this.pictureSort=pictureSort;
}
public String getPictureName(){
return pictureName;
}
public void setPictureName(String pictureName){
this.pictureName=pictureName;
}
public String getPictureType(){
return pictureType;
}
public void setPictureType(String pictureType){
this.pictureType=pictureType;
}
@Column(length=1000) public String getPictureUrl(){
return pictureUrl;
}
public void setPictureUrl(String pictureUrl){
this.pictureUrl=pictureUrl;
}
public Long getPictureSize(){
return pictureSize;
}
public void setPictureSize(Long pictureSize){
this.pictureSize=pictureSize;
}
}
|
package com.algo;
import java.util.Arrays;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
public class MinHeap {
public static void main(String[] args) {
MinHeap heap = new MinHeap();
heap.add(12);
heap.add(4);
heap.add(5);
heap.add(3);
heap.add(8);
heap.add(7);
System.out.println(heap);
}
private int size = 0;
private int capacity = 10;
private int[] items = new int[capacity];
public int peek() {
throwWhenEmpty();
return items[0];
}
public int poll() {
throwWhenEmpty();
int item = items[0];
items[0] = items[size - 1];
size--;
heapifyDown();
return item;
}
public void add(int item) {
ensureExtraCapacity();
items[size] = item;
size++;
heapifyUp();
}
private void heapifyUp() {
int index = size - 1;
while (hasParent(index) && parent(index) > items[index]) {
swap(getParentIndex(index), index);
index = getParentIndex(index);
}
}
private void heapifyDown() {
int index = 0;
while (hasLeftChild(index)) {
int smallerChildIndex = getLeftChildIndex(index);
if (hasRightChild(index) && rightChild(index) < leftChild(index)) {
smallerChildIndex = getRightChildIndex(index);
}
if (items[index] < smallerChildIndex) {
break;
} else {
swap(index, smallerChildIndex);
}
index = smallerChildIndex;
}
}
private void throwWhenEmpty() {
if (size == 0) throw new IllegalStateException();
}
private int getLeftChildIndex(int parentIndex) {
return 2 * parentIndex + 1;
}
private int getRightChildIndex(int parentIndex) {
return 2 * parentIndex + 2;
}
private int getParentIndex(int childIndex) {
return (childIndex - 1) / 2;
}
private boolean hasLeftChild(int index) {
return getLeftChildIndex(index) < size;
}
private boolean hasRightChild(int index) {
return getRightChildIndex(index) < size;
}
private boolean hasParent(int index) {
return getParentIndex(index) >= 0;
}
private int leftChild(int index) {
return items[getLeftChildIndex(index)];
}
private int rightChild(int index) {
return items[getRightChildIndex(index)];
}
private int parent(int index) {
return items[getParentIndex(index)];
}
private void swap(int indexOne, int indexTwo) {
int temp = items[indexOne];
items[indexOne] = items[indexTwo];
items[indexTwo] = temp;
}
private void ensureExtraCapacity() {
if (size == capacity) {
items = Arrays.copyOf(items, capacity * 2);
capacity *= 2;
}
}
}
/*
You need two heaps: one min-heap and one max-heap.
Each heap contains about one half of the data.
Every element in the min-heap is greater or equal to the median,
and every element in the max-heap is less or equal to the median.
When the min-heap contains one more element than the max-heap,
the median is in the top of the min-heap.
And when the max-heap contains one more element than the min-heap,
the median is in the top of the max-heap.
When both heaps contain the same number of elements,
the total number of elements is even.
In this case you have to choose according your definition of median:
a) the mean of the two middle elements;
b) the greater of the two;
c) the lesser;
d) choose at random any of the two...
Every time you insert,
compare the new element with those at the top of the heaps in order to decide where to insert it.
If the new element is greater than the current median,
it goes to the min-heap.
If it is less than the current median, it goes to the max heap.
Then you might need to rebalance.
If the sizes of the heaps differ by more than one element,
extract the min/max from the heap with more elements and insert it into the other heap.
In order to construct the median heap for a list of elements, we should first use a linear time algorithm and find the median.
Once the median is known, we can simply add elements to the Min-heap and Max-heap based on the median value.
Balancing the heaps isn't required because the median will split the input list of elements into equal halves.
If you extract an element you might need to compensate the size change
by moving one element from one heap to another.
This way you ensure that, at all times, both heaps have the same size or differ by just one element.
*/
class Heap {
private Queue<Integer> low = new PriorityQueue<>(Comparator.reverseOrder());
private Queue<Integer> high = new PriorityQueue<>();
public void add(int number) {
double median = median();
if(number < median) {
high.add(number);
} else {
low.add(number);
}
if (low.size() - high.size() > 1) {
high.add(low.poll());
}
if (high.size() - low.size() > 1) {
low.add(high.poll());
}
}
public double median() {
if(low.isEmpty() && high.isEmpty()) {
return 0;
} else {
if(low.size() == high.size()) {
return (low.peek() + high.peek()) / 2.0;
} else if (low.size() > high.size()) {
return low.peek();
} else {
return high.peek();
}
}
}
}
|
package org.rs.core.session.jdbc;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.rs.core.beans.RsSession;
import org.rs.core.beans.RsSessionAttribute;
import org.rs.core.beans.model.RsSessionModel;
import org.rs.core.service.RsSessionService;
import org.rs.core.session.RsIndexResolver;
import org.rs.core.session.RsMapSession;
import org.rs.core.session.RsSessionRepository;
import org.rs.core.utils.CoreUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.session.FlushMode;
import org.springframework.session.IndexResolver;
import org.springframework.session.SaveMode;
import org.springframework.session.Session;
import org.springframework.transaction.support.TransactionOperations;
import org.springframework.util.Assert;
public class RsIndexedSessionRepository
implements RsSessionRepository<RsIndexedSessionRepository.JdbcSession> {
private static final Logger logger = LoggerFactory.getLogger(RsIndexedSessionRepository.class);
private static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT";
/**
* If non-null, this value is used to override the default value for
* {@link JdbcSession#setMaxInactiveInterval(Duration)}.
*/
private Integer defaultMaxInactiveInterval;
private IndexResolver<Session> indexResolver = new RsIndexResolver<>();
private ConversionService conversionService = createDefaultConversionService();
private FlushMode flushMode = FlushMode.ON_SAVE;
private SaveMode saveMode = SaveMode.ON_SET_ATTRIBUTE;
private final RsSessionService sessionService;
/**
* Create a new {@link JdbcIndexedSessionRepository} instance which uses the provided
* {@link JdbcOperations} and {@link TransactionOperations} to manage sessions.
* @param jdbcOperations the {@link JdbcOperations} to use
* @param transactionOperations the {@link TransactionOperations} to use
*/
public RsIndexedSessionRepository(RsSessionService sessionService) {
this.sessionService = sessionService;
}
/**
* Set the maximum inactive interval in seconds between requests before newly created
* sessions will be invalidated. A negative time indicates that the session will never
* timeout. The default is 1800 (30 minutes).
* @param defaultMaxInactiveInterval the maximum inactive interval in seconds
*/
public void setDefaultMaxInactiveInterval(Integer defaultMaxInactiveInterval) {
this.defaultMaxInactiveInterval = defaultMaxInactiveInterval;
}
/**
* Set the {@link IndexResolver} to use.
* @param indexResolver the index resolver
*/
public void setIndexResolver(IndexResolver<Session> indexResolver) {
Assert.notNull(indexResolver, "indexResolver cannot be null");
this.indexResolver = indexResolver;
}
/**
* Sets the {@link ConversionService} to use.
* @param conversionService the converter to set
*/
public void setConversionService(ConversionService conversionService) {
Assert.notNull(conversionService, "conversionService must not be null");
this.conversionService = conversionService;
}
/**
* Set the flush mode. Default is {@link FlushMode#ON_SAVE}.
* @param flushMode the flush mode
*/
public void setFlushMode(FlushMode flushMode) {
Assert.notNull(flushMode, "flushMode must not be null");
this.flushMode = flushMode;
}
/**
* Set the save mode.
* @param saveMode the save mode
*/
public void setSaveMode(SaveMode saveMode) {
Assert.notNull(saveMode, "saveMode must not be null");
this.saveMode = saveMode;
}
private RsMapSession createRsMapSession( RsSessionModel model ) {
RsMapSession delegate = new RsMapSession(model.getSession_id());
delegate.setCreationTime(Instant.ofEpochMilli(model.getCreation_time()));
delegate.setLastAccessedTime(Instant.ofEpochMilli(model.getLast_access_time()));
delegate.setMaxInactiveInterval(Duration.ofSeconds(model.getMax_inactive_interval()));
List<RsSessionAttribute> attributes = model.getSessionAttrs();
for( RsSessionAttribute attribute : attributes ) {
delegate.setAttribute(attribute.getAttribute_name(), lazily(() -> deserialize(attribute.getAttribute_bytes())));
}
return delegate;
}
private RsSession createRsSession( JdbcSession session ) {
Map<String, String> indexes = indexResolver.resolveIndexesFor(session);
RsSession bean = new RsSession();
bean.setPrimary_id(session.primaryKey);
bean.setSession_id(session.getId());
bean.setCreation_time(session.getCreationTime().toEpochMilli());
bean.setLast_access_time(session.getLastAccessedTime().toEpochMilli());
bean.setMax_inactive_interval((int) session.getMaxInactiveInterval().getSeconds());
bean.setExpiry_time(session.getExpiryTime().toEpochMilli());
bean.setIp_addr(session.getIp());
bean.setPrincipal_name(indexes.get("yhbh"));
return bean;
}
@Override
public JdbcSession createSession() {
RsMapSession delegate = new RsMapSession();
if (this.defaultMaxInactiveInterval != null) {
delegate.setMaxInactiveInterval(Duration.ofSeconds(this.defaultMaxInactiveInterval));
}
HttpServletRequest request = CoreUtils.getHttpServletRequest();
String ip = CoreUtils.getIpAddr(request);
String primaryId = UUID.randomUUID().toString().replaceAll("-", "");
JdbcSession session = new JdbcSession(delegate, primaryId ,ip, true );
session.flushIfRequired();
logger.debug("Create session: {}", session.getId());
return session;
}
@Override
public void save(final JdbcSession session) {
logger.debug("Save session: {}", session.getId());
//logger.debug("Save session:", new RuntimeException("For debugging purposes only (not an error)"));
session.save();
}
@Override
public JdbcSession findById(final String id) {
//logger.debug("find session:", new RuntimeException("For debugging purposes only (not an error)"));
RsSessionModel result = sessionService.findBySessionId(id);
if( result == null )
return null;
RsMapSession delegate = createRsMapSession(result);
final JdbcSession session = new JdbcSession(delegate, result.getPrimary_id(),result.getIp_addr(), false );
if (session != null) {
if (session.isExpired()) {
deleteById(id);
}
else {
return session;
}
}
return session;
}
@Override
public void deleteById(final String id) {
sessionService.deleteBySessionId(id);
}
@Override
public Map<String, JdbcSession> findByIndexNameAndIndexValue(String indexName, final String indexValue) {
if (!PRINCIPAL_NAME_INDEX_NAME.equals(indexName)) {
return Collections.emptyMap();
}
List<RsSessionModel> sessions = sessionService.findByPrincipalName(indexValue);
Map<String, JdbcSession> sessionMap = new HashMap<>(sessions.size());
for (RsSessionModel result : sessions) {
RsMapSession delegate = createRsMapSession(result);
JdbcSession session = new JdbcSession(delegate, result.getPrimary_id(),result.getIp_addr(), false );
sessionMap.put(session.getId(), session);
}
return sessionMap;
}
private void insertSession(JdbcSession session) {
RsSession bean = createRsSession(session);
Set<String> attributeNames = session.getAttributeNames();
List<RsSessionAttribute> attributes = consctructSessionAttributes(session,new ArrayList<>(attributeNames),true);
sessionService.insertSessionAndAttributes(bean,attributes);
}
private void updateSession(JdbcSession session) {
RsSession bean = createRsSession(session);
List<String> addedAttributeNames = session.delta.entrySet().stream()
.filter((entry) -> entry.getValue() == RsDeltaValue.ADDED).map(Map.Entry::getKey)
.collect(Collectors.toList());
List<RsSessionAttribute> insertAttributes = consctructSessionAttributes(session,addedAttributeNames,true);
List<String> updatedAttributeNames = session.delta.entrySet().stream()
.filter((entry) -> entry.getValue() == RsDeltaValue.UPDATED).map(Map.Entry::getKey)
.collect(Collectors.toList());
List<RsSessionAttribute> updateAttributes = consctructSessionAttributes(session,updatedAttributeNames,true);
List<String> removedAttributeNames = session.delta.entrySet().stream()
.filter((entry) -> entry.getValue() == RsDeltaValue.REMOVED).map(Map.Entry::getKey)
.collect(Collectors.toList());
List<RsSessionAttribute> deleteAttributes = consctructSessionAttributes(session,removedAttributeNames,false);
sessionService.updateSessionAndAttributes(bean,insertAttributes,updateAttributes,deleteAttributes);
}
private List<RsSessionAttribute> consctructSessionAttributes(JdbcSession session, List<String> attributeNames, boolean isUpdate) {
//Assert.notEmpty(attributeNames, "attributeNames must not be null or empty");
List<RsSessionAttribute> attributes = new ArrayList<>();
for( String attributeName : attributeNames ) {
RsSessionAttribute bean = new RsSessionAttribute();
bean.setSession_primary_id(session.primaryKey);
bean.setAttribute_name(attributeName);
if( isUpdate )
bean.setAttribute_bytes(serialize(session.getAttribute(attributeName)));
attributes.add(bean);
}
return attributes;
}
public void cleanUpExpiredSessions() {
int deletedCount = sessionService.deleteSessionByExpiryTime(System.currentTimeMillis());
if (logger.isDebugEnabled()) {
logger.debug("Cleaned up " + deletedCount + " expired sessions");
}
}
private static GenericConversionService createDefaultConversionService() {
GenericConversionService converter = new GenericConversionService();
converter.addConverter(Object.class, byte[].class, new SerializingConverter());
converter.addConverter(byte[].class, Object.class, new DeserializingConverter());
return converter;
}
private byte[] serialize(Object object) {
return (byte[]) this.conversionService.convert(object, TypeDescriptor.valueOf(Object.class),
TypeDescriptor.valueOf(byte[].class));
}
private Object deserialize(byte[] bytes) {
return this.conversionService.convert(bytes, TypeDescriptor.valueOf(byte[].class),
TypeDescriptor.valueOf(Object.class));
}
private static <T> Supplier<T> value(T value) {
return (value != null) ? () -> value : null;
}
private static <T> Supplier<T> lazily(Supplier<T> supplier) {
Supplier<T> lazySupplier = new Supplier<T>() {
private T value;
@Override
public T get() {
if (this.value == null) {
this.value = supplier.get();
}
return this.value;
}
};
return (supplier != null) ? lazySupplier : null;
}
/**
* The {@link Session} to use for {@link RsIndexedSessionRepository}.
*
* @author Vedran Pavic
*/
final class JdbcSession implements Session {
private final Session delegate;
private final String primaryKey;
private boolean isNew;
private boolean changed;
private final String ip;
private Map<String, RsDeltaValue> delta = new HashMap<>();
JdbcSession(RsMapSession delegate, String primaryKey, String ip, boolean isNew ) {
this.delegate = delegate;
this.primaryKey = primaryKey;
this.isNew = isNew;
this.ip = ip;
if (this.isNew || (RsIndexedSessionRepository.this.saveMode == SaveMode.ALWAYS)) {
getAttributeNames().forEach((attributeName) -> this.delta.put(attributeName, RsDeltaValue.UPDATED));
}
}
String getIp() {
return ip;
}
boolean isNew() {
return this.isNew;
}
boolean isChanged() {
return this.changed;
}
Map<String, RsDeltaValue> getDelta() {
return this.delta;
}
void clearChangeFlags() {
this.isNew = false;
this.changed = false;
this.delta.clear();
}
Instant getExpiryTime() {
return getLastAccessedTime().plus(getMaxInactiveInterval());
}
@Override
public String getId() {
return this.delegate.getId();
}
public void setChanged() {
this.changed = true;
}
@Override
public String changeSessionId() {
this.changed = true;
return this.delegate.changeSessionId();
}
@Override
public <T> T getAttribute(String attributeName) {
Supplier<T> supplier = this.delegate.getAttribute(attributeName);
if (supplier == null) {
return null;
}
T attributeValue = supplier.get();
if (attributeValue != null
&& RsIndexedSessionRepository.this.saveMode.equals(SaveMode.ON_GET_ATTRIBUTE)) {
this.delta.put(attributeName, RsDeltaValue.UPDATED);
}
return attributeValue;
}
@Override
public Set<String> getAttributeNames() {
return this.delegate.getAttributeNames();
}
@Override
public void setAttribute(String attributeName, Object attributeValue) {
boolean attributeExists = (this.delegate.getAttribute(attributeName) != null);
boolean attributeRemoved = (attributeValue == null);
if (!attributeExists && attributeRemoved) {
return;
}
if (attributeExists) {
if (attributeRemoved) {
this.delta.merge(attributeName, RsDeltaValue.REMOVED,
(oldDeltaValue, deltaValue) -> (oldDeltaValue == RsDeltaValue.ADDED) ? null : deltaValue);
}
else {
this.delta.merge(attributeName, RsDeltaValue.UPDATED, (oldDeltaValue,
deltaValue) -> (oldDeltaValue == RsDeltaValue.ADDED) ? oldDeltaValue : deltaValue);
}
}
else {
this.delta.merge(attributeName, RsDeltaValue.ADDED, (oldDeltaValue,
deltaValue) -> (oldDeltaValue == RsDeltaValue.ADDED) ? oldDeltaValue : RsDeltaValue.UPDATED);
}
this.delegate.setAttribute(attributeName, value(attributeValue));
if (PRINCIPAL_NAME_INDEX_NAME.equals(attributeName) || SPRING_SECURITY_CONTEXT.equals(attributeName)) {
this.changed = true;
}
flushIfRequired();
}
@Override
public void removeAttribute(String attributeName) {
setAttribute(attributeName, null);
}
@Override
public Instant getCreationTime() {
return this.delegate.getCreationTime();
}
@Override
public void setLastAccessedTime(Instant lastAccessedTime) {
this.delegate.setLastAccessedTime(lastAccessedTime);
this.changed = true;
flushIfRequired();
}
@Override
public Instant getLastAccessedTime() {
return this.delegate.getLastAccessedTime();
}
@Override
public void setMaxInactiveInterval(Duration interval) {
this.delegate.setMaxInactiveInterval(interval);
this.changed = true;
flushIfRequired();
}
@Override
public Duration getMaxInactiveInterval() {
return this.delegate.getMaxInactiveInterval();
}
@Override
public boolean isExpired() {
return this.delegate.isExpired();
}
private void flushIfRequired() {
if (RsIndexedSessionRepository.this.flushMode == FlushMode.IMMEDIATE) {
save();
}
}
private void save() {
if (this.isNew) {
RsIndexedSessionRepository.this.insertSession(JdbcSession.this);
}
else {
RsIndexedSessionRepository.this.updateSession(JdbcSession.this);
}
clearChangeFlags();
}
}
}
|
package com.weili.dao;
//package com.weili.dao;
//
//import java.sql.Connection;
//import java.sql.SQLException;
//import java.util.List;
//import java.util.Map;
//
//import com.weili.database.Dao;
//import com.weili.database.Dao.Tables;
//import com.shove.data.DataException;
//import com.shove.data.DataSet;
//import com.shove.util.BeanMapUtils;
//
//public class DemoDao {
//
// public long addDemo(Connection conn) throws SQLException{
// Dao.Tables.t_demo demo = new Dao().new Tables().new t_demo();
//
// return demo.insert(conn);
// }
//
// public long updateDemo(Connection conn,long id) throws SQLException{
// Dao.Tables.t_demo demo = new Dao().new Tables().new t_demo();
//
// return demo.update(conn, " id = "+id);
// }
//
// public long deleteDemo(Connection conn,String ids) throws SQLException{
// Dao.Tables.t_demo demo = new Dao().new Tables().new t_demo();
//
// return demo.delete(conn, " id in("+ids+") ");
// }
//
// public Map<String,String> queryDemoById(Connection conn,long id) throws SQLException, DataException{
// Dao.Tables.t_demo demo = new Dao().new Tables().new t_demo();
//
// DataSet ds = demo.open(conn, " ", " id = "+id, "", -1, -1);
// return BeanMapUtils.dataSetToMap(ds);
// }
//
// public List<Map<String, Object>> queryDemoAll(Connection conn,String fieldList,String condition,String order)throws SQLException, DataException {
// Dao.Tables.t_demo demo = new Dao().new Tables().new t_demo();
// DataSet ds = demo.open(conn, fieldList, condition,order, -1, -1);
// ds.tables.get(0).rows.genRowsMap();
// return ds.tables.get(0).rows.rowsMap;
// }
//}
|
package com.BDD.blue_whale.repositories;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.web.bind.annotation.CrossOrigin;
import com.BDD.blue_whale.entities.ERole;
import com.BDD.blue_whale.entities.Role;
@RepositoryRestResource
@CrossOrigin("*")
public interface RoleRepository extends JpaRepository<Role, Long>{
//Role findByRole(String roleName);
Optional<Role> findByName(ERole name);
}
|
package com.soldevelo.vmi.it;
import com.soldevelo.vmi.enumerations.DiagnosticState;
import com.soldevelo.vmi.it.execution.TesterConfig;
import com.soldevelo.vmi.it.helper.ITHelper;
import com.soldevelo.vmi.logging.entities.Increment;
import com.soldevelo.vmi.logging.headers.HttpLogHeaders;
import com.soldevelo.vmi.logging.utils.IncrementManager;
import com.soldevelo.vmi.packets.TestResult;
import com.soldevelo.vmi.packets.TestResultDns;
import com.soldevelo.vmi.testclient.client.ExecutionResult;
import com.soldevelo.vmi.testclient.conf.ClientConfig;
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.supercsv.io.CsvMapReader;
import org.supercsv.prefs.CsvPreference;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
@ContextConfiguration(locations = { "/test-context.xml"})
@TesterConfig(locations = "classpath:acs/tester/tester.conf")
public class SchedulerIT extends SchedulerBaseIT {
@Autowired
private IncrementManager incrementManager;
@Before
public void setUp() {
incrementManager.removeAll();
}
@Test
public void testDownloadUploadHandling() throws InterruptedException, IOException {
ClientConfig clientConfig = new ClientConfig(getDefaultConfig());
clientConfig.setProperty(ClientConfig.SEND_INCREMENTS, "true");
ExecutionResult result = getTestClient().go(clientConfig);
assertTrue("Test execution failed", result.isSuccess());
File httpLogFile = new File(HTTP_LOG);
getWaitUtil().waitForFile(httpLogFile, 10);
assertTrue(httpLogFile.exists());
Reader logReader = null;
try {
logReader = new FileReader(httpLogFile);
CsvMapReader csvMapReader = new CsvMapReader(logReader, CsvPreference.STANDARD_PREFERENCE);
ITHelper.verifyHeaders(csvMapReader, HttpLogHeaders.headers());
assertEquals(2, result.getTestResults().size());
Map<String, String> logEntry = csvMapReader.read(HttpLogHeaders.headers());
TestResult testResult = result.getTestResults().get(0);
ITHelper.verifyDownloadFields(logEntry, testResult);
ITHelper.assertEmptyPhase2Fields(logEntry);
logEntry = csvMapReader.read(HttpLogHeaders.headers());
testResult = result.getTestResults().get(1);
ITHelper.verifyUploadFields(logEntry, testResult);
ITHelper.assertEmptyPhase2Fields(logEntry);
logEntry = csvMapReader.read(HttpLogHeaders.headers());
assertNull(logEntry);
} finally {
IOUtils.closeQuietly(logReader);
}
assertEquals(4, result.getTestIncrements().size());
getWaitUtil().wait(3);
List<Increment> increments = incrementManager.findIncrements("127.0.0.1");
assertEquals(4, increments.size());
for (int i = 0; i < 4; i++) {
ITHelper.verifyIncrement(result.getTestIncrements().get(i), increments.get(i));
}
}
@Test
public void shouldLogPhase2Requests() throws IOException, InterruptedException {
ClientConfig clientConfig = new ClientConfig(getDefaultConfig());
clientConfig.setProperty(ClientConfig.REQUEST_VERSION, "1");
ExecutionResult result = getTestClient().go(clientConfig);
assertTrue("Test execution failed", result.isSuccess());
File httpLogFile = new File(HTTP_LOG);
getWaitUtil().waitForFile(httpLogFile, 10);
assertTrue(httpLogFile.exists());
Reader logReader = null;
try {
logReader = new FileReader(httpLogFile);
CsvMapReader csvMapReader = new CsvMapReader(logReader, CsvPreference.STANDARD_PREFERENCE);
ITHelper.verifyHeaders(csvMapReader, HttpLogHeaders.headers());
assertEquals(2, result.getTestResults().size());
Map<String, String> logEntry = csvMapReader.read(HttpLogHeaders.headers());
TestResult testResult = result.getTestResults().get(0);
ITHelper.verifyDownloadFields(logEntry, testResult);
ITHelper.verifyTestLocationFields(logEntry, result.getTestLocation());
logEntry = csvMapReader.read(HttpLogHeaders.headers());
testResult = result.getTestResults().get(1);
ITHelper.verifyUploadFields(logEntry, testResult);
ITHelper.verifyTestLocationFields(logEntry, result.getTestLocation());
logEntry = csvMapReader.read(HttpLogHeaders.headers());
assertNull(logEntry);
} finally {
IOUtils.closeQuietly(logReader);
}
}
@Test
public void shouldRejectUnauthorizedUpload() throws InterruptedException, IOException {
ClientConfig clientConfig = getDefaultConfig();
clientConfig.setProperty(ClientConfig.UPLOAD_URL, "http://localhost:9002/unathorized");
ExecutionResult result = getTestClient().go(clientConfig);
File httpLogFile = new File(HTTP_LOG);
getWaitUtil().waitForFile(httpLogFile, 10);
assertTrue(httpLogFile.exists());
Reader logReader = null;
try {
logReader = new FileReader(httpLogFile);
CsvMapReader csvMapReader = new CsvMapReader(logReader, CsvPreference.STANDARD_PREFERENCE);
ITHelper.verifyHeaders(csvMapReader, HttpLogHeaders.headers());
assertEquals(2, result.getTestResults().size());
Map<String, String> logEntry = csvMapReader.read(HttpLogHeaders.headers());
TestResult testResult = result.getTestResults().get(0);
ITHelper.verifyDownloadFields(logEntry, testResult);
ITHelper.assertEmptyPhase2Fields(logEntry);
testResult = result.getTestResults().get(1);
assertEquals(DiagnosticState.ERROR_TRANSFER_FAILED, testResult.getDiagnosticState());
logEntry = csvMapReader.read(HttpLogHeaders.headers());
assertNull(logEntry);
} finally {
IOUtils.closeQuietly(logReader);
}
}
@Test
public void shouldRejectRejectTestsWithoutTestRequest() throws InterruptedException, IOException {
ClientConfig clientConfig = new ClientConfig(getDefaultConfig());
clientConfig.setProperty(ClientConfig.SEND_REQUEST, "false");
ExecutionResult result = getTestClient().go(clientConfig);
File httpLogFile = new File(HTTP_LOG);
getWaitUtil().waitForFile(httpLogFile, 10);
assertFalse(httpLogFile.exists());
assertEquals(2, result.getTestResults().size());
assertEquals(DiagnosticState.ERROR_INIT_CONNECTION_FAILED, result.getTestResults().get(0).getDiagnosticState());
assertEquals(DiagnosticState.ERROR_TRANSFER_FAILED, result.getTestResults().get(1).getDiagnosticState());
}
@Test
public void shouldHandleNdtTests() throws InterruptedException, IOException {
ClientConfig clientConfig = new ClientConfig(getDefaultConfig());
clientConfig.setProperty(ClientConfig.TEST_PROTOCOL, "NDT");
ExecutionResult result = getTestClient().go(clientConfig);
File httpLogFile = new File(HTTP_LOG);
getWaitUtil().waitForFile(httpLogFile, 10);
assertTrue(httpLogFile.exists());
Reader logReader = null;
try {
logReader = new FileReader(httpLogFile);
CsvMapReader csvMapReader = new CsvMapReader(logReader, CsvPreference.STANDARD_PREFERENCE);
ITHelper.verifyHeaders(csvMapReader, HttpLogHeaders.headers());
assertEquals(2, result.getTestResults().size());
Map<String, String> logEntry = csvMapReader.read(HttpLogHeaders.headers());
TestResult testResult = result.getTestResults().get(0);
Map<HttpLogHeaders, String> overwritten = new HashMap<HttpLogHeaders, String>();
overwritten.put(HttpLogHeaders.TEST_TYPE, "NDT");
overwritten.put(HttpLogHeaders.PORT, "7123");
overwritten.put(HttpLogHeaders.SERVER_ADDRESS, "ndt.atla.net.internet2.edu");
ITHelper.verifyTestFields(logEntry, testResult, "ndt://ndt.atla.net.internet2.edu:7123", "/", overwritten);
ITHelper.verifyTestLocationFields(logEntry, result.getTestLocation());
assertEquals("download", logEntry.get(HttpLogHeaders.DIRECTION.getName()));
logEntry = csvMapReader.read(HttpLogHeaders.headers());
testResult = result.getTestResults().get(1);
ITHelper.verifyTestFields(logEntry, testResult, "ndt://ndt.atla.net.internet2.edu:7123", "/", overwritten);
ITHelper.verifyTestLocationFields(logEntry, result.getTestLocation());
assertEquals("upload", logEntry.get(HttpLogHeaders.DIRECTION.getName()));
logEntry = csvMapReader.read(HttpLogHeaders.headers());
assertNull(logEntry);
} finally {
IOUtils.closeQuietly(logReader);
}
}
@Test
public void shouldHandleWprTests() throws InterruptedException, IOException {
ClientConfig clientConfig = new ClientConfig(getDefaultConfig());
clientConfig.setProperty(ClientConfig.TEST_PROTOCOL, "WPR");
ExecutionResult result = getTestClient().go(clientConfig);
File httpLogFile = new File(HTTP_LOG);
getWaitUtil().waitForFile(httpLogFile, 10);
assertTrue(httpLogFile.exists());
Reader logReader = null;
try {
logReader = new FileReader(httpLogFile);
CsvMapReader csvMapReader = new CsvMapReader(logReader, CsvPreference.STANDARD_PREFERENCE);
ITHelper.verifyHeaders(csvMapReader, HttpLogHeaders.headers());
assertEquals(1, result.getTestResults().size());
Map<String, String> logEntry = csvMapReader.read(HttpLogHeaders.headers());
TestResult testResult = result.getTestResults().get(0);
Map<HttpLogHeaders, String> overwritten = new HashMap<HttpLogHeaders, String>();
overwritten.put(HttpLogHeaders.TEST_TYPE, "WEB_PAGE");
overwritten.put(HttpLogHeaders.PATH, "/");
overwritten.put(HttpLogHeaders.SERVER_ADDRESS, "www.google.com");
overwritten.put(HttpLogHeaders.PORT, "80");
ITHelper.verifyTestFields(logEntry, testResult, "http://www.google.com", "/", overwritten);
ITHelper.verifyTestLocationFields(logEntry, result.getTestLocation());
assertEquals("download", logEntry.get(HttpLogHeaders.DIRECTION.getName()));
logEntry = csvMapReader.read(HttpLogHeaders.headers());
assertNull(logEntry);
} finally {
IOUtils.closeQuietly(logReader);
}
}
@Test
public void shouldHandleDnsTests() throws InterruptedException, IOException {
ClientConfig clientConfig = new ClientConfig(getDefaultConfig());
clientConfig.setProperty(ClientConfig.TEST_PROTOCOL, "DNS");
ExecutionResult result = getTestClient().go(clientConfig);
File httpLogFile = new File(HTTP_LOG);
getWaitUtil().waitForFile(httpLogFile, 10);
assertTrue(httpLogFile.exists());
Reader logReader = null;
try {
logReader = new FileReader(httpLogFile);
CsvMapReader csvMapReader = new CsvMapReader(logReader, CsvPreference.STANDARD_PREFERENCE);
ITHelper.verifyHeaders(csvMapReader, HttpLogHeaders.headers());
assertEquals(2, result.getTestResults().size());
Map<String, String> logEntry = csvMapReader.read(HttpLogHeaders.headers());
TestResultDns testResult = (TestResultDns) result.getTestResults().get(0);
ITHelper.verifyDnsFields(logEntry, testResult);
ITHelper.verifyTestLocationFields(logEntry, result.getTestLocation());
logEntry = csvMapReader.read(HttpLogHeaders.headers());
testResult = (TestResultDns) result.getTestResults().get(1);
ITHelper.verifyDnsFields(logEntry, testResult);
ITHelper.verifyTestLocationFields(logEntry, result.getTestLocation());
logEntry = csvMapReader.read(HttpLogHeaders.headers());
assertNull(logEntry);
} finally {
IOUtils.closeQuietly(logReader);
}
}
@Test
public void shouldHandleFtpTests() throws IOException, InterruptedException {
ClientConfig clientConfig = new ClientConfig(getDefaultConfig());
clientConfig.setProperty(ClientConfig.TEST_PROTOCOL, "FTP");
ExecutionResult result = getTestClient().go(clientConfig);
assertTrue("Test execution failed", result.isSuccess());
File httpLogFile = new File(HTTP_LOG);
getWaitUtil().waitForFile(httpLogFile, 10);
assertTrue(httpLogFile.exists());
Reader logReader = null;
try {
logReader = new FileReader(httpLogFile);
CsvMapReader csvMapReader = new CsvMapReader(logReader, CsvPreference.STANDARD_PREFERENCE);
ITHelper.verifyHeaders(csvMapReader, HttpLogHeaders.headers());
assertEquals(2, result.getTestResults().size());
Map<String, String> logEntry = csvMapReader.read(HttpLogHeaders.headers());
TestResult testResult = result.getTestResults().get(0);
Map<HttpLogHeaders, String> overwritten = new HashMap<HttpLogHeaders, String>();
overwritten.put(HttpLogHeaders.TEST_TYPE, "FTP");
overwritten.put(HttpLogHeaders.PATH, "/download.txt");
overwritten.put(HttpLogHeaders.SERVER_ADDRESS, "localhost");
overwritten.put(HttpLogHeaders.PORT, "3999");
overwritten.put(HttpLogHeaders.FILE_SIZE, "20000");
ITHelper.verifyTestFields(logEntry, testResult, "ftp://localhost:3999/download.txt", "/download.txt",
overwritten);
ITHelper.verifyTestLocationFields(logEntry, result.getTestLocation());
logEntry = csvMapReader.read(HttpLogHeaders.headers());
testResult = result.getTestResults().get(1);
overwritten.put(HttpLogHeaders.PORT, "3999");
overwritten.put(HttpLogHeaders.FILE_SIZE, "40000");
ITHelper.verifyTestFields(logEntry, testResult, "ftp://localhost:3999/upload.txt", "/upload.txt",
overwritten);
ITHelper.verifyTestLocationFields(logEntry, result.getTestLocation());
logEntry = csvMapReader.read(HttpLogHeaders.headers());
assertNull(logEntry);
} finally {
IOUtils.closeQuietly(logReader);
}
}
}
|
package com.fh.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fh.bean.CartBean;
import com.fh.commons.ServerResult;
import com.fh.service.ICartService;
import com.fh.utils.HttpClientUtil;
import com.fh.utils.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.*;
@Service("cartService")
public class ICartServiceImpl implements ICartService {
@Autowired
private RedisTemplate redisTemplate;
//新增购物车
@Override
public ServerResult addCart(Integer productId,String phone) {
///获取购物车id
String cartId = (String) redisTemplate.opsForValue().get(RedisKeyUtil.getCartKey(phone));
//获取商品信息
String url="http://localhost:8092/productSearch/"+productId;
String result = HttpClientUtil.doGet(url);
JSONObject jsonObject = JSON.parseObject(result);
JSONObject data = JSON.parseObject(jsonObject.get("data").toString());
//将数据存入redis中
CartBean cartBean=new CartBean();
cartBean.setProductId(productId);
cartBean.setProductName(data.getString("productName"));
cartBean.setMainImg(data.getString("mainImg"));
cartBean.setPrice(data.getBigDecimal("price"));
cartBean.setDetail(data.getString("detail"));
cartBean.setSubtitle(data.getString("subtitle"));
if(redisTemplate.opsForHash().hasKey(cartId,productId)){
CartBean cart= (CartBean) redisTemplate.opsForHash().get(cartId,productId);
cartBean.setCount(cart.getCount()+1);
}else {
cartBean.setCount(1);
}
//计算小计金额
BigDecimal bigDecimal=BigDecimal.valueOf(0.00);
BigDecimal count=new BigDecimal(cartBean.getCount());
BigDecimal subtotal=bigDecimal.add(cartBean.getPrice()).multiply(count);
cartBean.setSubtotal(subtotal);
cartBean.setIsChecked(true);
//查询商品是否有货
String stock = data.getString("stock");
if(Integer.valueOf(stock)>cartBean.getCount()){
cartBean.setIsStock(true);
}else {
cartBean.setIsStock(false);
}
redisTemplate.opsForHash().put(cartId,productId,cartBean);
Long size = redisTemplate.opsForHash().size(cartId);
return ServerResult.success(size);
}
//获取购物车中的数量
@Override
public ServerResult getCartCount(String phone) {
///获取购物车id
String cartId = (String) redisTemplate.opsForValue().get("cartId_" + phone);
Long size = redisTemplate.opsForHash().size(cartId);
return ServerResult.success(size);
}
/**
* 获取购物车的所有数据
* @param phone
* @return
*/
@Override
public Map<String, Object> findCartAll(String phone) {
///获取购物车id
String cartId = (String) redisTemplate.opsForValue().get("cartId_" + phone);
List<CartBean> cartBeanList = redisTemplate.opsForHash().values(cartId);
//计算总金额
BigDecimal bigDecimal=BigDecimal.valueOf(0.00);
for (CartBean cartBean : cartBeanList) {
if(cartBean.getIsChecked()){
bigDecimal= bigDecimal.add(cartBean.getSubtotal());
}
}
Map<String,Object> cartMap=new HashMap<>();
cartMap.put("cartList",cartBeanList);
cartMap.put("total",bigDecimal);
return cartMap;
}
/**
* 改变复选框状态
* @param phone
* @param productId
*/
@Override
public void checkStrtus(String phone, Integer productId) {
///获取购物车id
String cartId = (String) redisTemplate.opsForValue().get("cartId_" + phone);
CartBean cartBean = (CartBean) redisTemplate.opsForHash().get(cartId, productId);
cartBean.setIsChecked(!cartBean.getIsChecked());
redisTemplate.opsForHash().put(cartId,productId,cartBean);
}
/**
* 改变商品的数量
* @param phone
* @param sum
* @param productId
*/
@Override
public void changeProductSum(String phone, Integer sum, Integer productId) {
///获取购物车id
String cartId = (String) redisTemplate.opsForValue().get("cartId_" + phone);
CartBean cartBean = (CartBean)redisTemplate.opsForHash().get(cartId, productId);
cartBean.setCount(sum);
BigDecimal bigDecimal=BigDecimal.valueOf(0.00);
BigDecimal count=new BigDecimal(cartBean.getCount());
BigDecimal subtotal=bigDecimal.add(cartBean.getPrice()).multiply(count);
cartBean.setSubtotal(subtotal);
//查询商品是否有货
//获取商品信息
String url="http://localhost:8092/productSearch/"+productId;
String result = HttpClientUtil.doGet(url);
JSONObject jsonObject = JSON.parseObject(result);
JSONObject data = JSON.parseObject(jsonObject.get("data").toString());
String stock = data.getString("stock");
if(Integer.valueOf(stock)>cartBean.getCount()){
cartBean.setIsStock(true);
}else {
cartBean.setIsStock(false);
}
redisTemplate.opsForHash().put(cartId,productId,cartBean);
}
/**
* 是否全选
* @param phone
* @param productIds
*/
@Override
public void isCheckAll(String phone,String productIds) {
String cartId = (String) redisTemplate.opsForValue().get("cartId_" + phone);
List<String> list = Arrays.asList(productIds.split(","));
List<CartBean> cartBeanList = redisTemplate.opsForHash().values(cartId);
for (CartBean cartBean : cartBeanList) {
if(list.contains(String.valueOf(cartBean.getProductId()))){
cartBean.setIsChecked(!cartBean.getIsChecked());
redisTemplate.opsForHash().put(cartId,cartBean.getProductId(),cartBean);
}
}
}
/**
* 删除购物车中的商品
* @param productId
* @param phone
*/
@Override
public void deleteCart(Integer productId, String phone) {
String cartId = (String) redisTemplate.opsForValue().get("cartId_" + phone);
redisTemplate.opsForHash().delete(cartId,productId);
}
/**
* 查询所有被选中的商品
* @param phone
* @return
*/
@Override
public Map<String, Object> findProductList(String phone) {
///获取购物车id
String cartId = (String) redisTemplate.opsForValue().get("cartId_" + phone);
List<CartBean> cartBeanList = redisTemplate.opsForHash().values(cartId);
List<CartBean> cartBeans=new ArrayList<>();
//计算总金额
BigDecimal bigDecimal=BigDecimal.valueOf(0.00);
for (CartBean cartBean : cartBeanList) {
if(cartBean.getIsChecked()){
bigDecimal= bigDecimal.add(cartBean.getSubtotal());
cartBeans.add(cartBean);
}
}
Map<String,Object> cartMap=new HashMap<>();
cartMap.put("cartList",cartBeans);
cartMap.put("total",bigDecimal);
return cartMap;
}
}
|
import com.atlassian.jira.rest.client.domain.Issue;
import com.atlassian.jira.rest.client.domain.SearchResult;
import org.codehaus.jackson.map.ObjectMapper;
import org.swift.common.soap.confluence.ConfluenceSoapService;
import org.swift.common.soap.confluence.RemotePage;
import org.swift.common.soap.confluence.RemoteServerInfo;
import java.util.Set;
/**
* User: nirb
* Date: 5/27/13
*/
public class ReleaseNotesUpdate {
public static void main(String[] args) throws Exception {
String jiraUser = args[0];
String jiraPassword = args[1];
String wikiUser= args[2];
String wikiPassword = args[3];
String issueProject = args[4];
String issueFixVersion = args[5];
String sprintNumber = args[6];
String createdAfter = args[7];
String buildVersion = args[8];
String sinceVersion = args[9];
JiraClient jiraClient = new JiraClient(jiraUser, jiraPassword);
String issueType = "";
String issueResolution = "";
String issueStatus = "";
String tempCreatedAfter = createdAfter;
String tempIssueFixVersion = issueFixVersion;
ObjectMapper mapper = new ObjectMapper();
WikiClient wikiClient = new WikiClient("http://wiki.gigaspaces.com/wiki", wikiUser, wikiPassword);
System.out.println("Connected ok.");
ConfluenceSoapService service = wikiClient.getConfluenceSOAPService();
String token = wikiClient.getToken();
RemoteServerInfo info = service.getServerInfo(token);
System.out.println("Confluence version: " + info.getMajorVersion() + "." + info.getMinorVersion());
System.out.println("Completed.");
String cutBuildVersion = buildVersion.substring(0, buildVersion.length()-1);
String pageTitle = "GigaSpaces XAP " + cutBuildVersion + "X Release Notes";
RemotePage page = service.getPage(token, "RN", pageTitle);
String pageContent = page.getContent();
String[] cards = {"{card:label=Known Issues & Limitations}", "{card:label=Fixed Issues}", "{card:label=New Features and Improvements}"};
String[] headlines = {
"{card:label=Known Issues & Limitations}\n" +
"|| Key || Summary || SalesForce ID || Since version || Workaround || Platform/s ||",
"{card:label=Fixed Issues}\n" +
"|| Key || Summary || Fixed in Version || SalesForce ID || Platform/s ||",
"{card:label=New Features and Improvements}\n" +
"|| Key || Summary || Since Version || SalesForce ID || Documentation Link || Platform/s ||"
};
int headlineIndex = 0;
for(String card : cards){
int cardStartIndex = pageContent.indexOf(headlines[headlineIndex]);
int cardEndIndex = pageContent.indexOf("\n{card}", cardStartIndex);
String cardSubstring = pageContent.substring(cardStartIndex + headlines[headlineIndex].length(), cardEndIndex);
pageContent = pageContent.replace(cardSubstring, "");
headlineIndex++;
}
for(int i = 0; i < 3; i++){
//Fixed issues
if(i == 0){
issueType = "Bug";
issueResolution = "Fixed";
issueStatus = "Closed";
issueFixVersion = tempIssueFixVersion;
createdAfter = "";
}
//New features
if(i == 1){
issueType = "\"New Feature\", Task, Improvement, Sub-task";
issueResolution = "Fixed";
issueStatus = "Closed";
issueFixVersion = tempIssueFixVersion;
createdAfter = "";
}
//Known issues
if(i == 2){
issueType = "Bug";
issueResolution = "Unresolved";
issueStatus = "";
issueFixVersion = "";
createdAfter = tempCreatedAfter;
}
String jqlQuery = jiraClient.createJqlQuery(issueProject, issueType, issueResolution, issueStatus, issueFixVersion, sprintNumber, createdAfter);
System.out.println("query: " + jqlQuery);
SearchResult filter = jiraClient.createFilter(jqlQuery);
Set<Issue> issuesFromFilter = jiraClient.getIssuesFromFilter(filter);
for(Issue issue : issuesFromFilter){
String fieldsText;
String newEntryText;
if(!jiraClient.isPublicIssue(mapper, issue)){
continue;
}
if(issueType.contains("Bug")){
if(issueResolution.contains("Unresolved")){
fieldsText = "{card:label=Known Issues & Limitations}\n" +
"|| Key || Summary || SalesForce ID || Since version || Workaround || Platform/s ||";
newEntryText = "| " + issue.getKey() + " | " + issue.getSummary() + " | " +jiraClient.salesforceIdIterableToToString(issue) + " | " + sinceVersion + " | | " + jiraClient.platformsIterableToToString(mapper, issue) + " |";
}
else{
fieldsText = "{card:label=Fixed Issues}\n" +
"|| Key || Summary || Fixed in Version || SalesForce ID || Platform/s ||";
newEntryText = "| " + issue.getKey() + " | " + issue.getSummary() + " | " + jiraClient.fixVersionIterableToToString(issue) + " | " + jiraClient.salesforceIdIterableToToString(issue) + " | " + jiraClient.platformsIterableToToString(mapper, issue) + " |";
}
}
else{
fieldsText = "{card:label=New Features and Improvements}\n" +
"|| Key || Summary || Since Version || SalesForce ID || Documentation Link || Platform/s ||";
newEntryText = "| " + issue.getKey() + " | " + issue.getSummary() + " | " + jiraClient.fixVersionIterableToToString(issue) + " | " + jiraClient.salesforceIdIterableToToString(issue) +" | | " + jiraClient.platformsIterableToToString(mapper, issue) + " |";
}
int cardStartIndex = pageContent.indexOf(fieldsText);
String cardSubstring = pageContent.substring(cardStartIndex, cardStartIndex + fieldsText.length());
String newCardSubstring;
String newText = fieldsText + "\n" + newEntryText;
newCardSubstring = cardSubstring.replace(fieldsText, newText);
pageContent = pageContent.replace(cardSubstring, newCardSubstring);
page.setContent(pageContent);
}
}
wikiClient.getConfluenceSOAPService().storePage(wikiClient.getToken(), page);
}
}
|
/* https://codeforces.com/contest/279/problem/B
tag: #binary-search #implementation #two-pointer
max (get number of books can be read that counted from i-th element)
*/
/* Example:
10 15
10 9 1 1 5 10 5 3 7 2
f |
l |
*/
import java.util.Scanner;
public class Books {
static int calMaxNumBooks() {
Scanner scanner = new Scanner(System.in);
int numberOfBooks = scanner.nextInt();
int freeMinutes = scanner.nextInt();
int[] bookMinuteArr = new int[numberOfBooks];
for (int i = 0; i < numberOfBooks; i++) {
int minute = scanner.nextInt();
bookMinuteArr[i] = minute;
}
int maxBooksBeRead = 0;
int count = 0;
int firstIdx = 0;
int lastIdx = 0;
while (lastIdx < numberOfBooks) {
if (bookMinuteArr[lastIdx] <= freeMinutes) {
freeMinutes -= bookMinuteArr[lastIdx];
count++;
lastIdx++;
if (count > maxBooksBeRead) {
maxBooksBeRead = count;
}
} else {
freeMinutes += bookMinuteArr[firstIdx];
count--;
firstIdx++;
/*
if (count > 0) {
freeMinutes += bookMinuteArr[firstIdx];
firstIdx++;
count--;
} else {
lastIdx++;
}
*/
}
}
return maxBooksBeRead;
}
public static void main(String[] args) {
System.out.println(calMaxNumBooks());
}
}
|
package com.weathair.controllers;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.weathair.dto.indicators.AirIndicatorDto;
import com.weathair.entities.indicators.AirIndicator;
import com.weathair.exceptions.AirIndicatorException;
import com.weathair.exceptions.TownshipException;
import com.weathair.services.AirIndicatorService;
/**
* @author tarbo
* controller of air indicator
*/
@CrossOrigin
@RestController
@RequestMapping("airindicators")
public class AirIndicatorController {
private AirIndicatorService airIndicatorService;
public AirIndicatorController(AirIndicatorService airIndicatorService) {
super();
this.airIndicatorService = airIndicatorService;
}
/**
* @return all air indicators with "all" on url
* @throws AirIndicatorException
*/
@GetMapping
public List<AirIndicator> listAllAirIndicator() throws AirIndicatorException {
return airIndicatorService.getAllAirIndicators();
}
@GetMapping("township={townshipName}")
public List<AirIndicator> listAirIndicatorsByTownshipName(@PathVariable String townshipName) throws AirIndicatorException{
return airIndicatorService.getAirIndicatorsByTownshipName(townshipName);
}
/**
* @param id
* @return an air indicator by id
* @throws AirIndicatorException
*/
@GetMapping("{id}")
public ResponseEntity<?> airIndicatorById(@PathVariable Integer id) throws AirIndicatorException {
AirIndicator airIndicator = this.airIndicatorService.getAirIndicatorById(id);
return ResponseEntity.ok(airIndicator);
}
/**
* @param dto
* @return a new air indicator
* @throws AirIndicatorException
* @throws TownshipException
*/
@PreAuthorize("hasAuthority('ROLE_ADMINISTRATOR')")
@PostMapping
public ResponseEntity<?> createNewAirIndicator(@RequestBody AirIndicatorDto airIndicatorDto) throws AirIndicatorException, TownshipException {
return ResponseEntity.ok(airIndicatorService.createAirIndicator(airIndicatorDto));
}
/**
* @param id
* @param newDateTime
* @throws AirIndicatorException
* @throws TownshipException
*/
@PreAuthorize("hasAuthority('ROLE_ADMINISTRATOR')")
@PutMapping("{id}")
public ResponseEntity<?> updateAirIndicator(@RequestParam Integer id, @RequestBody AirIndicatorDto airIndicatorDto)
throws AirIndicatorException, TownshipException {
airIndicatorService.updateAirIndicator(id, airIndicatorDto);
return ResponseEntity.ok("The air indicator with id " + id + " has been successfully updated");
}
/**
* @param id
* delete an air indicator by id
* @throws AirIndicatorException
*/
@PreAuthorize("hasAuthority('ROLE_ADMINISTRATOR')")
@DeleteMapping("{id}")
public ResponseEntity<?> deleteAirIndicatorByUser(@RequestParam Integer id) throws AirIndicatorException {
airIndicatorService.deleteAirIndicator(id);
return ResponseEntity.ok("The air indicator with id " + id + " has been successfully deleted");
}
}
|
package services;
import exceptions.MessageFormatException;
import models.MovieOption;
import models.Payload;
import services.interfaces.MovieService;
import services.interfaces.TCPResquestHandler;
import javax.inject.Inject;
import java.io.*;
import java.net.Socket;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
public class TCPResquestHandlerImpl implements TCPResquestHandler {
static Logger logger = Logger.getLogger(TCPResquestHandlerImpl.class.getName());
private Socket clientSocket;
private final MovieService movieService;
@Inject
public TCPResquestHandlerImpl(MovieService movieService) {
this.movieService = movieService;
}
/**
* Deals with client resquest and query MovieService
*/
public void run() {
try {
Payload requestPayload = getRequestPayload();
final String responseContent = movieService.findAllByTitle(requestPayload.getContent())
.stream()
.map(MovieOption::getName)
.collect(Collectors.joining("\n"));
final Payload responsePayload = new Payload(responseContent);
sendMessage(responsePayload.toString());
} catch (IOException e) {
handleError(e);
} finally {
close();
}
}
/**
* Closes the client socket connection
* After query movies list server will stop client connection
*/
private void close() {
try {
this.clientSocket.close();
} catch (IOException e) {
logger.severe("Error occurred while trying to close socket connection..");
}
}
/**
* Send message to socket client
*
* @param message
* @return
* @throws IOException
*/
private void sendMessage(String message) throws IOException {
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println(message);
out.println('\n');
}
/**
* Handle a friendly error to socket client
* For now a default message is sent
*
* @param ex
*/
public void handleError(IOException ex) {
try {
OutputStream output = clientSocket.getOutputStream();
output.write(ex.getMessage().getBytes());
} catch (Exception e) {
logger.log(Level.SEVERE, "An Error occurred while processind the client request", e);
}
}
/**
* Cast InputStream to a common format 'models.Payload'
*
* @return
*/
private Payload getRequestPayload() throws IOException {
final Optional<String> requestString = clientInputStreamToString();
final Payload payload = new Payload();
if (requestString.isPresent()) {
payload.setContent(requestString.get());
}
return payload;
}
/**
* @param
* @return message sent by client in String format or null
*/
private Optional<String> clientInputStreamToString() throws IOException {
final InputStream inputStream = this.clientSocket.getInputStream();
final StringBuilder queryContentSb = new StringBuilder();
final StringBuilder queryLengthSb = new StringBuilder();
long queryLength = -1;
int incoming = inputStream.read();
while (incoming != -1) {
char c = (char) incoming;
if (queryLength > -1) {
queryContentSb.append(c);
} else if (queryLength == -1) {
if (c == ':') {
queryLength = safeParseToInteger(queryLengthSb.toString());
}
queryLengthSb.append(c);
}
if (queryContentSb.toString().getBytes().length == queryLength)
break;
incoming = inputStream.read();
}
if(!queryContentSb.toString().matches("^[a-zA-Z0-9/:]+$")){
throw new MessageFormatException("The <query> can only have alphanumeric chars and '/:', please rewrite your message...");
}
return Optional.of(queryContentSb.toString());
}
private Integer safeParseToInteger(String queryLength) throws MessageFormatException {
try {
final Integer value = Integer.parseInt(queryLength);
if(value.equals(0)){
throw new MessageFormatException("The <query> should not be empty, please rewrite your message...");
}
return Integer.parseInt(queryLength);
} catch (NumberFormatException e) {
throw new MessageFormatException("The <query length> is out of 'int' range and is not valid, please rewrite your message...");
}
}
@Override
public void setClientSocket(Socket clientSocket) {
this.clientSocket = clientSocket;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.