blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 7
332
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
50
| license_type
stringclasses 2
values | repo_name
stringlengths 7
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 557
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
684M
⌀ | star_events_count
int64 0
77.7k
| fork_events_count
int64 0
48k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 82
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
5.41M
| extension
stringclasses 11
values | content
stringlengths 7
5.41M
| authors
listlengths 1
1
| author
stringlengths 0
161
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7d2790ac9c3831da5d39c95491ded74b7dbfd4a5 | 7b43ceaaf31d06fb12869abc15bfa6c904d81eda | /src/main/java/com/technopreneur/moneytransfer/web/MoneyTransferController.java | da20f5233d36a9d77b28aa35a642e0959036799b | []
| no_license | technopreneur-milind/moneytransfer | 8fed02c327cfbcec75c9685da3423e8b97061f49 | d5dd622007e09e0c3802c2bbe98c59012211e7a0 | refs/heads/master | 2022-06-07T07:39:02.967207 | 2020-01-03T15:01:06 | 2020-01-03T15:01:06 | 230,803,715 | 0 | 0 | null | 2021-06-04T02:24:10 | 2019-12-29T21:09:54 | Java | UTF-8 | Java | false | false | 2,838 | java | package com.technopreneur.moneytransfer.web;
import com.google.gson.Gson;
import com.google.inject.Inject;
import com.technopreneur.moneytransfer.exception.MoneyTransferValidationException;
import com.technopreneur.moneytransfer.model.MoneyTransferBatchDetail;
import com.technopreneur.moneytransfer.model.MoneyTransferDetail;
import com.technopreneur.moneytransfer.model.Response;
import com.technopreneur.moneytransfer.model.Status;
import com.technopreneur.moneytransfer.service.MoneyTransferService;
import com.technopreneur.moneytransfer.service.TransactionStatusService;
import com.technopreneur.moneytransfer.validate.MoneyAppValidator;
import spark.Request;
import java.util.List;
import static spark.Spark.*;
public class MoneyTransferController implements BaseController {
@Inject
private MoneyTransferService moneyTransferService;
@Inject
private MoneyAppValidator validator;
@Inject
private TransactionStatusService transactionStatusService;
private final String TRANSFER_QUEUE_MESSAGE ="Your transfers are succesfully queued ! Please refer Data Section for Transaction Id." +
"You can quote this transaction Id for any queries related to the transfer. You can check status at /transfer/status/{transactionId} endpoint";
@Override
public void addEndPoints() {
transfer();
batchTransfer();
transactionStatus();
}
private void transactionStatus() {
get("/transfer/status/:transactionId", (request, response) -> {
response.type("application/json");
String transactionId = request.params(":transactionId");
return new Gson().toJson(transactionStatusService.getTransactionStatus(transactionId));
});
}
private void transfer() {
post("/transfer", (request, response) -> {
response.type("application/json");
MoneyTransferDetail transferDetail = new Gson().fromJson(request.body(), MoneyTransferDetail.class);
validator.validateMoneyTransferDetail(transferDetail);
String transactionId = moneyTransferService.transfer(transferDetail);
return new Gson().toJson(new Response(Status.SUCCESS, TRANSFER_QUEUE_MESSAGE, transactionId));
});
}
private void batchTransfer() {
post("/batchTransfer", (request, response) -> {
response.type("application/json");
MoneyTransferBatchDetail transferBatchDetail = new Gson().fromJson(request.body(), MoneyTransferBatchDetail.class);
validator.validateMoneyTransferDetail(transferBatchDetail);
List<String> transactionIds = moneyTransferService.batchTransfer(transferBatchDetail);
return new Gson().toJson(new Response(Status.SUCCESS, TRANSFER_QUEUE_MESSAGE, transactionIds));
});
}
}
| [
"[email protected]"
]
| |
ef07a210768ccb5588a264bae167d4bc20ee71e0 | ff464ccb127fa5b9ba6e4be423a1422853667672 | /Module2/src/Task4/Comment.java | 308a865b6cf27e86a5b4728fba7704344b743117 | []
| no_license | Stanislav077/ALevel | 33ac53c460cc4fdd2de283fe9250c55240fc6608 | 5e10ad008bf034656917ca6258f6926d8cf96fbe | refs/heads/master | 2020-03-18T16:22:14.888888 | 2018-05-26T10:00:29 | 2018-05-26T10:00:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 319 | java | package Task4;
/**
* Created by Ivan Isaev on 13.04.2018.
*/
public class Comment {
String userId;
String comment;
Comment(String userId, String comment){
this.userId = userId;
this.comment = comment;
}
public String toString(){
return userId + " : " + comment;
}
}
| [
"[email protected]"
]
| |
1048b00100f98f1da57864b4661568dab86d6e6a | 8b07dffa0c30339dd6bc85ae9d65e7c10c4d311c | /Server/Brainsense_new/src/com/matrix/brainsense/dao/AdminDao.java | 95825d591b84370a154eec95b4d46f59aa2c66c7 | []
| no_license | joselyncui/Bransense | 7c7afe43c288b039b4ee70796fb0e05c803b1da8 | f423bd8c91a520b3fa5c2bcdf1ece78ba1489576 | refs/heads/master | 2021-01-10T09:20:44.114298 | 2015-10-22T01:06:11 | 2015-10-22T01:06:11 | 44,713,427 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 285 | java | package com.matrix.brainsense.dao;
import com.matrix.brainsense.entity.Admin;
public interface AdminDao extends BaseDao<Admin> {
/**
* get admin by user name
* @param userName the name of admin
* @return see <code>Admin</code>
*/
Admin getAdminByName(String userName);
}
| [
"[email protected]"
]
| |
6ce880a01c4e80e176603efc8fff31e0865001b0 | 2f5f605d845d4f9003929442a2e78544e69fd9f7 | /src/com/xms/offer/Window.java | a0dc42373ad0f1d517a400682bd021339dbc6a6d | [
"Apache-2.0"
]
| permissive | xms1000/Structure | 759c396959432467c9ac0e362ee21d3d68aeb94b | 80db9747f2e1ca2321423834dc50c7dd8e5a1026 | refs/heads/master | 2021-01-19T12:22:12.473698 | 2017-09-22T10:19:48 | 2017-09-22T10:19:48 | 100,778,134 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 945 | java | package com.xms.offer;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
/**
* Created by xms on 2017/8/25.
*/
public class Window {
public ArrayList<Integer> maxInWindows(int[] num, int size) {
ArrayList<Integer> list = new ArrayList();
if (size > num.length) {
return list;
}
Deque<Integer> deque = new LinkedList<>();
for (int i = 0; i < size; i++) {
while (!deque.isEmpty() && num[i] > num[deque.peekLast()]) {
deque.pollLast();
}
deque.addLast(i);
}
for (int j = size; j < num.length; j++) {
while (!deque.isEmpty() && num[j] > num[deque.peekLast()]) {
deque.pollLast();
}
deque.addLast(j);
if (deque.peekFirst() <= j - size) {
deque.pollFirst();
}
}
return list;
}
}
| [
"[email protected]"
]
| |
4734609978b7566e1cbed51e91d8d73db03fea7a | ff84da45fcaf796cb164ca4c71531c33350d70ce | /shop3/com/enation/app/shop/core/model/statistics/MonthAmount.java | 8c4fb2ef08d15c0996e4b24e34a18756c21ea6d8 | []
| no_license | xxs/xxs_src | 25306a20acbdc4558e99990fded6949f769c4c0a | 27cff88c3e9a475eb9d0f6494ca4bca921e9de06 | refs/heads/master | 2021-01-02T09:34:09.444655 | 2013-04-23T05:23:42 | 2013-04-23T05:23:42 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 801 | java | /* */ package com.enation.app.shop.core.model.statistics;
/* */
/* */ public class MonthAmount
/* */ {
/* */ private String month;
/* */ private Double amount;
/* */
/* */ public String getMonth()
/* */ {
/* 16 */ return this.month;
/* */ }
/* */
/* */ public void setMonth(String month) {
/* 20 */ this.month = month;
/* */ }
/* */
/* */ public Double getAmount() {
/* 24 */ return this.amount;
/* */ }
/* */
/* */ public void setAmount(Double amount) {
/* 28 */ this.amount = amount;
/* */ }
/* */ }
/* Location: C:\Users\xiaxiaoshi\Desktop\shop\
* Qualified Name: com.enation.app.shop.core.model.statistics.MonthAmount
* JD-Core Version: 0.6.0
*/ | [
"[email protected]"
]
| |
06fc31899f6d742144f6df819d655ed96b981371 | 0066d4a41c2e5b39f7b4f81a8527cffd960c6b4b | /SyncProxyEx_AQI/sdl_android_lib/src/main/java/com/smartdevicelink/util/HttpUtils.java | 926a3a17c69a48f7b65def44b6bc30c2abd876c7 | []
| no_license | APCVSRepo/SdlEx-Android | 336a222f468c4506065ef3e631d9fccf94f9f7a5 | 012315e4fe8ff4a852748fe87d2deab649ed2aaf | refs/heads/master | 2021-09-22T11:48:10.220708 | 2018-09-10T06:55:21 | 2018-09-10T06:55:21 | 104,317,535 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 635 | java | package com.smartdevicelink.util;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class HttpUtils{
public static Bitmap downloadImage(String urlStr) throws IOException{
URL url = new URL(urlStr);
URLConnection connection = url.openConnection();
BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
Bitmap result = BitmapFactory.decodeStream(bis);
bis.close();
return result;
}
}
| [
"[email protected]"
]
| |
394afd6d1569a2016ffbdb03a0a9ec9a1cc3db67 | 8d26b26652f736688269c495cb74217e48836b28 | /DoubleHampsterdam/src/org/usfirst/frc/team1829/robot/commands/BasicAutonomousDriveCommand.java | 24c69ddcb91bb7954570b26199139818f1b489b5 | []
| no_license | ZachEthington/FRC-2016-Robot-Code | 81749c4f7992e40e5456d6f4897b17513c913548 | e564e7754ef433e003d307840b84e0a815f06cc0 | refs/heads/master | 2021-01-11T01:53:57.014652 | 2016-10-12T00:51:31 | 2016-10-12T00:51:31 | 70,646,962 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,108 | java | package org.usfirst.frc.team1829.robot.commands;
import org.usfirst.frc.team1829.robot.Robot;
import edu.wpi.first.wpilibj.command.Command;
public class BasicAutonomousDriveCommand extends Command {
private long myTime;
public BasicAutonomousDriveCommand() {
requires(Robot.getcurrentDrive());
}
@Override
protected void initialize() {
// TODO Auto-generated method stub
//sets current time to varibale myTime
myTime = System.currentTimeMillis();
//sets finish time to 3 seconds
myTime += 6500;
//myTime += 3500;
}
@Override
protected void execute() {
// TODO Auto-generated method stub
Robot.getcurrentDrive().Arcade(-0.75, 0.05);
}
@Override
protected boolean isFinished() {
// TODO Auto-generated method stub
return System.currentTimeMillis() >= myTime;
}
@Override
protected void end() {
// TODO Auto-generated method stub
//stops robot at end of exectue method
Robot.getcurrentDrive().Arcade(0.0, 0.0);
}
@Override
protected void interrupted() {
// TODO Auto-generated method stub
}
}
| [
"[email protected]"
]
| |
fd34d47763e227ca49f96ece79cf03a8a24e3e2d | da85538602c4d19c5236e5535606eac2a8a6fc66 | /src/ec/edu/ups/vista/Principal.java | 08483fb54c08f9cc6fc92c7ead9dd0ddf97776d8 | []
| no_license | dleont/RegistroCalificaciones | 37078c4e2cfba8dfb8716fbb7147d6e411b51d37 | 42238575c60465d39f428d41fcaf4a7fecd2f371 | refs/heads/master | 2020-05-05T00:02:39.663155 | 2019-04-09T03:32:23 | 2019-04-09T03:32:23 | 179,564,246 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,217 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ec.edu.ups.vista;
import ec.edu.ups.clases.Carrera;
import ec.edu.ups.clases.Estudiante;
import ec.edu.ups.clases.Grupo;
import ec.edu.ups.clases.HistorialCalificacionEstudiante;
import ec.edu.ups.clases.Materia;
import ec.edu.ups.clases.Persona;
import ec.edu.ups.clases.Profesor;
import ec.edu.ups.clases.Sede;
/**
*
* @author Darwin
*/
public class Principal {
public static void main(String[] args) {
System.out.println("Iniciando programa de Registro de Calificaciones");
Estudiante est = new Estudiante();
/**
* //asignamos valores a los atributos de la clase Estudiante y Perosna
* est.setCodigo(1); est.setNombre("juan quispe");
* est.setCedula("0106993835"); est.setDireccion("Baños");
* est.setTelefono("4040706"); est.setCorreo("[email protected]");
* //est.setSede(Sede); //est.setCarrera(carrera);
*
* //obtenemos el valor para imprimir en consola
* System.out.println("Codigo: "+est.getCodigo());
* System.out.println("Nombre: "+est.getNombre());
* System.out.println("Cedula: "+est.getCedula());
* System.out.println("Diireccion: "+est.getDireccion());
* System.out.println("Telefono: "+est.getTelefono());
* System.out.println("Correo: "+est.getCorreo());
* System.out.println("Sede: "+est.getSede());
* //System.out.println("Carrera: "est.getCarrera());*
*/
//instanciamos mediante un constructor y no es necesario setiar; asignamos valores directamente
//(crear constructoren la clase instanciada)
Sede cuenca = new Sede(1, "Sede Cuenca", "Calle vieja", "777123");
Carrera computacion = new Carrera(001, "Computacion", 10, 40, "Ing. Ciencias de la computacion");
Carrera electronica = new Carrera(002, "Electronica", 10, 35, "Ing. Electronico");
Carrera telematica = new Carrera(003, "Telematica", 10, 40, "Ing. en Telematica");
//6 materias
Materia calculoVa = new Materia(004, "Calculo de una Variable", 3, 240, 1);
Materia mateAvan = new Materia(006, "Matematicas Avanzadas en Ingeniería", 3, 160, 3);
Materia electro = new Materia(007, "Electronica", 3, 120, 3);
Materia sistOper = new Materia(8, "Sistemas Operativos", 3, 160, 2);
Materia ecuaciones = new Materia(9, "Ecaciones Diferenciales", 3, 160, 2);
Materia prograApli = new Materia(010, "Programacion Aplicada", 3, 240, 3);
//2 profesores
Persona profe1 = new Profesor("Ing. en Sistemas", 1500, "profesor", 011, "Andrea Plaza", "0102551448", "09665412872", "El vergel", "[email protected]");
Persona profe2 = new Profesor("Ing. en Telecomunicacion", 1200, "Dir. carrera", 012, "Pedro Songor", "01154851448", "0954871458", "Miraflores", "[email protected]");
//4 esttidiantes
Persona est1 = new Persona(013, "Esteban Barrera", "0105884847", "0963225414", "Baños", "[email protected]");
Persona est2 = new Persona(014, "Cristian Jacome", "0105884557", "0952144875", "Checa", "[email protected]");
Persona est3 = new Persona(015, "Brayan Barbecho", "0156998554", "0985215487", "Cuenca", "[email protected]");
Persona est4 = new Persona(016, "Esteban Quinde", "0105884847", "0954216598", "Deleg", "[email protected]");
//2 grupos
Grupo grup1 = new Grupo(17, "Grupo 1", 40);
Grupo grup2 = new Grupo(18, "Grupo 2", 35);
// 6 notas
HistorialCalificacionEstudiante nota1 = new HistorialCalificacionEstudiante(35, 10, 35, 10, "Sistemas Operativos");
HistorialCalificacionEstudiante nota2 = new HistorialCalificacionEstudiante(35, 15, 35, 15, "Calculo de una Varible");
HistorialCalificacionEstudiante nota3 = new HistorialCalificacionEstudiante(30, 10, 30, 10, "Electronica");
HistorialCalificacionEstudiante nota4 = new HistorialCalificacionEstudiante(30, 10, 30, 10, "Programacion Aplicada");
HistorialCalificacionEstudiante nota5 = new HistorialCalificacionEstudiante(30, 10, 30, 10, "Ecuaciones Diferenciales");
HistorialCalificacionEstudiante nota6 = new HistorialCalificacionEstudiante(30, 10, 30, 10, "Matematica Avanzada");
// agregar objetos a los objetos
cuenca.agregarCarrera(electronica);
cuenca.agregarCarrera(computacion);
cuenca.agregarCarrera(telematica);
//asignamos materias a las carreras
electronica.agregarMateria(electro);
electronica.agregarMateria(calculoVa);
computacion.agregarMateria(mateAvan);
computacion.agregarMateria(prograApli);
telematica.agregarMateria(sistOper);
telematica.agregarMateria(ecuaciones);
System.out.println("Sede Cuenca"+ cuenca);
}
}
| [
"[email protected]"
]
| |
03cabd14ad3b139b4b4cb77c3ba3e5c11032fd52 | 2d08ae316d4e761deeaa4c1dddf1f5f01390dd8c | /app/src/main/java/com/song/fileiodemo/AssetsUtil.java | 6b7c817ec0d1aecf4b3315f62dc9d9221e5b241c | []
| no_license | songguanxun/FileDemo | 1711a8395001b1c1d81d34a58ed919b77eeec363 | 206bf028fe19229de918b6216d898415e8e6ea21 | refs/heads/master | 2020-07-31T08:59:02.318963 | 2019-09-24T09:04:26 | 2019-09-24T09:04:26 | 210,553,050 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 7,981 | java | package com.song.fileiodemo;
import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Assets读取文件工具类
*/
public class AssetsUtil {
/**
* 遍历读取assets文件夹下的文件。
*
* @param path assets中的文件或文件夹路径
*/
public static void travelAssetsFile(Context context, String path) {
if (context == null) {
Log.i("sgx", "context为空");
return;
}
if (path == null || path.equals("")) {
Log.i("sgx", "传入地址为空");
return;
}
AssetManager assetManager = context.getAssets();
try {
String[] fileList = assetManager.list(path); // path文件夹下的子文件列表
if (fileList != null) {
// 步骤1:遍历Assets中的文件夹path
for (String item : fileList) {
String subPath = path + '/' + item; // path文件夹下的子文件名称
String[] grandChildren = assetManager.list(subPath);
if (grandChildren != null) {
if (grandChildren.length > 0) { // 是文件夹
travelAssetsFile(context, subPath);
} else { // 是文件
Log.i("sgx", "assets文件: " + subPath);
Log.i("sgx", "assets文内容: " + getTextFromAssetsFile(context, subPath));
Log.i("sgx", "--------------------------------------------");
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 读取获取assets目录下的单个文件的文本数据。
*
* @param path 文件在assets文件夹中的相对地址。
* @return 文件的文本数据,字符串格式。
*/
public static String getTextFromAssetsFile(Context context, String path) {
try {
InputStreamReader inputReader = new InputStreamReader(context.getAssets().open(path));
BufferedReader bufferedReader = new BufferedReader(inputReader);
StringBuilder result = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null)
result.append(line);
return result.toString();
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* 拷贝assets文件到files文件夹
* <p>
* 注:文件夹在files中的目录结构与assets中的相同。
*
* @param context context
* @param path assets文件地址
*/
public static void copyAssetsFileToFiles(Context context, String path) {
copyAssetsFileToFiles(context, path, path);
}
/**
* 拷贝assets文件到files文件夹
* <p>
* 注:文件夹在files中的目录结构可以与assets中的不同。
*
* @param context Context,请使用getApplicationContext()获取
* @param sourcePath 文件原路径,如:"superhero/dc/profile1.json"
* @param targetPath 文件目标路径,如:"collection/superhero/my_profile1.json"
*/
public static void copyAssetsFileToFiles(Context context, String sourcePath, String targetPath) {
if (context == null) {
Log.i("sgx", "context为空");
return;
}
if (sourcePath == null || sourcePath.isEmpty() || targetPath == null || targetPath.isEmpty()) {
Log.e("sgx", "原路径或目标路径为空或空字符串");
return;
}
BufferedInputStream inputStream = null;
BufferedOutputStream outputStream = null;
try {
// 输入流
inputStream = new BufferedInputStream(context.getAssets().open(sourcePath));
// 输出文件
File targetFile = new File(context.getFilesDir() + "/" + targetPath);
// 上级目录不存在,创建多级目录
File targetDir = targetFile.getParentFile();
if (targetDir != null && !targetDir.exists()) {
targetDir.mkdirs();
}
boolean created = targetFile.createNewFile();
if (created) {
Log.i("sgx", "本文件不存在,且已成功创建: " + targetPath);
} else {
Log.i("sgx", "本文件已存在: " + targetPath);
}
// 输出流
outputStream = new BufferedOutputStream(new FileOutputStream(targetFile));
int bufferNumber = inputStream.available();
byte[] buf = new byte[bufferNumber];
int i;
// 写入
while ((i = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, i);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close(inputStream);
close(outputStream);
}
}
private static void close(Closeable c) {
if (c != null) {
try {
c.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 拷贝assets文件夹到files文件夹
* <p>
* 注:文件夹在files中的目录结构与assets中的相同。
*
* @param context context
* @param path assets文件夹地址
*/
public static void copyAssetsDirToFiles(Context context, String path) {
copyAssetsDirToFiles(context, path, path);
}
/**
* 拷贝assets文件夹到files文件夹
* <p>
* 注:文件夹在files中的目录结构与assets中的可以相同。
*
* @param context Context,请使用getApplicationContext()获取
* @param sourceDirPath 源文件夹地址(assets中),如:"superhero"
* @param targetDirPath 目标文件夹地址(files中),如:"my_superhero"
*/
public static void copyAssetsDirToFiles(Context context, String sourceDirPath, String targetDirPath) {
if (context == null) {
Log.i("sgx", "context为空");
return;
}
if (sourceDirPath == null || sourceDirPath.isEmpty()
|| targetDirPath == null || targetDirPath.isEmpty()) {
Log.i("sgx", "源文件或目标文件夹地址为空或空字符串");
return;
}
AssetManager assetManager = context.getAssets();
try {
String[] fileList = assetManager.list(sourceDirPath); // sourceDirPath文件夹下的子文件列表
if (fileList != null) {
// 步骤1:遍历Assets中的文件夹path
for (String item : fileList) {
String sourceSubPath = sourceDirPath + '/' + item; // sourceDirPath文件夹下的子文件名称
String targetSubPath = targetDirPath + "/" + item; // targetDirPath文件夹下的子文件名称
String[] grandChildren = assetManager.list(sourceSubPath);
if (grandChildren != null) {
if (grandChildren.length > 0) { // 是文件夹
copyAssetsDirToFiles(context, sourceSubPath, targetSubPath);
} else { // 是文件
copyAssetsFileToFiles(context, sourceSubPath, targetSubPath);
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
| [
"[email protected]"
]
| |
0e14670f877a37c7ad0ca4cf89fad3bff260daf5 | 536e5d23800eb24b8594bdb40b38e337d179a2dd | /TestProject/src/main/java/com/mycompany/entity/Interface/CreditCard.java | d473ae1fa89eea90f873785da7d5b433187a8dff | []
| no_license | koke6645/SE452 | 1a30ec34e6e67e3beb7bf152a84c213747bcc683 | 4d8ca067c48fec75a3c110d19d9e452de67f1d39 | refs/heads/master | 2016-09-05T20:33:37.955057 | 2014-11-18T05:31:25 | 2014-11-18T05:31:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 341 | java | package com.mycompany.entity.Interface;
public interface CreditCard {
boolean equals(Object object);
int getCardexpire();
int getCardnumber();
Integer getCreditid();
void setCardexpire(int cardexpire);
void setCardnumber(int cardnumber);
void setCreditid(Integer creditid);
String toString();
}
| [
"[email protected]"
]
| |
3024a1cfcf0f3ae6c9f2f6e8ea58e672b869c484 | 895f962a89306754687fbaed8170cd370b2a0d21 | /src/main/resources/BasePage.java | 1dc103db7e1b4b8dd63a88ed32c8858d445d94d3 | []
| no_license | eduhlana/gcpjava | 991f673b376e5dfe4da664396f20c014e0ecdd31 | e619e11aa6aa540583a39e9ecc22e8faced11652 | refs/heads/master | 2020-03-26T16:48:05.154345 | 2018-08-17T13:37:17 | 2018-08-17T13:37:17 | 145,123,571 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,988 | java |
package core;
import static org.junit.Assert.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.ElementNotVisibleException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
/**
*
* @author eduardo.lana
*/
public class BasePage {
protected void acao(By Element) {
DriverFactory.GetDriver().findElement(Element).click();
}
protected void checked(By Element) {
if(!DriverFactory.GetDriver().findElement(Element).isSelected()){
DriverFactory.GetDriver().findElement(Element).click();
}
}
protected void SelecionaGridComercial(By Element) {
try {
DriverFactory.GetDriver().findElement(Element).click();
} catch (NoSuchElementException a) {
System.out.println("Nao existe abrangencia comercial cadastrada para esse codigo de venda ");
throw a;
}
}
protected void SelecionaGrid(By Element, String acao, String teste) {
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date today = Calendar.getInstance().getTime();
String logDate = df.format(today);
try {
DriverFactory.GetDriver().findElement(Element).click();
} catch (NoSuchElementException a) {
System.out.println("Nao existe registro para " + acao);
throw a;
}
}
protected void Escrever(By Element, String Text) {
DriverFactory.GetDriver().findElement(Element).sendKeys(Text);
}
protected void SelectValue(By Element, String Text) {
new Select(DriverFactory.GetDriver().findElement(Element)).selectByValue(Text);
}
protected void Status(By Element) {
DriverFactory.GetDriver().findElement(Element).click();
}
protected String ObterTexto(By Element) {
return DriverFactory.GetDriver().findElement(Element).getText();
}
protected void ValidaMensagemPopup(By Element, By Element1, String Texto1, String teste) {
Date logDate = new Date();
String result;
try {
String mensagem = DriverFactory.GetDriver().findElement(Element1).getText();
result = logDate + " - " + teste + ": " + mensagem;
assertEquals(mensagem, Texto1);
} catch (NoSuchElementException a) {
String mensagem = DriverFactory.GetDriver().findElement(Element).getText();
result = logDate + " - " + teste + ": " + mensagem;
assertEquals(mensagem, Texto1);
}
}
protected void ValidaMensagemPopupComercial(By Element, By Element1, String Texto1, String teste) {
Date logDate = new Date();
String result;
try {
String mensagem = DriverFactory.GetDriver().findElement(Element).getText();
result = logDate + " - " + teste + ": " + mensagem;
assertEquals(mensagem, Texto1);
} catch (NoSuchElementException a) {
String mensagem = DriverFactory.GetDriver().findElement(Element1).getText();
result = logDate + " - " + teste + ": " + mensagem;
assertEquals(mensagem, Texto1);
}
}
protected void EsperaCarregamento(By Element) {
WebDriverWait wait = new WebDriverWait(DriverFactory.GetDriver(), 60);
wait.until(ExpectedConditions.visibilityOfElementLocated((Element)));
}
protected String ObtemCiclo(By Element) {
try {
return DriverFactory.GetDriver().findElement(Element).getText();
}catch(Exception e) {
return "";
}
}
protected String ObtemCicloComercial(By Element) {
try {
String valor = DriverFactory.GetDriver().findElement(Element).getAttribute("value");
return valor;
}catch(Exception e) {
return "";
}
}
protected String resultado(By Element) {
try {
return DriverFactory.GetDriver().findElement(Element).getText();
}catch(Exception e) {
return "";
}
}
}
| [
"[email protected]"
]
| |
78b8035dba3444c2813226b2b23c7f91f544d8b6 | f55f916fc3dd5736d5e37f9d2a8e4220c9ad3e48 | /toorder/src/com/zykj/toorder/activity/SuppliersUnRsponseActivity.java | 7c612b07330076750b1ca950ec42618ab166f1be | []
| no_license | WorkRoom/toorder | ce453c6b98ff7496d7db73ffaf5879f16dc36de9 | cd56438189f4facad7e18fcb94d8cf92a07880af | refs/heads/master | 2020-06-01T07:36:03.438375 | 2015-11-09T09:14:24 | 2015-11-09T09:14:24 | 42,768,815 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,626 | java | package com.zykj.toorder.activity;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import com.zykj.toorder.BaseActivity;
import com.zykj.toorder.R;
import com.zykj.toorder.adapter.CommonAdapter;
import com.zykj.toorder.adapter.ViewHolder;
import com.zykj.toorder.model.Supplier;
import com.zykj.toorder.utils.StringUtil;
import com.zykj.toorder.view.MyCommonTitle;
import com.zykj.toorder.view.XListView;
import com.zykj.toorder.view.XListView.IXListViewListener;
public class SuppliersUnRsponseActivity extends BaseActivity implements IXListViewListener,OnItemClickListener{
private static int PERPAGE = 10;// //perpage默认每页显示10条信息
private int nowpage = 1;// 当前显示的页面
private MyCommonTitle myCommonTitle;
private XListView mListView;
private CommonAdapter<Supplier> suppIntradeAdapter;
private List<Supplier> suppliers = new ArrayList<Supplier>();
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ui_supplier_in_trade);
mHandler = new Handler();
initView();
}
private void initView() {
myCommonTitle = (MyCommonTitle) findViewById(R.id.aci_mytitle);
myCommonTitle.setLisener(this, null, null);
myCommonTitle.setTag("未响应的");
myCommonTitle.setBackEditTitle("供应商");
mListView = (XListView) findViewById(R.id.list_supplier_in_trade);
mListView.setDividerHeight(0);
mListView.setPullRefreshEnable(true);
mListView.setPullLoadEnable(true);
mListView.setXListViewListener(this);
suppIntradeAdapter = new CommonAdapter<Supplier>(
SuppliersUnRsponseActivity.this,
R.layout.ui_item_suppliers_intrade, getTestData()) {
@Override
public void convert(ViewHolder holder, Supplier supplier) {
holder.setText(R.id.supplier_intrade_title,
StringUtil.toString(supplier.getName())).setText(
R.id.supplier_intrade_content,
StringUtil.toString(supplier.getIntro()));
}
};
mListView.setAdapter(suppIntradeAdapter);
mListView.setOnItemClickListener(SuppliersUnRsponseActivity.this);
suppIntradeAdapter.notifyDataSetChanged();
}
/**
* 测试数据
*
* @return
*/
private List<Supplier> getTestData() {
Supplier supplier1 = new Supplier();
supplier1.setName("供应商1");
supplier1.setIntro("简介消息简介消息简介消息简介消息简介消息简介消息");
suppliers.add(supplier1);
Supplier supplier2 = new Supplier();
supplier2.setName("供应商2");
supplier2.setIntro("简介消息简介消息简介消息简介消息简介消息简介消息");
suppliers.add(supplier2);
Supplier supplier3 = new Supplier();
supplier3.setName("供应商3");
supplier3.setIntro("简介消息简介消息简介消息简介消息简介消息简介消息");
suppliers.add(supplier3);
return suppliers;
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
}
@Override
public void onRefresh() {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
nowpage = 1;
// requestData();
onLoad();
}
}, 1000);
}
@Override
public void onLoadMore() {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
nowpage += 1;
// requestData();
onLoad();
}
}, 1000);
}
private void onLoad() {
mListView.stopRefresh();
mListView.stopLoadMore();
mListView.setRefreshTime("刚刚");
}
}
| [
"[email protected]"
]
| |
dd0aa434552b87d3114e4fdab82978804b417336 | e2010e9c549ca447270a871cfa071f4638ad254a | /src/MemberShipDAOlib/MemberShipDAO.java | 6c2484119e22f299b8c55a94d775942720eb288e | []
| no_license | EldrickMindcastle/MemberShipDAO | c161b4a33f665327e1e33807ddfeff5577599363 | b4e7824add3fb9ea8174bf0a1992d2db7c306f28 | refs/heads/master | 2021-01-19T08:15:05.170988 | 2015-10-01T03:02:13 | 2015-10-01T03:14:43 | 41,642,045 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 341 | java | package MemberShipDAOlib;
public interface MemberShipDAO {
public void add(Member member);
public void update(Member member);
public Member FindByAcc(String member_acc);
public boolean Login(String member_acc,String member_pw) ;
public void resetpw(String member_acc);
public boolean reg_confirm(String member_acc,Integer tmp_pw);
}
| [
"[email protected]"
]
| |
078e41a71ce270baceb94f28363e2ccb25accb56 | ef986cf7dc5bad66495227dd6179af475e919597 | /2016_0112Homework_제어문정리문제/src/HW10_1부터100_3의배수합_출력_dowhile.java | f91d2615117e58fc5000a456724e067095327982 | []
| no_license | yjs9918/sistStudy_java | 4509fc61a4088a92a71079ab0d7b93631368a4f4 | c0c8f7def4851189804c82150798ccf93172fed0 | refs/heads/master | 2021-01-10T01:09:47.193672 | 2016-03-10T07:22:37 | 2016-03-10T07:22:37 | 53,563,909 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 856 | java | /*
* 초기값 => 1
* do
* {
* 문장 => 2
* 증가식 => 3
* }while(조건식); ==> 4 => true:문장, false:종료
*/
public class HW10_1부터100_3의배수합_출력_dowhile {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a=0;//3의 배수를 누적하는 변수
for(int i=1;i<=100;i++)
{
if(i%3==0)
{
System.out.print(i+" ");
a+=i;
}
}
System.out.println("\n3의 배수 합:"+a);
a=0;
int i=1;
do
{
if(i%3==0)
{
System.out.print(i+" ");
a+=i;
}
i++;
}while(i<=100);
System.out.println("\n3의 배수 합:"+a);
a=0;
i=1;
while(i<=100)
{
if(i%3==0)
{
System.out.print(i+" ");
a+=i;
}
i++;
}
System.out.println("\n3의 배수 합:"+a);
}
}
| [
"[email protected]"
]
| |
b40a1c9f50a8bba42940909d4f0699dfe057cfc6 | 343d1e3d8be89894f1c8fe91d32a50171d90981a | /src/main/java/com/example/devcon/controller/AuthController.java | 3380c36c228e7ad34f44ce6658ee356836a15b64 | []
| no_license | yhs97/dev-con | bc6c3369c798fcc9be43313c09abbbe5fbd690fe | a2fdace50826f8d3a797504e34cc9f429ac1d533 | refs/heads/main | 2023-03-01T19:10:54.545387 | 2021-02-06T05:14:20 | 2021-02-06T05:14:20 | 329,609,154 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 858 | java | package com.example.devcon.controller;
import com.example.devcon.dto.RegisterRequest;
import com.example.devcon.service.AuthService;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static org.springframework.http.HttpStatus.OK;
@RestController
@RequestMapping("/api/auth")
@AllArgsConstructor
public class AuthController {
private final AuthService authService;
@PostMapping("/signup")
public ResponseEntity signup(@RequestBody RegisterRequest registerRequest){
authService.signUp(registerRequest);
return new ResponseEntity(OK);
}
}
| [
"[email protected]"
]
| |
b8de31695d12c56265f6cff8b38a42de9a8985cb | 22b66682306e6c5a7c3caa40204eefd198834e4b | /BookSearch/app/src/main/java/com/example/ashleighwilson/booksearch/views/HorizontalOverlayLayout/line/LineViewHolder.java | 524b600a95cfc0e4d2baccab4833730d4ed420f1 | []
| no_license | NaturallyAsh/BookSearch | f027dc31821765ec51bea882196b8ce8a717f8c3 | 9baf0007bc9da80ff77a9ba68462baa5ff24af2a | refs/heads/master | 2022-07-17T13:00:03.723130 | 2022-07-01T22:13:45 | 2022-07-01T22:13:45 | 140,329,502 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,619 | java | package com.example.ashleighwilson.booksearch.views.HorizontalOverlayLayout.line;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.ashleighwilson.booksearch.R;
import com.example.ashleighwilson.booksearch.views.HorizontalOverlayLayout.MaterialLeanBack;
import com.example.ashleighwilson.booksearch.views.HorizontalOverlayLayout.MaterialLeanBackSettings;
import com.example.ashleighwilson.booksearch.views.HorizontalOverlayLayout.OnItemClickListenerWrapper;
import com.example.ashleighwilson.booksearch.views.HorizontalOverlayLayout.cell.CellAdapter;
import com.example.ashleighwilson.booksearch.views.HorizontalOverlayLayout.cell.CellViewHolder;
import com.example.ashleighwilson.booksearch.views.RecyclerLayout.MultiRecyclerAttrs;
import com.example.ashleighwilson.booksearch.views.RecyclerLayout.MultiRecyclerLayout;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class LineViewHolder extends RecyclerView.ViewHolder{
protected final MultiRecyclerAttrs settings;
protected final RecyclerView recyclerView;
protected final MultiRecyclerLayout.MultiAdapter adapter;
protected final MultiRecyclerLayout.Customizer customizer;
protected ViewGroup layout;
protected TextView title;
protected TextView author;
protected OnItemClickListenerWrapper onItemClickListenerWrapper;
protected int row;
protected boolean wrapped = false;
public LineViewHolder(View itemView, @NonNull MultiRecyclerLayout.MultiAdapter adapter, @NonNull MultiRecyclerAttrs settings,
final MultiRecyclerLayout.Customizer customizer, final OnItemClickListenerWrapper onItemClickListenerWrapper) {
super(itemView);
this.adapter = adapter;
this.settings = settings;
this.customizer = customizer;
this.onItemClickListenerWrapper = onItemClickListenerWrapper;
layout = (ViewGroup) itemView.findViewById(R.id.row_layout);
title = (TextView) itemView.findViewById(R.id.row_title);
author = itemView.findViewById(R.id.row_author);
recyclerView = (RecyclerView) itemView.findViewById(R.id.row_recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(itemView.getContext(), LinearLayoutManager.HORIZONTAL, false));
recyclerView.setHasFixedSize(true);
}
public RecyclerView getRecyclerView() {
return recyclerView;
}
public void onBind(final int row) {
this.row = row;
{
final String titleString = adapter.getTitleForRow(this.row);
if (!adapter.hasRowTitle(row) || (titleString == null || titleString.trim().isEmpty()))
title.setVisibility(View.GONE);
else
title.setText(titleString);
title.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (onItemClickListenerWrapper != null) {
final MultiRecyclerLayout.OnItemClickListener onItemClickListener = onItemClickListenerWrapper.getOnItemClickListener();
if (onItemClickListener != null) {
onItemClickListener.onTitleClicked(row, titleString);
}
}
}
});
if (settings.titleColor != null)
title.setTextColor(settings.titleColor);
if (settings.titleSize != -1)
title.setTextSize(settings.titleSize);
if (this.customizer != null)
customizer.customizeTitle(title);
}
{
if (settings.lineSpacing != null) {
layout.setPadding(
layout.getPaddingLeft(),
layout.getPaddingTop(),
layout.getPaddingRight(),
settings.lineSpacing
);
}
}
recyclerView.setAdapter(new CellAdapter(row, adapter, settings, onItemClickListenerWrapper, new CellAdapter.HeightCalculatedCallback() {
@Override
public void onHeightCalculated(int height) {
if (!wrapped) {
//recyclerView.getLayoutParams().height = height;
//recyclerView.requestLayout();
//wrapped = true;
}
}
}));
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
adapter.getEnlargedItemPosition(adapter.itemPosition);
}
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
for (int i = 0; i < recyclerView.getChildCount(); ++i) {
RecyclerView.ViewHolder viewHolder = recyclerView.getChildViewHolder(recyclerView.getChildAt(i));
if (viewHolder instanceof CellViewHolder) {
CellViewHolder cellViewHolder = ((CellViewHolder) viewHolder);
cellViewHolder.newPosition(i);
}
}
}
});
}
}
| [
"[email protected]"
]
| |
d1f87e1cd250010f054f98bb15c0092aa5976b28 | 7fde95bf8491b0bc1906a30a3b4e7a1e202fa734 | /maven_webmail/src/main/java/cse/maven_webmail/model/FormParser.java | 522f9754dc48f66ce713e5976ae14684c76b6233 | [
"MIT"
]
| permissive | JeongEunBae/Web-Mail-System-MaintenanceProject | ea0b87e7056d2c019e539e9ccb18e117a16318de | a3af364459ade94909c5de67aa6d553b89f37cf8 | refs/heads/main | 2023-05-26T14:44:26.150423 | 2021-06-05T09:11:59 | 2021-06-05T09:11:59 | 364,337,968 | 0 | 0 | MIT | 2021-06-05T11:08:09 | 2021-05-04T17:40:47 | Java | UTF-8 | Java | false | false | 4,653 | java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package cse.maven_webmail.model;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* 책임: enctype이 multipart/form-data인 HTML 폼에 있는 각 필드와 파일 정보 추출
*
* @author jongmin
*/
public class FormParser {
private HttpServletRequest request;
private String toAddress = null;
private String ccAddress = null;
private String subject = null;
private String body = null;
private String fileName = null;
private String uploadTargetDir = "C:/temp/upload";
Log log = LogFactory.getLog(FormParser.class);
public FormParser(HttpServletRequest request) {
this.request = request;
if (System.getProperty("os.name").equals("Linux")) {
uploadTargetDir = request.getServletContext().getRealPath("/WEB-INF")
+ File.separator + "upload";
File f = new File(uploadTargetDir);
if (!f.exists()) {
f.mkdir();
}
}
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getCcAddress() {
return ccAddress;
}
public void setCcAddress(String ccAddress) {
this.ccAddress = ccAddress;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getToAddress() {
return toAddress;
}
public void setToAddress(String toAddress) {
this.toAddress = toAddress;
}
public void parse() {
try {
request.setCharacterEncoding("UTF-8");
// 1. 디스크 기반 파일 항목에 대한 팩토리 생성
DiskFileItemFactory diskFactory = new DiskFileItemFactory();
// 2. 팩토리 제한사항 설정
diskFactory.setSizeThreshold(10 * 1024 * 1024);
diskFactory.setRepository(new File(this.uploadTargetDir));
// 3. 파일 업로드 핸들러 생성
ServletFileUpload upload = new ServletFileUpload(diskFactory);
// 4. request 객체 파싱
List<?> fileItems = upload.parseRequest(request); // S3740
Iterator<?> i = fileItems.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (fi.isFormField()) { // 5. 폼 필드 처리
String fieldName = fi.getFieldName();
String item = fi.getString("UTF-8");
if (fieldName.equals("to")) {
setToAddress(item); // 200102 LJM - @ 이후의 서버 주소 제거
} else if (fieldName.equals("cc")) {
setCcAddress(item);
} else if (fieldName.equals("subj")) {
setSubject(item);
} else if (fieldName.equals("body")) {
setBody(item);
}
} else { // 6. 첨부 파일 처리
if (!(fi.getName() == null || fi.getName().equals(""))) {
String fieldName = fi.getFieldName();
log.info("ATTACHED FILE : " + fieldName + " = " + fi.getName()); //S106
// 절대 경로 저장
setFileName(uploadTargetDir + "/" + fi.getName());
File fn = new File(fileName);
// upload 완료. 추후 메일 전송후 해당 파일을 삭제하도록 해야 함.
if (fileName != null) {
fi.write(fn);
}
}
}
}
} catch (Exception ex) {
log.error("FormParser.parse() : exception = " + ex); //S106
}
} // parse()
}
| [
"[email protected]"
]
| |
f0e8e284e0c56522b97b9546afd20522b3393aa6 | 2ce7793e334c0afeba0ca30743b3823ab36e7fb9 | /labv-demo/src/main/java/br/edu/uscs/labv/controller/CadastroPessoaController.java | e9e056f109ce2b78e1bac72071282705dd9d9376 | []
| no_license | petersonlarentis/uscs | 7082045300e8b552b36521fcb1c4edc0833e5451 | 48f3dcb265d7d831eefdfa71b8d4265de1b6ff95 | refs/heads/master | 2021-01-19T03:23:24.986180 | 2014-01-23T13:02:42 | 2014-01-23T13:13:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,161 | java | package br.edu.uscs.labv.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import br.edu.uscs.labv.domain.Pessoa;
import br.edu.uscs.labv.service.CadastroService;
import br.edu.uscs.labv.service.CadastroServiceImpl;
@WebServlet("/cadastroPessoa")
public class CadastroPessoaController extends HttpServlet {
private static final long serialVersionUID = 1L;
private CadastroService cadastroService;
public CadastroPessoaController() {
cadastroService = new CadastroServiceImpl();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Pessoa pessoa = createPessoa(request);
cadastroService.cadastrar(pessoa);
}
private Pessoa createPessoa(HttpServletRequest request) {
// TODO: 1 - obter os dados do request ( nome e idade ) e criar um objeto Pessoa com esses dados.
return null;
}
}
| [
"[email protected]"
]
| |
2439367d27c282151c88b04df4d1ec2e9205cb82 | b9eacde1d41511aff4edf1be7d75969b6fd90c06 | /chapter_001/src/main/java/ru/job4j/array/Turn.java | b2c30d0cf8624d4a030e7613fb220537dfe1aabd | [
"Apache-2.0"
]
| permissive | Mrsananabos/ashveytser | c8f6a30681ef7bf3e802b14d43d9c8e2e5da0517 | 4d209768e9bd01f77334ebf45cca06b648997840 | refs/heads/master | 2021-01-02T09:30:11.925069 | 2019-05-20T07:52:46 | 2019-05-20T07:52:46 | 99,225,036 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 435 | java | package ru.job4j.array;
import com.sun.prism.shader.Solid_TextureYV12_AlphaTest_Loader;
import java.util.Arrays;
public class Turn {
public int[] back(int[] array) {
int length = array.length;
for (int i = array.length - 1; i >= (length / 2); i--) {
int num = array[i];
array[i] = array[length - i - 1];
array[length - i - 1] = num;
}
return array;
}
}
| [
"[email protected]"
]
| |
157a94a76435eca5521d55997987a40b4546bd90 | c6a499fee83fd842ba48bf31378224419fc5a398 | /src/test/java/com/thoughtworks/training/kmj/JwtTest.java | 3a1c3dc864990673cb1797e3fe2c071cefb3d9ef | []
| no_license | koumiaozi/todo-service-with_flyway | 1aad03897aedd367edc1de24be113651843f906a | 6441016be7ea3b3b14f3fdc65ea4630cf292b3e8 | refs/heads/master | 2020-03-25T01:36:15.485709 | 2018-08-05T10:24:06 | 2018-08-05T10:24:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,159 | java | package com.thoughtworks.training.kmj;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class JwtTest {
private Map<String,Object> claims;
@Test
public void generateJwt() {
HashMap<String,Object> claims = new HashMap<>();
claims.put("name","hahha");
claims.put("role","dev");
byte[] secretKey = "kitty".getBytes();
//generate
String token = Jwts.builder()
.addClaims(claims)
// .setExpiration(Date.from(Instant.now().minus(1,ChronoUnit.DAYS)))
.signWith(SignatureAlgorithm.HS512,secretKey)
.compact();
//Parse & Verification
Claims body = Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.getBody();
assertThat(body.get("name"),is("hahha"));
assertThat(body.get("role"),is("dev"));
System.out.println(body);
}
}
| [
"[email protected]"
]
| |
16c0d20306c6e752c4e2d5e874d4d8407811b555 | 8e4f8a4a130157ac7f65577a3c9a7825738e9a7c | /src/com/xueya/tools/ZoomControlView.java | 09597e6adbb200f04977f6922eed8f3a3351a8a0 | []
| no_license | Liguhaha/PalmBus | 53434eee77a1a44d01e572f96208792ada141f81 | 1409a24150aeaa1be163fe96eb9006aa0bc5ffbd | refs/heads/master | 2020-05-20T08:59:15.070096 | 2015-07-04T14:25:34 | 2015-07-04T14:25:34 | 38,536,345 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,828 | java | package com.xueya.tools;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.xueya.palmbus.R;
public class ZoomControlView extends RelativeLayout implements OnClickListener {
private ImageView mImageViewZoomin;
private ImageView mImageViewZoomout;
private MapView mapView;
private float maxZoomLevel;
private float minZoomLevel;
public ZoomControlView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ZoomControlView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
@SuppressLint("InflateParams") private void init() {
View view = LayoutInflater.from(getContext()).inflate(
R.layout.zoom_controls_layout, null);
mImageViewZoomin = (ImageView) view.findViewById(R.id.zoomin);
mImageViewZoomout = (ImageView) view.findViewById(R.id.zoomout);
mImageViewZoomin.setOnClickListener(this);
mImageViewZoomout.setOnClickListener(this);
addView(view);
}
@Override
public void onClick(View v) {
if (mapView == null) {
throw new NullPointerException(
"you can call setMapView(MapView mapView) at first");
}
switch (v.getId()) {
case R.id.zoomin: {
MapStatusUpdate msu = MapStatusUpdateFactory.zoomIn();
mapView.getMap().setMapStatus(msu);
break;
}
case R.id.zoomout: {
MapStatusUpdate msu = MapStatusUpdateFactory.zoomOut();
mapView.getMap().setMapStatus(msu);
break;
}
}
}
/**
* 与MapView设置关联
*
* @param mapView
*/
public void setMapView(MapView mapView) {
this.mapView = mapView;
// 获取最大的缩放级别
maxZoomLevel = mapView.getMap().getMaxZoomLevel();
// 获取最大的缩放级别
minZoomLevel = mapView.getMap().getMinZoomLevel();
}
/**
* 根据MapView的缩放级别更新缩放按钮的状态,当达到最大缩放级别,设置mButtonZoomin
* 为不能点击,反之设置mButtonZoomout
*
* @param level
*/
public void refreshZoomButtonStatus(Float level) {
if (level > minZoomLevel && level < maxZoomLevel) {
if (!mImageViewZoomout.isEnabled()) {
mImageViewZoomout.setEnabled(true);
}
if (!mImageViewZoomin.isEnabled()) {
mImageViewZoomin.setEnabled(true);
}
} else if (level == minZoomLevel) {
mImageViewZoomout.setEnabled(false);
} else if (level == maxZoomLevel) {
mImageViewZoomin.setEnabled(false);
}
}
}
| [
"Ligu@Ligu-PC"
]
| Ligu@Ligu-PC |
efc118df77e009ec043fc7a421bbc4741e0dd951 | ecfd92a79a791dcd0dce46619b0233d1aca7f40a | /library/src/main/java/com/afollestad/materialcamera/CaptureActivity.java | 4b6563c68ce142b1004747b9d9773646a18b19f1 | [
"Apache-2.0"
]
| permissive | fazalBykea/material-camera-master | 4ebb1c3e0049eb07d964de243f5e680a363dfc86 | 8074ad4eea0f13916fa8ccac115b42ed2dca63a4 | refs/heads/master | 2020-04-02T22:11:52.012298 | 2018-03-05T11:23:16 | 2018-03-05T11:23:16 | 154,824,798 | 0 | 0 | Apache-2.0 | 2018-10-26T11:34:51 | 2018-10-26T11:34:51 | null | UTF-8 | Java | false | false | 418 | java | package com.afollestad.materialcamera;
import android.app.Fragment;
import android.support.annotation.NonNull;
import com.afollestad.materialcamera.internal.BaseCaptureActivity;
import com.afollestad.materialcamera.internal.CameraFragment;
public class CaptureActivity extends BaseCaptureActivity {
@Override
@NonNull
public Fragment getFragment() {
return CameraFragment.newInstance();
}
} | [
"[email protected]"
]
| |
7994bac787fad8a2b323ea03b442d5aa5aa2641c | d828e7483f75a380c33ea1a9f5d81f9a2a5681fe | /core/src/main/java/io/snappydata/util/com/clearspring/analytics/stream/frequency/IFrequency.java | 4e13338c1d91f2a1221d5290183fc9a82162fdce | [
"OFL-1.1",
"MPL-1.1",
"BSD-3-Clause",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-mx4j",
"LGPL-2.0-or-later",
"OpenSSL",
"LGPL-2.1-only",
"FSFAP",
"LicenseRef-scancode-other-permissive",
"LGPL-2.1-or-later",
"WTFPL",
"GCC-exception-3.1",
"PostgreSQL",
"Zlib",
"EPL-2.0",
"CDDL-1.0",
"EPL-1.0",
"Classpath-exception-2.0",
"MIT",
"CC0-1.0",
"Apache-1.1",
"MPL-1.0",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-warranty-disclaimer",
"MIT-0",
"CDDL-1.1",
"GPL-1.0-or-later",
"GPL-2.0-only",
"Minpack",
"BSD-2-Clause-Views",
"Apache-2.0",
"MPL-2.0",
"LGPL-2.0-only",
"CC-PDDC",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-protobuf",
"CPL-1.0",
"Plexus",
"LicenseRef-scancode-generic-cla",
"JSON"
]
| permissive | wiltonlazary/snappydata | 025dfada00a0d8331389fc37af1a7199ad443bbe | ade39e6fb846101e43f85cedcb6721cacfe531c1 | refs/heads/master | 2020-04-27T16:06:21.885336 | 2020-03-01T16:20:57 | 2020-03-01T16:20:57 | 174,472,682 | 0 | 0 | Apache-2.0 | 2020-03-01T16:20:59 | 2019-03-08T05:06:54 | Scala | UTF-8 | Java | false | false | 274 | java | package io.snappydata.util.com.clearspring.analytics.stream.frequency;
public interface IFrequency {
void add(long item, long count);
void add(String item, long count);
long estimateCount(long item);
long estimateCount(String item);
long size();
}
| [
"[email protected]"
]
| |
7a30bd4f46ffc7e35d5b6f48f8ef34c4aab10740 | 2a1e2968f4b9affd20b5121518139f777e6337b7 | /android/app/src/main/java/com/sentientmobile/MainApplication.java | 21ac23881ae93a61a80cf18e045b74c765bee362 | []
| no_license | consensus-ai/SentientMobile | 8b2c2093e25015bde95bbe3a4c8ea1310914b235 | b60a346253d5ba80d14bb06880908f46b0c5007f | refs/heads/master | 2020-04-27T00:11:47.767263 | 2019-03-05T10:39:23 | 2019-03-05T10:39:23 | 173,926,777 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,249 | java | package com.sentientmobile;
import android.app.Application;
import com.facebook.react.ReactApplication;
import com.oblador.vectoricons.VectorIconsPackage;
import com.swmansion.gesturehandler.react.RNGestureHandlerPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import java.util.Arrays;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new VectorIconsPackage(),
new RNGestureHandlerPackage()
);
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}
| [
"[email protected]"
]
| |
4d0045e2044f4abef6f87d706a009270783aa8a2 | 46c1dcc487192b8516222a0cc0f808620987b919 | /src/tw/com/pm/xml/domain/MyRootElement.java | 9c94f3fce9f8546c527534b8d067d35afa07ff7e | []
| no_license | 595money/Genesis | 353dc6690de17516a5817d8adc15494f4cc1931b | 5360e35f75f84c005970ff878f7230d838e5cce9 | refs/heads/master | 2020-05-03T10:38:19.383642 | 2019-04-20T01:21:48 | 2019-04-20T01:21:48 | 178,584,134 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 814 | java | package tw.com.pm.xml.domain;
import java.lang.reflect.Field;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "beans")
public class MyRootElement {
List<Bean> beans;
@XmlElement(name = "bean")
public List<Bean> getBeans() {
return beans;
}
public void setBeans(List<Bean> beans) {
this.beans = beans;
}
public String toString() {
Field[] fields = this.getClass().getDeclaredFields();
String res = "";
try {
for (Field field : fields) {
res += field.getName() + ":\n" + field.get(this);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return res;
}
}
| [
"[email protected]"
]
| |
9caca2dba20ad041c1ee0dfd6131250f20fdfebb | 1f902e98de99596e36ba017ce3907828b99a3c1f | /services/core/java/com/android/server/health/HealthServiceWrapperHidl.java | 0301174a45c6f48f7b953454a02f2be17095cf9d | [
"LicenseRef-scancode-unicode",
"Apache-2.0"
]
| permissive | aosp-mirror/platform_frameworks_base | c98112233373c83586fb1bf4d7ac256e5521b11d | 942d47b019852409865ee53a189b09cc0743dff1 | refs/heads/main | 2023-08-29T10:34:14.756209 | 2023-08-29T07:02:44 | 2023-08-29T07:02:44 | 65,885 | 4,479 | 2,590 | NOASSERTION | 2023-08-08T07:25:50 | 2008-10-21T18:20:37 | Java | UTF-8 | Java | false | false | 13,093 | java | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server.health;
import static android.hardware.health.Translate.h2aTranslate;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.hardware.health.HealthInfo;
import android.hardware.health.V2_0.IHealth;
import android.hardware.health.V2_0.Result;
import android.hidl.manager.V1_0.IServiceManager;
import android.hidl.manager.V1_0.IServiceNotification;
import android.os.BatteryManager;
import android.os.BatteryProperty;
import android.os.HandlerThread;
import android.os.RemoteException;
import android.os.Trace;
import android.util.MutableInt;
import android.util.Slog;
import com.android.internal.annotations.VisibleForTesting;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
/**
* Implement {@link HealthServiceWrapper} backed by the HIDL HAL.
*
* @hide
*/
final class HealthServiceWrapperHidl extends HealthServiceWrapper {
private static final String TAG = "HealthServiceWrapperHidl";
public static final String INSTANCE_VENDOR = "default";
private final IServiceNotification mNotification = new Notification();
private final HandlerThread mHandlerThread = new HandlerThread("HealthServiceHwbinder");
// These variables are fixed after init.
private Callback mCallback;
private IHealthSupplier mHealthSupplier;
private String mInstanceName;
// Last IHealth service received.
private final AtomicReference<IHealth> mLastService = new AtomicReference<>();
private static void traceBegin(String name) {
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, name);
}
private static void traceEnd() {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
@Override
public int getProperty(int id, final BatteryProperty prop) throws RemoteException {
traceBegin("HealthGetProperty");
try {
IHealth service = mLastService.get();
if (service == null) throw new RemoteException("no health service");
final MutableInt outResult = new MutableInt(Result.NOT_SUPPORTED);
switch (id) {
case BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER:
service.getChargeCounter(
(int result, int value) -> {
outResult.value = result;
if (result == Result.SUCCESS) prop.setLong(value);
});
break;
case BatteryManager.BATTERY_PROPERTY_CURRENT_NOW:
service.getCurrentNow(
(int result, int value) -> {
outResult.value = result;
if (result == Result.SUCCESS) prop.setLong(value);
});
break;
case BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE:
service.getCurrentAverage(
(int result, int value) -> {
outResult.value = result;
if (result == Result.SUCCESS) prop.setLong(value);
});
break;
case BatteryManager.BATTERY_PROPERTY_CAPACITY:
service.getCapacity(
(int result, int value) -> {
outResult.value = result;
if (result == Result.SUCCESS) prop.setLong(value);
});
break;
case BatteryManager.BATTERY_PROPERTY_STATUS:
service.getChargeStatus(
(int result, int value) -> {
outResult.value = result;
if (result == Result.SUCCESS) prop.setLong(value);
});
break;
case BatteryManager.BATTERY_PROPERTY_ENERGY_COUNTER:
service.getEnergyCounter(
(int result, long value) -> {
outResult.value = result;
if (result == Result.SUCCESS) prop.setLong(value);
});
break;
}
return outResult.value;
} finally {
traceEnd();
}
}
@Override
public void scheduleUpdate() throws RemoteException {
getHandlerThread()
.getThreadHandler()
.post(
() -> {
traceBegin("HealthScheduleUpdate");
try {
IHealth service = mLastService.get();
if (service == null) {
Slog.e(TAG, "no health service");
return;
}
service.update();
} catch (RemoteException ex) {
Slog.e(TAG, "Cannot call update on health HAL", ex);
} finally {
traceEnd();
}
});
}
private static class Mutable<T> {
public T value;
}
@Override
public HealthInfo getHealthInfo() throws RemoteException {
IHealth service = mLastService.get();
if (service == null) return null;
final Mutable<HealthInfo> ret = new Mutable<>();
service.getHealthInfo(
(result, value) -> {
if (result == Result.SUCCESS) {
ret.value = h2aTranslate(value.legacy);
}
});
return ret.value;
}
/**
* Start monitoring registration of new IHealth services. Only instance {@link #INSTANCE_VENDOR}
* and in device / framework manifest are used. This function should only be called once.
*
* <p>mCallback.onRegistration() is called synchronously (aka in init thread) before this method
* returns if callback is not null.
*
* @throws RemoteException transaction error when talking to IServiceManager
* @throws NoSuchElementException if one of the following cases: - No service manager; - {@link
* #INSTANCE_VENDOR} is not in manifests (i.e. not available on this device), or none of
* these instances are available to current process.
* @throws NullPointerException when supplier is null
*/
@VisibleForTesting
HealthServiceWrapperHidl(
@Nullable Callback callback,
@NonNull IServiceManagerSupplier managerSupplier,
@NonNull IHealthSupplier healthSupplier)
throws RemoteException, NoSuchElementException, NullPointerException {
if (managerSupplier == null || healthSupplier == null) {
throw new NullPointerException();
}
mHealthSupplier = healthSupplier;
// Initialize mLastService and call callback for the first time (in init thread)
IHealth newService = null;
traceBegin("HealthInitGetService_" + INSTANCE_VENDOR);
try {
newService = healthSupplier.get(INSTANCE_VENDOR);
} catch (NoSuchElementException ex) {
/* ignored, handled below */
} finally {
traceEnd();
}
if (newService != null) {
mInstanceName = INSTANCE_VENDOR;
mLastService.set(newService);
}
if (mInstanceName == null || newService == null) {
throw new NoSuchElementException(
String.format(
"IHealth service instance %s isn't available. Perhaps no permission?",
INSTANCE_VENDOR));
}
if (callback != null) {
mCallback = callback;
mCallback.onRegistration(null, newService, mInstanceName);
}
// Register for future service registrations
traceBegin("HealthInitRegisterNotification");
mHandlerThread.start();
try {
managerSupplier
.get()
.registerForNotifications(IHealth.kInterfaceName, mInstanceName, mNotification);
} finally {
traceEnd();
}
Slog.i(TAG, "health: HealthServiceWrapper listening to instance " + mInstanceName);
}
@VisibleForTesting
public HandlerThread getHandlerThread() {
return mHandlerThread;
}
/** Service registration callback. */
interface Callback {
/**
* This function is invoked asynchronously when a new and related IServiceNotification is
* received.
*
* @param service the recently retrieved service from IServiceManager. Can be a dead service
* before service notification of a new service is delivered. Implementation must handle
* cases for {@link RemoteException}s when calling into service.
* @param instance instance name.
*/
void onRegistration(IHealth oldService, IHealth newService, String instance);
}
/**
* Supplier of services. Must not return null; throw {@link NoSuchElementException} if a service
* is not available.
*/
interface IServiceManagerSupplier {
default IServiceManager get() throws NoSuchElementException, RemoteException {
return IServiceManager.getService();
}
}
/**
* Supplier of services. Must not return null; throw {@link NoSuchElementException} if a service
* is not available.
*/
interface IHealthSupplier {
default IHealth get(String name) throws NoSuchElementException, RemoteException {
return IHealth.getService(name, true /* retry */);
}
}
private class Notification extends IServiceNotification.Stub {
@Override
public final void onRegistration(
String interfaceName, String instanceName, boolean preexisting) {
if (!IHealth.kInterfaceName.equals(interfaceName)) return;
if (!mInstanceName.equals(instanceName)) return;
// This runnable only runs on mHandlerThread and ordering is ensured, hence
// no locking is needed inside the runnable.
mHandlerThread
.getThreadHandler()
.post(
new Runnable() {
@Override
public void run() {
try {
IHealth newService = mHealthSupplier.get(mInstanceName);
IHealth oldService = mLastService.getAndSet(newService);
// preexisting may be inaccurate (race). Check for equality
// here.
if (Objects.equals(newService, oldService)) return;
Slog.i(
TAG,
"health: new instance registered " + mInstanceName);
// #init() may be called with null callback. Skip null
// callbacks.
if (mCallback == null) return;
mCallback.onRegistration(
oldService, newService, mInstanceName);
} catch (NoSuchElementException | RemoteException ex) {
Slog.e(
TAG,
"health: Cannot get instance '"
+ mInstanceName
+ "': "
+ ex.getMessage()
+ ". Perhaps no permission?");
}
}
});
}
}
}
| [
"[email protected]"
]
| |
a0408f7267115e640c362004a8c183c1f1e3c97c | d4f37cd14fa6a7781d063a1b74150505a0baf28f | /src/com/sywood/starbucks/siyan/ccc/CCCSenior/CCC2016s3.java | 33d5f3b3a5a1b64219f75aa53ca2ca3f5c687462 | []
| no_license | siyan/starbucks | 251af5a1a199f701dcd2e50f4d0029c557b8d7b8 | 5355414fb434b837a60e68aa06001431c927ce09 | refs/heads/master | 2021-01-24T06:15:56.653694 | 2017-08-13T23:52:50 | 2017-08-13T23:52:50 | 40,939,930 | 5 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,127 | java | package com.sywood.starbucks.siyan.ccc.CCCSenior;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class CCC2016s3 {
static ArrayList<Integer>[] list;
public static void main(String[] args)throws Exception{
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
String[] data = input.readLine().split(" ");
int N = Integer.parseInt(data[0]);
int M = Integer.parseInt(data[1]);
int a,b;
ArrayList<Integer> restaurants = new ArrayList<>();
st = new StringTokenizer(input.readLine());
for (int i = 0; i < M; i++) {
restaurants.add(Integer.parseInt(st.nextToken()));
}
list = new ArrayList[N];
Arrays.fill(list, new ArrayList<Integer>());
for (int i = 0; i < N-1; i++) {
data = input.readLine().split(" ");
a = Integer.parseInt(data[0]);
b = Integer.parseInt(data[1]);
list[a].add(b);
}
}
}
| [
"[email protected]"
]
| |
d9ae4692f71244eae78e33fa9539bc50c71f6b31 | 4719fe5dca721d423c19fe89fa42b3739068d568 | /datavirt-commons-dev/src/main/java/org/jboss/datavirt/commons/dev/server/util/ArchiveUtils.java | 54212d25596e362a9c5cdf04214c5b202a534097 | []
| no_license | mdrillin/datavirt-commons | 01b2324b444cf82f270d822b08ae7230fb8969f8 | b962ef20a3e2744d07f44b06c6dddb9f1756505e | refs/heads/master | 2021-03-12T22:55:20.281666 | 2014-02-03T22:09:44 | 2014-02-03T22:09:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,512 | java | /*
* Copyright 2012 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.datavirt.commons.dev.server.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.commons.io.IOUtils;
/**
* Some general porpoise utils for working with archives.
*
* @author [email protected]
*/
public class ArchiveUtils {
/**
* Unpacks the given archive file into the output directory.
* @param archiveFile an archive file
* @param toDir where to unpack the archive to
* @throws IOException
*/
public static void unpackToWorkDir(File archiveFile, File toDir) throws IOException {
ZipFile zipFile = null;
try {
zipFile = new ZipFile(archiveFile);
Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntries();
while (zipEntries.hasMoreElements()) {
ZipArchiveEntry entry = zipEntries.nextElement();
String entryName = entry.getName();
File outFile = new File(toDir, entryName);
if (!outFile.getParentFile().exists()) {
if (!outFile.getParentFile().mkdirs()) {
throw new IOException("Failed to create parent directory: " + outFile.getParentFile().getCanonicalPath());
}
}
if (entry.isDirectory()) {
if (!outFile.mkdir()) {
throw new IOException("Failed to create directory: " + outFile.getCanonicalPath());
}
} else {
InputStream zipStream = null;
OutputStream outFileStream = null;
zipStream = zipFile.getInputStream(entry);
outFileStream = new FileOutputStream(outFile);
try {
IOUtils.copy(zipStream, outFileStream);
} finally {
IOUtils.closeQuietly(zipStream);
IOUtils.closeQuietly(outFileStream);
}
}
}
} finally {
ZipFile.closeQuietly(zipFile);
}
}
}
| [
"[email protected]"
]
| |
2875a3a77a853dfee14ac8d5628ef7bfd452013c | 846e794e965057624ecfe2cd4fafde1ea3c86dc4 | /src/view/ViewlClientes.java | cc189a8997392cea7a7f5bfac43acf5aa72fc0b8 | []
| no_license | JadsonFeitosa/Hot_Pizza | a7b244e7d13be083ace00fca14a4be43a94b89de | 4a7297b73ff85db61042431082811c51f1a77dcb | refs/heads/master | 2023-06-02T00:18:07.132194 | 2021-06-24T03:37:22 | 2021-06-24T03:37:22 | 379,784,181 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 3,991 | java | package view;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import controller.BotoesGeral;
import controller.ControlCliente;
public class ViewlClientes extends Principal {
/**
*
*/
private static final long serialVersionUID = -6100634636482570749L;
TableClientes tabela;
public ViewlClientes(String bot) {
setTitle("Lista de Clientes");
setBounds(400, 50, 700, 500);
setResizable(false);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
tabela(this);
botoes(bot);
barra();
setVisible(true);
repaint();
}
public void barra() {
JLabel barra = new JLabel();
barra.setOpaque(true);
barra.setBackground(Color.GRAY);
barra.setBounds(0, 10, 700, 120);
add(barra);
}
public void botoes(String bot) {
BotoesGeral cad = new BotoesGeral("Cadastrar",new ImageIcon("Icon/cadcli.png"), 10, 10, 100, 110);
add(cad);
cad.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String tela=e.getActionCommand();
dispose();
new TelaCadCliente(false,tela,0);
}
});
BotoesGeral editar = new BotoesGeral("Editar",new ImageIcon("Icon/editarcli.png"), 111, 10, 100, 110);
add(editar);
editar.setVisible(true);
editar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String tela=e.getActionCommand();
int linha1 =tabela.seletctID();
System.out.println(linha1);
dispose();
new TelaCadCliente(false,tela,linha1);
}catch (Exception d) {
}
}
});
BotoesGeral excluir = new BotoesGeral("Excluir",new ImageIcon("Icon/exlcuircli.png"), 212, 10, 100, 110);
add(excluir);
excluir.setVisible(true);
excluir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int linha1 =tabela.seletctID();
System.out.println(linha1);
if(linha1<0) {
JOptionPane.showMessageDialog(null, "Selecione a linha pra exclusão", "Aviso", JOptionPane.INFORMATION_MESSAGE); }
else {
ControlCliente.contExcluirClienteDelete(linha1);
tabela.excluirLinha(tabela.selectLinha());
JOptionPane.showMessageDialog(null, "Cliente excluido com sucesso !", "Aviso", JOptionPane.INFORMATION_MESSAGE);
}
}
});
BotoesGeral pes = new BotoesGeral("Pesquisar",new ImageIcon("Icon/peesquisacli.png"), 313, 10, 100, 110);
add(pes);
pes.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String n= JOptionPane.showInputDialog(null, "Digite o nome do pra pesquisa", "Pesquisar",
JOptionPane.INFORMATION_MESSAGE);
n=n.toUpperCase();
if (tabela.filtroNome(n)==false) {
JOptionPane.showMessageDialog(null, "Cliente não cadastrado", "Aviso", JOptionPane.INFORMATION_MESSAGE);
}
else
tabela.limparTabela();
tabela.filtroNome(n);
tabela.repaint();
}catch(NullPointerException k) {
}
}
});
BotoesGeral adic = new BotoesGeral("Adicionar",new ImageIcon("Icon/salvarcli.png"), 10, 10, 100, 110);
add(adic);
if(bot.equals("<html>Add Cliente<html>")) {
cad.setVisible(false);
editar.setVisible(false);
excluir.setVisible(false);
}
else
adic.setVisible(false
);
adic.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int linha=tabela.seletctID();
VIewPDV.recCliente(linha);
dispose();
}
});
}
public void tabela(JFrame janela) {
tabela = new TableClientes();
tabela.adicionarTabela(janela);
tabela.repaint();
janela.add(tabela);
}
public static void main(String[] args) {
new ViewlClientes("");
}
}
| [
"[email protected]"
]
| |
8e26baad836acd9bdab4fcb57fd6b4787b18da66 | cf07c0eb93f36ed2b1a6ad0e8f0d1a16034da13f | /leetcode/src/main/java/com/dgh/leetcode/Number235.java | 4a0d5718f55048ea8977c1756c8beb8520a4ed40 | []
| no_license | ding-guohang/algorithm | b8cc432f1213aac02da6dc266edf3e7023b22df2 | 1ea97ad28c34b695e9735b51a810ba161141fda0 | refs/heads/master | 2021-07-21T19:55:33.466758 | 2020-10-09T03:22:37 | 2020-10-09T03:22:37 | 218,208,567 | 0 | 0 | null | 2020-10-13T23:20:19 | 2019-10-29T05:08:57 | Java | UTF-8 | Java | false | false | 2,514 | java | package com.dgh.leetcode;
/**
* 给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
* <p>
* 百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
* <p>
* 例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5]
* <p>
* <p>
* <p>
*
* <p>
* 示例 1:
* <p>
* 输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
* 输出: 6
* 解释: 节点 2 和节点 8 的最近公共祖先是 6。
* 示例 2:
* <p>
* 输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
* 输出: 2
* 解释: 节点 2 和节点 4 的最近公共祖先是 2, 因为根据定义最近公共祖先节点可以为节点本身。
*
* <p>
* 说明:
* <p>
* 所有节点的值都是唯一的。
* p、q 为不同节点且均存在于给定的二叉搜索树中。
*
* @author 丁国航 Meow on 2020/9/27
*/
public class Number235 {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
/**
* 方法二:一次遍历
* 思路与算法
*
* 我们从根节点开始遍历;
*
* 如果当前节点的值大于 pp 和 qq 的值,说明 pp 和 qq 应该在当前节点的左子树,因此将当前节点移动到它的左子节点;
*
* 如果当前节点的值小于 pp 和 qq 的值,说明 pp 和 qq 应该在当前节点的右子树,因此将当前节点移动到它的右子节点;
*
* 如果当前节点的值不满足上述两条要求,那么说明当前节点就是「分岔点」。此时,pp 和 qq 要么在当前节点的不同的子树中,要么其中一个就是当前节点。
*
* 可以发现,如果我们将这两个节点放在一起遍历,我们就省去了存储路径需要的空间。
*/
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
TreeNode now = root;
while (null != now) {
if (now.val > p.val && now.val > q.val) {
now = now.left;
continue;
}
if (now.val < p.val && now.val < q.val) {
now = now.right;
continue;
}
return now;
}
return null;
}
}
| [
"[email protected]"
]
| |
a058bf16ff615383e6ecb54bbf422f4f8f051236 | 5d8aef3058e9b90f20763cdb5e5f2ee939ad7ae8 | /cafe-master-pom/service/src/main/java/com/cafe/mybatis/domain/Base.java | 5e4f98d7eb2d394547c5aa791fcd564e5f1dd727 | []
| no_license | farzia/cafePlatform | c8c07b19ffb27c303c00c2433e5843b9927b4ace | 0393cca260e6bcea8168ec0bdae942f8d07bdd30 | refs/heads/master | 2021-01-18T11:57:59.372925 | 2016-04-04T14:02:04 | 2016-04-04T14:02:04 | 55,415,075 | 0 | 0 | null | 2016-04-04T13:51:07 | 2016-04-04T13:51:06 | null | UTF-8 | Java | false | false | 897 | java | package com.cafe.mybatis.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.commons.lang.BooleanUtils;
import java.io.Serializable;
/**
* Created by mamun on 1/11/16.
*/
public class Base implements Serializable {
private Boolean isSelected;
@JsonIgnore
private Boolean skipAudit;
private Integer serial; // used in pagination to show serial
public Boolean getIsSelected() {
return BooleanUtils.toBoolean(isSelected);
}
public void setIsSelected(Boolean isSelected) {
this.isSelected = isSelected;
}
public Boolean getSkipAudit() {
return skipAudit;
}
public void setSkipAudit(Boolean skipAudit) {
this.skipAudit = skipAudit;
}
public Integer getSerial() {
return serial;
}
public void setSerial(Integer serial) {
this.serial = serial;
}
}
| [
"[email protected]"
]
| |
7d28cdb00e1a15f049fe8be16cb654664775f14a | 11115790db63813e05da2fcda0751b6b56a7ca27 | /HappyNumbers.java | f07c376ea7fa1581d3ba97a2cc43abb0d3bcdac1 | []
| no_license | JazzyJas0911/HappyNumbers | e31f254645a37a9642295c8fe8fef7d5d02c239f | 3c3e3efcf98c3733d9ed0d252a4ff03d8b3b305e | refs/heads/master | 2020-05-18T22:18:30.774173 | 2019-05-03T02:27:00 | 2019-05-03T02:27:00 | 184,687,953 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,946 | java | /* Jasmin Agustin
* CECS 274 - 05
* Project 3 - Happy Numbers
* 10/18/2016
*/
import java.util.ArrayList;
import java.util.Scanner;
public class HappyNumbers {
static ArrayList <Integer> List = new ArrayList<Integer>();
public static void main(String[] args) {
int Choice = 0;
Scanner keyboard = new Scanner(System.in);
while(Choice != 3){
Choice = Menu();
switch (Choice){
case 1:
System.out.println("Please enter a positive number.");
int number = positiveNumber();
int temp = number;
while(!inHappyList(temp, List) && !isHappy(temp)){
List.add(temp);
temp = SumOfDigitsSquared(temp);
}
List.add(temp);
displayList(temp);
List.clear();
break;
case 2:
System.out.println("Please enter 2 integers and I will output the Happy Numbers between those numbers.");
System.out.print("Number 1: ");
int num1 = positiveNumber();
System.out.print("Number 2: ");
int num2 = positiveNumber();
displayRange(num1, num2);
System.out.println("\n");
break;
case 3:
System.out.println("You have chosen to exit the code.");
break;
default:
System.out.println("Error. Invalid input please try again.");
break;
}
}
}//end of main
public static int Menu(){
Scanner keyboard = new Scanner(System.in);
System.out.println("Menu:\n"
+ "1. Show Happy Sequence for a number\n"
+ "2. Show all Happy Numbers in a range\n"
+ "3. Exit\n");
int UserInput = keyboard.nextInt();
return UserInput;
}
public static int positiveNumber(){
Scanner keyboard = new Scanner(System.in);
int positive = 0;
while(positive < 1){
positive = keyboard.nextInt();
if(positive < 1)
System.out.println("Error. Please enter a positive number.");
}
return positive;
}
public static boolean isHappy(int x){
boolean happy = false;
if (x == 1)
happy = true;
return happy;
}
public static boolean inHappyList(int x, ArrayList <Integer> List){
return List.contains(x);
}
public static int SumOfDigitsSquared(int x){
if(x < 10)
return x * x;
else
return SumOfDigitsSquared(x / 10) + SumOfDigitsSquared(x % 10);
}
public static void displayList(int x){
System.out.println("List: " + List);
if(isHappy(x) == true)
System.out.println(" - Happy\n");
else
System.out.println(" - Not Happy\n");
}
public static void displayRange(int x, int y){
int counter = 0;
while(x <= y){
int temp = x;
int nIntegers = x;
while(!inHappyList(temp, List) && !isHappy(temp)){
List.add(temp);
temp = SumOfDigitsSquared(temp);
}
if(isHappy(temp) == true){
System.out.print(x);
while(nIntegers > 0){
nIntegers = nIntegers / 10;
counter++;
}
}
else{
System.out.print(".");
counter++;
}
List.clear();
if (counter > 74){
counter = 0;
System.out.println();
}
x++;
}
}
}//end of class | [
"[email protected]"
]
| |
95b4a53f2b728ed105e5090723058f4a1ba42a99 | ca030864a3a1c24be6b9d1802c2353da4ca0d441 | /classes11.dex_source_from_JADX/com/facebook/pages/fb4a/events/eventslist/protocol/PageEventsGraphQLParsers.java | 5e19b502411f5765b3d00d586b7e5d8506806d0d | []
| no_license | pxson001/facebook-app | 87aa51e29195eeaae69adeb30219547f83a5b7b1 | 640630f078980f9818049625ebc42569c67c69f7 | refs/heads/master | 2020-04-07T20:36:45.758523 | 2018-03-07T09:04:57 | 2018-03-07T09:04:57 | 124,208,458 | 4 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,504 | java | package com.facebook.pages.fb4a.events.eventslist.protocol;
import com.facebook.events.graphql.EventsGraphQLParsers.EventCommonFragmentParser;
import com.facebook.flatbuffers.FlatBufferBuilder;
import com.facebook.flatbuffers.MutableFlatBuffer;
import com.facebook.graphql.enums.GraphQLEventsCalendarSubscriptionStatus;
import com.facebook.graphql.modelutil.DeserializerHelpers;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.nio.ByteBuffer;
/* compiled from: profile_fields */
public class PageEventsGraphQLParsers {
/* compiled from: profile_fields */
public final class PagePastEventsQueryParser {
/* compiled from: profile_fields */
public final class OwnedEventsParser {
/* compiled from: profile_fields */
public final class PageInfoParser {
public static int m4067a(JsonParser jsonParser, FlatBufferBuilder flatBufferBuilder) {
int[] iArr = new int[2];
boolean[] zArr = new boolean[1];
boolean[] zArr2 = new boolean[1];
while (jsonParser.c() != JsonToken.END_OBJECT) {
String i = jsonParser.i();
jsonParser.c();
if (!(jsonParser.g() == JsonToken.VALUE_NULL || i == null)) {
if (i.equals("end_cursor")) {
iArr[0] = flatBufferBuilder.b(jsonParser.o());
} else if (i.equals("has_next_page")) {
zArr[0] = true;
zArr2[0] = jsonParser.H();
} else {
jsonParser.f();
}
}
}
flatBufferBuilder.c(2);
flatBufferBuilder.b(0, iArr[0]);
if (zArr[0]) {
flatBufferBuilder.a(1, zArr2[0]);
}
return flatBufferBuilder.d();
}
public static void m4068a(MutableFlatBuffer mutableFlatBuffer, int i, JsonGenerator jsonGenerator) {
jsonGenerator.f();
if (mutableFlatBuffer.g(i, 0) != 0) {
jsonGenerator.a("end_cursor");
jsonGenerator.b(mutableFlatBuffer.c(i, 0));
}
boolean a = mutableFlatBuffer.a(i, 1);
if (a) {
jsonGenerator.a("has_next_page");
jsonGenerator.a(a);
}
jsonGenerator.g();
}
}
public static int m4069a(JsonParser jsonParser, FlatBufferBuilder flatBufferBuilder) {
int[] iArr = new int[2];
while (jsonParser.c() != JsonToken.END_OBJECT) {
String i = jsonParser.i();
jsonParser.c();
if (!(jsonParser.g() == JsonToken.VALUE_NULL || i == null)) {
if (i.equals("nodes")) {
iArr[0] = EventCommonFragmentParser.b(jsonParser, flatBufferBuilder);
} else if (i.equals("page_info")) {
iArr[1] = PageInfoParser.m4067a(jsonParser, flatBufferBuilder);
} else {
jsonParser.f();
}
}
}
flatBufferBuilder.c(2);
flatBufferBuilder.b(0, iArr[0]);
flatBufferBuilder.b(1, iArr[1]);
return flatBufferBuilder.d();
}
public static void m4070a(MutableFlatBuffer mutableFlatBuffer, int i, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) {
jsonGenerator.f();
int g = mutableFlatBuffer.g(i, 0);
if (g != 0) {
jsonGenerator.a("nodes");
EventCommonFragmentParser.a(mutableFlatBuffer, g, jsonGenerator, serializerProvider);
}
g = mutableFlatBuffer.g(i, 1);
if (g != 0) {
jsonGenerator.a("page_info");
PageInfoParser.m4068a(mutableFlatBuffer, g, jsonGenerator);
}
jsonGenerator.g();
}
}
public static MutableFlatBuffer m4071a(JsonParser jsonParser) {
FlatBufferBuilder flatBufferBuilder = new FlatBufferBuilder(128);
int[] iArr = new int[1];
while (jsonParser.c() != JsonToken.END_OBJECT) {
String i = jsonParser.i();
jsonParser.c();
if (!(jsonParser.g() == JsonToken.VALUE_NULL || i == null)) {
if (i.equals("owned_events")) {
iArr[0] = OwnedEventsParser.m4069a(jsonParser, flatBufferBuilder);
} else {
jsonParser.f();
}
}
}
flatBufferBuilder.c(1);
flatBufferBuilder.b(0, iArr[0]);
flatBufferBuilder.d(flatBufferBuilder.d());
ByteBuffer wrap = ByteBuffer.wrap(flatBufferBuilder.e());
wrap.position(0);
MutableFlatBuffer mutableFlatBuffer = new MutableFlatBuffer(wrap, null, null, true, null);
mutableFlatBuffer.a(4, Boolean.valueOf(true));
return mutableFlatBuffer;
}
}
/* compiled from: profile_fields */
public final class PageUpcomingEventsQueryParser {
/* compiled from: profile_fields */
public final class OwnedEventsParser {
/* compiled from: profile_fields */
public final class PageInfoParser {
public static int m4072a(JsonParser jsonParser, FlatBufferBuilder flatBufferBuilder) {
int[] iArr = new int[2];
boolean[] zArr = new boolean[1];
boolean[] zArr2 = new boolean[1];
while (jsonParser.c() != JsonToken.END_OBJECT) {
String i = jsonParser.i();
jsonParser.c();
if (!(jsonParser.g() == JsonToken.VALUE_NULL || i == null)) {
if (i.equals("end_cursor")) {
iArr[0] = flatBufferBuilder.b(jsonParser.o());
} else if (i.equals("has_next_page")) {
zArr[0] = true;
zArr2[0] = jsonParser.H();
} else {
jsonParser.f();
}
}
}
flatBufferBuilder.c(2);
flatBufferBuilder.b(0, iArr[0]);
if (zArr[0]) {
flatBufferBuilder.a(1, zArr2[0]);
}
return flatBufferBuilder.d();
}
public static void m4073a(MutableFlatBuffer mutableFlatBuffer, int i, JsonGenerator jsonGenerator) {
jsonGenerator.f();
if (mutableFlatBuffer.g(i, 0) != 0) {
jsonGenerator.a("end_cursor");
jsonGenerator.b(mutableFlatBuffer.c(i, 0));
}
boolean a = mutableFlatBuffer.a(i, 1);
if (a) {
jsonGenerator.a("has_next_page");
jsonGenerator.a(a);
}
jsonGenerator.g();
}
}
public static int m4074a(JsonParser jsonParser, FlatBufferBuilder flatBufferBuilder) {
int[] iArr = new int[2];
while (jsonParser.c() != JsonToken.END_OBJECT) {
String i = jsonParser.i();
jsonParser.c();
if (!(jsonParser.g() == JsonToken.VALUE_NULL || i == null)) {
if (i.equals("nodes")) {
iArr[0] = EventCommonFragmentParser.b(jsonParser, flatBufferBuilder);
} else if (i.equals("page_info")) {
iArr[1] = PageInfoParser.m4072a(jsonParser, flatBufferBuilder);
} else {
jsonParser.f();
}
}
}
flatBufferBuilder.c(2);
flatBufferBuilder.b(0, iArr[0]);
flatBufferBuilder.b(1, iArr[1]);
return flatBufferBuilder.d();
}
public static void m4075a(MutableFlatBuffer mutableFlatBuffer, int i, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) {
jsonGenerator.f();
int g = mutableFlatBuffer.g(i, 0);
if (g != 0) {
jsonGenerator.a("nodes");
EventCommonFragmentParser.a(mutableFlatBuffer, g, jsonGenerator, serializerProvider);
}
g = mutableFlatBuffer.g(i, 1);
if (g != 0) {
jsonGenerator.a("page_info");
PageInfoParser.m4073a(mutableFlatBuffer, g, jsonGenerator);
}
jsonGenerator.g();
}
}
public static int m4076a(JsonParser jsonParser, FlatBufferBuilder flatBufferBuilder) {
int[] iArr = new int[5];
boolean[] zArr = new boolean[2];
boolean[] zArr2 = new boolean[1];
int[] iArr2 = new int[1];
while (jsonParser.c() != JsonToken.END_OBJECT) {
String i = jsonParser.i();
jsonParser.c();
if (!(jsonParser.g() == JsonToken.VALUE_NULL || i == null)) {
if (i.equals("events_calendar_can_viewer_subscribe")) {
zArr[0] = true;
zArr2[0] = jsonParser.H();
} else if (i.equals("events_calendar_subscriber_count")) {
zArr[1] = true;
iArr2[0] = jsonParser.E();
} else if (i.equals("events_calendar_subscription_status")) {
iArr[2] = flatBufferBuilder.a(GraphQLEventsCalendarSubscriptionStatus.fromString(jsonParser.o()));
} else if (i.equals("owned_events")) {
iArr[3] = OwnedEventsParser.m4074a(jsonParser, flatBufferBuilder);
} else if (i.equals("viewer_profile_permissions")) {
iArr[4] = DeserializerHelpers.a(jsonParser, flatBufferBuilder);
} else {
jsonParser.f();
}
}
}
flatBufferBuilder.c(5);
if (zArr[0]) {
flatBufferBuilder.a(0, zArr2[0]);
}
if (zArr[1]) {
flatBufferBuilder.a(1, iArr2[0], 0);
}
flatBufferBuilder.b(2, iArr[2]);
flatBufferBuilder.b(3, iArr[3]);
flatBufferBuilder.b(4, iArr[4]);
return flatBufferBuilder.d();
}
}
}
| [
"[email protected]"
]
| |
6877ddf109ef054e57c70b75140d5e18b139c174 | 9ff0d09b62146d91c8b7c42acf74af8b200208d3 | /src/main/java/com/example/netty_learning/chapter8_EncodeAndDecode/protocol/command/Packet.java | bb29b8ccaa675ff993243c40624fdac2c9994355 | []
| no_license | loloassange/NettyLearning | 7ef703d03b659a19288638531fc6b8033c41ab76 | bb03bf5a54f4ec3950346da8312dccc691acae35 | refs/heads/master | 2020-05-22T21:26:28.612814 | 2019-05-19T06:47:10 | 2019-05-19T06:47:10 | 186,526,000 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 943 | java | package com.example.netty_learning.chapter8_EncodeAndDecode.protocol.command;
import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
/**
* 1. 这个是 通信过程中 Java 对象的抽象类 ,可以看到:
* 我们定义了一个版本号(默认值为 1 )以及一个获取指令的抽象方法,所有的指令数据包都必须实现这个方法,这样我们就可以知道某种指令的含义。
*
* 2. @Data 注解由 lombok 提供,它会自动帮我们生产 getter/setter 方法,减少大量重复代码,推荐使用。
*/
@Data
public abstract class Packet {
/**
* 协议版本
*
* @JSONField(deserialize = false, serialize = false) 忽略不想反序列化的字段,忽略不想序列化的字段
*/
@JSONField(deserialize = false, serialize = false)
private Byte version = 1;
@JSONField(serialize = false)
public abstract Byte getCommand();
}
| [
"[email protected]"
]
| |
ce4749fa1bae78cd07e5105f764d90f3fe8f423e | 9e4dc6eee0da7286233b18eae534a0b272b16155 | /warehouse-common/src/main/java/com/ms/warehouse/common/db/helper/ListHashtable.java | 7902a7874b0d3a22db0fb5a3bca725132f799a2a | []
| no_license | ms930602/TJRJ | a38d5f42ae5d52e83aa32261d39f3e0dc9654e67 | 20a6d262ac505a6835c408f876eddf459632abc5 | refs/heads/master | 2020-03-31T08:52:43.892273 | 2018-12-04T08:46:22 | 2018-12-04T08:46:22 | 152,075,310 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,262 | java | /*
* Created on Nov 23, 2004
*
*/
package com.ms.warehouse.common.db.helper;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
/**
* @author MF1180
* Hashtable that maintains the input order of the data elements - Note
* only put, putall, clear and remove maintains the ordered list
*
*/
@SuppressWarnings({"serial", "rawtypes","unchecked"})
public class ListHashtable extends Hashtable {
protected List orderedKeys = new ArrayList();
public synchronized void clear() {
super.clear();
orderedKeys = new ArrayList();
}
public synchronized Object put(Object aKey, Object aValue) {
if (orderedKeys.contains(aKey)) {
int pos = orderedKeys.indexOf(aKey);
orderedKeys.remove(pos);
orderedKeys.add(pos,aKey);
}
else {
if (aKey instanceof Integer) {
Integer key = (Integer) aKey;
int pos = getFirstKeyGreater(key.intValue());
if (pos >= 0)
orderedKeys.add(pos,aKey);
else
orderedKeys.add(aKey);
}
else
orderedKeys.add(aKey);
}
return super.put(aKey, aValue);
}
/**
* @param aKey
* @returns
* calculate position at which the first key is greater
* otherwise return -1 if no key can be found which is greater
*
*/
private int getFirstKeyGreater(int aKey) {
int pos = 0;
int numKeys = getOrderedKeys().size();
for (int i=0;i<numKeys;i++) {
Integer key = (Integer) getOrderedKey(i);
int keyval = key.intValue();
if (keyval < aKey)
++pos;
else
break;
}
if (pos >= numKeys)
pos = -1;
return pos;
}
public synchronized Object remove(Object aKey) {
if (orderedKeys.contains(aKey)) {
int pos = orderedKeys.indexOf(aKey);
orderedKeys.remove(pos);
}
return super.remove(aKey);
}
/**
* This method reorders the ListHashtable only if the keys
* used are integer keys.
*
*/
public void reorderIntegerKeys() {
List keys = getOrderedKeys();
int numKeys = keys.size();
if (numKeys <=0 )
return;
if (!(getOrderedKey(0) instanceof Integer))
return;
List newKeys = new ArrayList();
List newValues = new ArrayList();
for (int i=0;i<numKeys;i++) {
Integer key = (Integer) getOrderedKey(i);
Object val = getOrderedValue(i);
int numNew = newKeys.size();
int pos = 0;
for (int j=0;j<numNew;j++) {
Integer newKey = (Integer) newKeys.get(j);
if (newKey.intValue() < key.intValue())
++pos;
else
break;
}
if (pos >= numKeys) {
newKeys.add(key);
newValues.add(val);
} else {
newKeys.add(pos,key);
newValues.add(pos,val);
}
}
// reset the contents
this.clear();
for (int l=0;l<numKeys;l++) {
put(newKeys.get(l),newValues.get(l));
}
}
public String toString() {
StringBuffer x = new StringBuffer();
x.append("Ordered Keys: ");
int numKeys = orderedKeys.size();
x.append("[");
for (int i=0;i<numKeys;i++) {
x.append(orderedKeys.get(i)+ " ");
}
x.append("]\n");
x.append("Ordered Values: ");
x.append("[");
for (int j=0;j<numKeys;j++) {
x.append(getOrderedValue(j)+" ");
}
x.append("]\n");
return x.toString();
}
public void merge(ListHashtable newTable) {
// This merges the newtable with the current one
int num = newTable.size();
for (int i=0;i<num;i++) {
Object aKey = newTable.getOrderedKey(i);
Object aVal = newTable.getOrderedValue(i);
this.put(aKey, aVal);
}
}
/**
* @return Returns the orderedKeys.
*/
public List getOrderedKeys() {
return orderedKeys;
}
public Object getOrderedKey(int i) {
return getOrderedKeys().get(i);
}
/**
* This method looks through the list of values and returns the key
* associated with the value.. Otherwise if not found, null is returned
* @param aValue
* @return
*/
public Object getKeyForValue(Object aValue) {
int num = getOrderedValues().size();
for (int i=0;i<num;i++) {
Object tmpVal = getOrderedValue(i);
if (tmpVal.equals(aValue)) {
return getOrderedKey(i);
}
}
return null;
}
public List getOrderedValues() {
List values = new ArrayList();
int numKeys = orderedKeys.size();
for (int i=0;i<numKeys;i++) {
values.add(get(getOrderedKey(i)));
}
return values;
}
public Object getOrderedValue(int i) {
return get(getOrderedKey(i));
}
}
| [
"[email protected]"
]
| |
8c0a4e2bb37d9655f75b20fd8130bcfd3afbe05f | 71fce0ad9d679d1a6877acd2600d6bf35d46e56d | /src/chess/ChessPosition.java | 6d7ed1307c83994b39330aa9c04c10015df3f9cb | []
| no_license | francinaldobrito/project-chess | ef6c046622b08de1a2b2711bcff345e3c7a97aed | 86741463e6224c96c81040c9202eb3a2640e0f28 | refs/heads/master | 2020-06-01T15:37:18.183082 | 2019-06-09T03:34:41 | 2019-06-09T03:34:41 | 190,835,822 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 770 | java | package chess;
import boardgame.Position;
public class ChessPosition {
private char column;
private int row;
public ChessPosition(char column, int row) {
if (column < 'a' || column > 'h' || row < 1 || row > 8) {
throw new ChessException(" Erro na instacia da posição, valores validos de a1 a h8.");
}
this.column = column;
this.row = row;
}
public char getColumn() {
return column;
}
public int getRow() {
return row;
}
protected Position toPosition() {
return new Position(8 - row, column - 'a');
}
protected static ChessPosition fromPosition(Position position) {
return new ChessPosition((char) ('a' - position.getColumn()), 8 - position.getRow());
}
@Override
public String toString() {
return "" + column + row;
}
}
| [
"[email protected]"
]
| |
dee1295fbdb075d20b6b289dea095eb3cdcdb583 | e90bfb91ae7e218f7d237e07258731e0e1924295 | /src/main/java/tn/gov/douane/formations/api/dto/UserGradeDto.java | ee1f103d18971cdeee735a94b5b513a8f1a7fb2d | [
"Apache-2.0"
]
| permissive | christian80gabi/sprintboot_formations_sapnextgen | 0491b6fb61e5d7c21a9741d30e27e8269f647313 | 2d9ec80392d48bb83a991872029700097a91864a | refs/heads/main | 2023-09-01T01:48:57.375810 | 2021-10-29T14:11:43 | 2021-10-29T14:11:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,505 | java | package tn.gov.douane.formations.api.dto;
import tn.gov.douane.formations.api.model.Grade;
import tn.gov.douane.formations.api.model.User;
import java.util.List;
public class UserGradeDto {
private int id;
private int userId;
private int gradeId;
private User user;
private Grade grade;
private List<User> users;
private List<Grade> grades;
public UserGradeDto() {
}
public UserGradeDto(int id, int userId, int gradeId) {
this.id = id;
this.userId = userId;
this.gradeId = gradeId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getGradeId() {
return gradeId;
}
public void setGradeId(int gradeId) {
this.gradeId = gradeId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Grade getGrade() {
return grade;
}
public void setGrade(Grade grade) {
this.grade = grade;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public List<Grade> getGrades() {
return grades;
}
public void setGrades(List<Grade> grades) {
this.grades = grades;
}
}
| [
"[email protected]"
]
| |
1ef896447021efb4a108938d37b824bf01f2b7e8 | e88b11c1eb56e4468cd31ab519286c917bff85a1 | /Networks/task6/src/User.java | 37e33ac6226931e12915faf37a8272c63d5af0f4 | []
| no_license | 15202-sidorov/NSU_courses_2 | b23554c2b6527c0d422488f40bfd4da26d168bd9 | 7346d59e0b34e526accef6375607a127cd33d55f | refs/heads/master | 2021-09-26T22:11:36.242761 | 2018-11-03T12:58:25 | 2018-11-03T12:58:25 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 515 | java | import java.util.UUID;
public class User {
public User ( String inputUserName ) {
userName = inputUserName;
id = UUID.randomUUID();
isOnline = true;
token = userName.hashCode();
}
public String getUserName() { return userName; }
public UUID getId() { return id; }
public boolean isOnline() { return isOnline; }
public int getToken() { return token; }
private String userName;
private UUID id;
private boolean isOnline;
private int token;
}
| [
"[email protected]"
]
| |
d38e57973209c11c09d96dd3e3c452b7d3e3810d | e73b09691ba87cf26aae334dbd2159a6fa3b55fb | /src/main/java/com/olg/qa/smoketest/Withdrawal.java | 08d4d78e5015e23aad5d92a502008cdb71450627 | []
| no_license | swethasayala/OLGSmokeTest | 61fb9b87a7c15dc11a9b1b1a86d6c1bb0f28c183 | 4e97d794395378ca66c98a982828ba7f4807a2e2 | refs/heads/master | 2020-03-26T09:14:38.522645 | 2018-08-14T16:12:25 | 2018-08-14T16:12:25 | 144,742,121 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 60 | java | package com.olg.qa.smoketest;
public class Withdrawal {
}
| [
"[email protected]"
]
| |
b801bebbdb1c3a55724c8ae93e257d7855489f02 | ebe7514295d33ecd88d4b2510d79ef0e5def8937 | /src/main/java/com/kakawin/gis/springboot/modules/system/entity/FileInfo.java | 29d1e3195e0ac8fe5952ab08219f7209b60f783f | []
| no_license | janck13/spring-boot | cd5822c6978462acb53abbec23bea05c5a1e34e7 | 5c2a100d8af32477416cfd0a39f3e19ae2319320 | refs/heads/master | 2020-05-21T03:04:55.782272 | 2017-10-30T03:27:14 | 2017-10-30T03:27:14 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,211 | java | package com.kakawin.gis.springboot.modules.system.entity;
import java.io.File;
import java.io.Serializable;
import java.util.Date;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.fasterxml.jackson.annotation.JsonIgnore;
@TableName(value = "tb_sys_file_info")
public class FileInfo implements Serializable {
private static final long serialVersionUID = -8756106587961682525L;
/** fileId: 文件id,作为保存在文件系统下的名称 */
@TableId(value = "file_id")
private String fileId;
/** fileName: 原始文件名,原上传的文件名 */
@TableField(value = "file_name")
private String fileName;
/** fileDir: 文件父目录 */
@JsonIgnore
@TableField(value = "file_dir")
private String fileDir;
/** fileType: 文件类型 */
@TableField(value = "file_type")
private String fileType;
/** fileContentType: 文件传输类型 */
@TableField(value = "file_content_type")
private String fileContentType;
/** fileSize: 文件大小,单位为Byte */
@TableField(value = "file_size")
private long fileSize;
/** MD5: MD5码 */
@TableField(value = "md5")
private String md5;
/** creator: 创建人 */
private String creator;
/** createTime: 创建时间 */
@TableField(value = "create_time")
private Date createTime; // 创建时间
public String getFileId() {
return fileId;
}
public void setFileId(String fileId) {
this.fileId = fileId;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileDir() {
return fileDir;
}
public void setFileDir(String fileDir) {
this.fileDir = fileDir;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
public long getFileSize() {
return fileSize;
}
public void setFileSize(long fileSize) {
this.fileSize = fileSize;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getMd5() {
return md5;
}
public void setMd5(String md5) {
this.md5 = md5;
}
@JsonIgnore
public String getFullPath() {
if (StringUtils.isEmpty(this.fileId)) {
return "";
}
if (StringUtils.isEmpty(this.fileType)) {
return this.fileDir + File.separator + this.fileId;
}
return this.fileDir + File.separator + this.fileId + "." + this.fileType;
}
@Override
public String toString() {
return "FileInfo [fileId=" + fileId + ", fileName=" + fileName + ", fileDir=" + fileDir + ", fileType="
+ fileType + ", fileContentType=" + fileContentType + ", fileSize=" + fileSize + ", md5=" + md5
+ ", creator=" + creator + ", createTime=" + createTime + "]";
}
}
| [
"[email protected]"
]
| |
77a9c495bb7c99e702bc95821eda912d69f2ec00 | 6f36e847fbacb814f7ba041fe060dab32fa1be74 | /commons/common-utils/src/main/java/com/study/util/EntityUtils.java | 47d7d543f3b4a3cffaab0774b3c3c9a46d002847 | []
| no_license | wcl19860926/springboot-demo | b3d31f2a03bb3edc3097abad55d356f0505a2d28 | c71827acda26314ecd80dfd024e7858147f4c3b3 | refs/heads/main | 2023-03-09T15:31:28.805200 | 2021-02-28T11:34:05 | 2021-02-28T11:34:05 | 342,522,874 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,379 | java | package com.study.util;
import com.study.function.ToStringFunction;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanWrapperImpl;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.ToIntFunction;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* EntityUtils <br>
*
* @author @author xiquee
* @date 2018-11-09 10:16:00
*/
public class EntityUtils {
public static final String CHAR_REGEX = "^[A-Za-z]+$";
public static final int MIN_ORDER_LEN = 20;
public static final String CLASS = "class";
/**
* 获取某字段的值 返回List(String)
*
* @param entities --Entity列表
* @param keyExtractor --属性名称
*/
public static <E> List<String> getStringProperties(List<E> entities, ToStringFunction<? super E> keyExtractor) {
List<String> properties = new ArrayList<>();
if (entities != null && entities.size() > 0 && keyExtractor != null) {
entities.forEach(entity -> properties.add(keyExtractor.applyAsString(entity)));
}
return properties;
}
/**
* 获取某字段的值 返回List(Integer)
*
* @param entities --Entity列表
* @param keyExtractor --属性提取函数
*/
public static <E> List<Integer> getIntegerProperties(List<E> entities, ToIntFunction<? super E> keyExtractor) {
List<Integer> properties = new ArrayList<>();
if (entities != null && entities.size() > 0 && keyExtractor != null) {
entities.forEach(entity -> properties.add(keyExtractor.applyAsInt(entity)));
}
return properties;
}
/**
* 返回Map(String,T)
*
* @param entities --Entity列表
* @param keyExtractor --属性名称
*/
public static <E> Map<String, E> getEntityMap(List<E> entities, ToStringFunction<? super E> keyExtractor) {
Map<String, E> map = new HashMap<>(8);
if (entities != null && entities.size() > 0 && keyExtractor != null) {
entities.forEach(entity -> map.put(keyExtractor.applyAsString(entity), entity));
}
return map;
}
/**
* 返回Map(Integer,T)
*
* @param entities --Entity列表
* @param keyExtractor --属性名称
*/
public static <E> Map<Integer, E> getEntityMap(List<E> entities, ToIntFunction<? super E> keyExtractor) {
Map<Integer, E> map = new HashMap<>(8);
if (entities != null && entities.size() > 0 && keyExtractor != null) {
entities.forEach(entity -> map.put(keyExtractor.applyAsInt(entity), entity));
}
return map;
}
/**
* 将一个Bean转成Map
*/
public static Map<String, Object> transBean2Map(Object obj) {
Map<String, Object> fieldValueMap = new HashMap<>();
if (obj != null && !"".equals(obj)) {
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
// 过滤class属性
if (!CLASS.equals(key)) {
// 得到property对应的getter方法
Method getter = property.getReadMethod();
Object value = getter.invoke(obj);
fieldValueMap.put(key, value);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return fieldValueMap;
}
/**
* 根据source获取对象中的空属性.
*
* @param source 要获取空属性的对象
* @return 获取到的空属性的字段名
*/
private static String[] getNullPropertyNames(Object source) {
final BeanWrapperImpl src = new BeanWrapperImpl(source);
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<String>();
for (java.beans.PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null) {
emptyNames.add(pd.getName());
}
}
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}
/**
* 复制属性,并且属性为非空.
*
* @param src 要复制的对象
* @param target 目标对象
*/
public static void copyPropertiesIgnoreNull(Object src, Object target) {
if (src != null && target != null) {
org.springframework.beans.BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
}
}
public static boolean isValidFieldName(String order) {
if (order.length() >= MIN_ORDER_LEN) {
return false;
}
Pattern pattern = Pattern.compile(CHAR_REGEX);
Matcher matcher = pattern.matcher(order);
return matcher.matches();
}
/**
* @param obj
* @param propertyName
* @param value
*/
public static void setPropertyValue(Object obj, String propertyName, Object value) {
if (obj == null || !StringUtils.hasLength(propertyName)) {
return;
}
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (key.equals(propertyName)) {
Method setter = property.getWriteMethod();
setter.invoke(obj, value);
}
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* @param clazz
* @param properties
* @return
*/
public static Object createEntity(Class<?> clazz, Map<String, Object> properties) {
try {
Object instance = clazz.newInstance();
if (properties != null && properties.size() > 0) {
for (Map.Entry<String, Object> entry : properties.entrySet()) {
setPropertyValue(instance, entry.getKey(), entry.getValue());
}
}
return instance;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
/**
* 使用正则表达式提取中括号中的内容
*/
public static List<String> extractMessageByRegular(String msg, String regex) {
List<String> list = new ArrayList<>();
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(msg);
while (m.find()) {
list.add(m.group().substring(1, m.group().length() - 1));
}
return list;
}
/**
* 比较两个集合<T> 如果一样则返回true, 否则返回false
*/
public static <T> Boolean compareListT(List<T> first, List<T> second) {
if (CollectionUtils.isEmpty(first) && CollectionUtils.isNotEmpty(second)) {
return false;
}
if (CollectionUtils.isEmpty(second) && CollectionUtils.isNotEmpty(first)) {
return false;
}
if (CollectionUtils.isNotEmpty(first) && CollectionUtils.isNotEmpty(second)) {
if (first.size() != second.size()) {
return false;
}
List<T> commonList = new ArrayList<>();
for (T t1 :
first) {
for (T t2 :
second) {
if (t1.equals(t2)) {
commonList.add(t1);
}
}
}
if (commonList.size() == 0 || commonList.size() != first.size() || commonList.size() != second.size()) {
return false;
}
}
return true;
}
}
| [
"[email protected]"
]
| |
795eea90ebe26192f39856c1865d25a46a3ffccb | b107cb503a5fd61bfc1ba58cc2fb0750e4055e0b | /app/src/main/java/co/grability/test/bo/Id.java | 4d382fa4049e6a220c098309ea3de8146fa3f40a | []
| no_license | jhonatancaceres/GrabilityTest | e03f13b29dc4b0b876a16bdfe8fe12a47776a69e | 4a6538868ba6a6e4fda87a93a38047db9e3a067e | refs/heads/master | 2021-01-10T09:07:44.330767 | 2016-04-11T18:00:29 | 2016-04-11T18:00:29 | 55,928,977 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 766 | java | package co.grability.test.bo;
import java.io.Serializable;
public class Id implements Serializable {
private String label;
private String id;
private String bundleId;
public Id() {
}
public Id(String label, String id, String bundleId) {
this.label = label;
this.id = id;
this.bundleId = bundleId;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBundleId() {
return bundleId;
}
public void setBundleId(String bundleId) {
this.bundleId = bundleId;
}
} | [
"[email protected]"
]
| |
7f840e7af06298d45a204ffdcf6a5d738def47b6 | 1565782261813d3de8111297cec91896c6c71eb1 | /jseckill-backend/src/main/java/com/liushaoming/jseckill/backend/mq/MQConsumer.java | 66efcf60e41a22ad757070746a2e3739eae7c6de | [
"Apache-2.0"
]
| permissive | ygs12/jseckill | b6f671d440fa380b4047dc1df73b13c5de8558f4 | 94a2a79cd3150858ed50d8be8132ba4718f29113 | refs/heads/master | 2020-05-26T18:25:46.354341 | 2019-05-10T02:39:17 | 2019-05-10T02:39:17 | 188,334,651 | 1 | 1 | Apache-2.0 | 2019-05-24T01:55:58 | 2019-05-24T01:55:58 | null | UTF-8 | Java | false | false | 5,460 | java | package com.liushaoming.jseckill.backend.mq;
import com.alibaba.fastjson.JSON;
import com.liushaoming.jseckill.backend.bean.MQConfigBean;
import com.liushaoming.jseckill.backend.constant.RedisKey;
import com.liushaoming.jseckill.backend.dto.SeckillMsgBody;
import com.liushaoming.jseckill.backend.enums.AckAction;
import com.liushaoming.jseckill.backend.enums.SeckillStateEnum;
import com.liushaoming.jseckill.backend.exception.SeckillException;
import com.liushaoming.jseckill.backend.service.SeckillService;
import com.rabbitmq.client.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import javax.annotation.Resource;
import java.io.IOException;
@Component
public class MQConsumer {
private static final Logger logger = LoggerFactory.getLogger(MQConsumer.class);
@Resource
private SeckillService seckillService;
@Resource(name = "mqConnectionReceive")
private Connection mqConnectionReceive;
@Resource(name = "initJedisPool")
private JedisPool jedisPool;
@Autowired
private MQConfigBean mqConfigBean;
public void receive() {
Channel channel = null;
try {
channel = mqConnectionReceive.createChannel();
channel.queueDeclare(mqConfigBean.getQueue(), true, false, false, null);
channel.basicQos(0, 1, false);
} catch (IOException e) {
e.printStackTrace();
}
MyDefaultConsumer myDefaultConsumer = new MyDefaultConsumer(channel);
try {
channel.basicConsume(mqConfigBean.getQueue(), false, myDefaultConsumer);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
private class MyDefaultConsumer extends DefaultConsumer {
private Channel channel;
/**
* Constructs a new instance and records its association to the passed-in channel.
*
* @param channel the channel to which this consumer is attached
*/
public MyDefaultConsumer(Channel channel) {
super(channel);
this.channel = channel;
}
@Override
public void handleDelivery(String consumerTag, Envelope envelope,
AMQP.BasicProperties properties, byte[] body)
throws IOException {
long threadId1 = Thread.currentThread().getId();
logger.info("---receive_threadId_1={}", threadId1);
String msg = new String(body, "UTF-8");
logger.info("[mqReceive] '" + msg + "'");
SeckillMsgBody msgBody = JSON.parseObject(msg, SeckillMsgBody.class);
AckAction ackAction = AckAction.ACCEPT;
try {
// 这里演延时2秒,模式秒杀的耗时操作, 上线的时候需要注释掉
// try {
// Thread.sleep(2000);
// } catch (InterruptedException e) {
// logger.error(e.getMessage(), e);
// }
seckillService.handleInRedis(msgBody.getSeckillId(), msgBody.getUserPhone());
ackAction = AckAction.ACCEPT;
} catch (SeckillException seckillE) {
if (seckillE.getSeckillStateEnum() == SeckillStateEnum.SOLD_OUT
|| seckillE.getSeckillStateEnum() == SeckillStateEnum.REPEAT_KILL) {
// 已售罄,或者此人之前已经秒杀过的
ackAction = AckAction.THROW;
} else {
logger.error(seckillE.getMessage(), seckillE);
logger.info("---->NACK--error_requeue!!!");
ackAction = AckAction.RETRY;
}
} finally {
logger.info("------processIt----");
switch (ackAction) {
case ACCEPT:
try {
logger.info("---->ACK");
channel.basicAck(envelope.getDeliveryTag(), false);
} catch (IOException ioE) {
logger.info("---------basicAck_throws_IOException----------");
logger.error(ioE.getMessage(), ioE);
throw ioE;
}
Jedis jedis = jedisPool.getResource();
jedis.srem(RedisKey.QUEUE_PRE_SECKILL, msgBody.getSeckillId() + "@" + msgBody.getUserPhone());
jedis.close();
break;
case THROW:
logger.info("--LET_MQ_ACK REASON:SeckillStateEnum.SOLD_OUT,SeckillStateEnum.REPEAT_KILL");
channel.basicAck(envelope.getDeliveryTag(), false);
Jedis jedis1 = jedisPool.getResource();
jedis1.srem(RedisKey.QUEUE_PRE_SECKILL, msgBody.getSeckillId() + "@" + msgBody.getUserPhone());
jedis1.close();
break;
case RETRY:
logger.info("---->NACK--error_requeue!!!");
channel.basicNack(envelope.getDeliveryTag(), false, true);
break;
}
}
}
}
}
| [
"[email protected]"
]
| |
1767250a08845b113cfd198115bb7773d3904300 | 81d5cb3552c89fc8b89fc7a0ddd3552dd3f6cea6 | /src/ExampleInterface.java | 015088e748f0cf048eb496689b226bb8132b5194 | []
| no_license | Girish979979/Java | 3e1acf06a0c557684651dbd3fdeb472dc2114437 | a5993b4a4800778d655902a6cc54e2a219a2a905 | refs/heads/master | 2021-05-07T08:05:38.621226 | 2017-11-07T18:14:26 | 2017-11-07T18:14:26 | 109,248,775 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 111 | java | interface ExampleInterface {
public void add();
public void multiply();
public void subtract();
}
| [
"[email protected]"
]
| |
a42455d215ba424662529cbbd009a1b309851d0e | e6de01b2152896642c79939190e389146ff937c5 | /src/main/java/com/onlinestore/onlineStore/model/payment/MyWallet.java | 1f3a0542208dce99e716b37fec677aac119df312 | []
| no_license | tamarakitanovska/Store | 65ace7a6b42a197255e25023016c9a428c45b458 | 6d40c377cf423a2044a642869f1cee648fc10350 | refs/heads/master | 2020-07-21T10:28:50.911625 | 2019-01-09T21:19:18 | 2019-01-09T21:19:18 | 206,833,465 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 395 | java | package com.onlinestore.onlineStore.model.payment;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MyWallet {
@Id
@GeneratedValue
public String id;
public String password;
}
| [
"[email protected]"
]
| |
d50be4fbdfcafdc82d3188b70ff7a05258e7690a | 955c2c8da1d457a2601dcda6641dae0f391be397 | /src/main/java/net/playblack/cuboids/exceptions/InvalidApiHookException.java | 3d39127060526023f0f40e1d2c347e7956c58df6 | [
"BSD-2-Clause"
]
| permissive | damagefilter/Cuboids | a4a34d279d484d3737c9908852814cdfada6a3f1 | d47291a9a778488a64784bfafa6e4c56de91cc6d | refs/heads/master | 2016-09-07T06:48:25.696199 | 2014-12-19T09:51:41 | 2014-12-19T09:51:41 | 2,958,340 | 2 | 1 | null | 2014-12-15T12:39:56 | 2011-12-11T14:08:11 | Java | UTF-8 | Java | false | false | 282 | java | package net.playblack.cuboids.exceptions;
public class InvalidApiHookException extends Exception {
/**
*
*/
private static final long serialVersionUID = -6554437535302207763L;
public InvalidApiHookException(String message) {
super(message);
}
}
| [
"[email protected]"
]
| |
9063b69fabb63d51de8d73a2afb32ab3e1a7d883 | 35e62fb26174807276dda301bf34660dd8185582 | /bundles/umljava/tools.vitruv.applications.umljava.java2uml/src-gen/mir/reactions/javaToUmlMethod/JavaNamedElementRenamedReaction.java | 23d096ca2ed180898d8e849d587c7b05d414fc4c | []
| no_license | jGleitz/Vitruv-Applications-ComponentBasedSystems | d3aea6e2d3b106659764e1cde1f10c017d9bd7b4 | 811a4081657f857e3132f76eba1f3b03d830a63e | refs/heads/master | 2023-04-16T15:00:15.597887 | 2018-10-26T07:28:45 | 2018-10-26T07:28:45 | 158,076,165 | 0 | 0 | null | 2023-03-25T00:24:00 | 2018-11-18T11:21:42 | Java | UTF-8 | Java | false | false | 4,078 | java | package mir.reactions.javaToUmlMethod;
import mir.routines.javaToUmlMethod.RoutinesFacade;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.xtext.xbase.lib.Extension;
import org.emftext.language.java.commons.NamedElement;
import tools.vitruv.extensions.dslsruntime.reactions.AbstractReactionRealization;
import tools.vitruv.extensions.dslsruntime.reactions.AbstractRepairRoutineRealization;
import tools.vitruv.extensions.dslsruntime.reactions.ReactionExecutionState;
import tools.vitruv.extensions.dslsruntime.reactions.structure.CallHierarchyHaving;
import tools.vitruv.framework.change.echange.EChange;
import tools.vitruv.framework.change.echange.feature.attribute.ReplaceSingleValuedEAttribute;
@SuppressWarnings("all")
public class JavaNamedElementRenamedReaction extends AbstractReactionRealization {
private ReplaceSingleValuedEAttribute<NamedElement, String> replaceChange;
private int currentlyMatchedChange;
public JavaNamedElementRenamedReaction(final RoutinesFacade routinesFacade) {
super(routinesFacade);
}
public void executeReaction(final EChange change) {
if (!checkPrecondition(change)) {
return;
}
org.emftext.language.java.commons.NamedElement affectedEObject = replaceChange.getAffectedEObject();
EAttribute affectedFeature = replaceChange.getAffectedFeature();
java.lang.String oldValue = replaceChange.getOldValue();
java.lang.String newValue = replaceChange.getNewValue();
getLogger().trace("Passed complete precondition check of Reaction " + this.getClass().getName());
mir.reactions.javaToUmlMethod.JavaNamedElementRenamedReaction.ActionUserExecution userExecution = new mir.reactions.javaToUmlMethod.JavaNamedElementRenamedReaction.ActionUserExecution(this.executionState, this);
userExecution.callRoutine1(replaceChange, affectedEObject, affectedFeature, oldValue, newValue, this.getRoutinesFacade());
resetChanges();
}
private void resetChanges() {
replaceChange = null;
currentlyMatchedChange = 0;
}
public boolean checkPrecondition(final EChange change) {
if (currentlyMatchedChange == 0) {
if (!matchReplaceChange(change)) {
resetChanges();
return false;
} else {
currentlyMatchedChange++;
}
}
return true;
}
private boolean matchReplaceChange(final EChange change) {
if (change instanceof ReplaceSingleValuedEAttribute<?, ?>) {
ReplaceSingleValuedEAttribute<org.emftext.language.java.commons.NamedElement, java.lang.String> _localTypedChange = (ReplaceSingleValuedEAttribute<org.emftext.language.java.commons.NamedElement, java.lang.String>) change;
if (!(_localTypedChange.getAffectedEObject() instanceof org.emftext.language.java.commons.NamedElement)) {
return false;
}
if (!_localTypedChange.getAffectedFeature().getName().equals("name")) {
return false;
}
if (_localTypedChange.isFromNonDefaultValue() && !(_localTypedChange.getOldValue() instanceof java.lang.String)) {
return false;
}
if (_localTypedChange.isToNonDefaultValue() && !(_localTypedChange.getNewValue() instanceof java.lang.String)) {
return false;
}
this.replaceChange = (ReplaceSingleValuedEAttribute<org.emftext.language.java.commons.NamedElement, java.lang.String>) change;
return true;
}
return false;
}
private static class ActionUserExecution extends AbstractRepairRoutineRealization.UserExecution {
public ActionUserExecution(final ReactionExecutionState reactionExecutionState, final CallHierarchyHaving calledBy) {
super(reactionExecutionState);
}
public void callRoutine1(final ReplaceSingleValuedEAttribute replaceChange, final NamedElement affectedEObject, final EAttribute affectedFeature, final String oldValue, final String newValue, @Extension final RoutinesFacade _routinesFacade) {
_routinesFacade.renameUmlNamedElement(affectedEObject);
}
}
}
| [
"[email protected]"
]
| |
1fa32a4924814411b059ac021b2bb794af40fdf7 | 59d024deee481d2d7f5d22c2b2dff52cadcc4fd5 | /mall-admin/src/main/java/com/yoooho/mall/service/impl/PmsStoreServiceImpl.java | 719cbc738029adbe6cfc39b482aa24fe4827e3d3 | []
| no_license | YohooShop/back-end | 73ae5123cf4ef49499afd9f5adc5870d1ef5f191 | 14df7b96c6d03b3ec3dccbb6180a7c46793ae41f | refs/heads/master | 2023-02-14T20:40:28.361896 | 2021-01-18T07:52:59 | 2021-01-18T07:52:59 | 330,533,667 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,764 | java | package com.yoooho.mall.service.impl;
import com.github.pagehelper.PageHelper;
import com.yoooho.mall.common.CommonPage;
import com.yoooho.mall.common.utils.FileUtil;
import com.yoooho.mall.dto.PmsStoreQueryParam;
import com.yoooho.mall.mapper.PmsStoreConfigMapper;
import com.yoooho.mall.mapper.PmsStoreMapper;
import com.yoooho.mall.model.PmsStore;
import com.yoooho.mall.model.PmsStoreConfig;
import com.yoooho.mall.model.PmsStoreConfigExample;
import com.yoooho.mall.model.PmsStoreExample;
import com.yoooho.mall.service.PmsStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
@Service
public class PmsStoreServiceImpl implements PmsStoreService {
@Autowired
PmsStoreConfigMapper storeConfigMapper;
@Autowired
PmsStoreMapper pmsStoreMapper;
public int addStoreConfig (PmsStoreConfig storeConfig) {
return storeConfigMapper.insertSelective(storeConfig);
}
public int updateStoreConfig(PmsStoreConfig storeConfig) {
return storeConfigMapper.updateByPrimaryKeySelective(storeConfig);
}
public List <PmsStoreConfig> queryStoreConfigAll(){
PmsStoreConfigExample storeConfigExample = new PmsStoreConfigExample();
return storeConfigMapper.selectByExample(storeConfigExample);
}
@Override
public CommonPage queryStoreList(PmsStoreQueryParam queryParam, Pageable pageable) {
PageHelper.startPage(pageable.getPageNumber(), pageable.getPageSize());
List<PmsStore> stores = pmsStoreMapper.selectByExample(new PmsStoreExample());
CommonPage result = CommonPage.restPage(stores);
return result;
}
@Override
public List<PmsStore> queryStoreAll(PmsStoreQueryParam queryParam) {
return pmsStoreMapper.selectByExample(new PmsStoreExample());
}
@Override
public int addStore(PmsStore store) {
store.setAddTime(new Date());
return pmsStoreMapper.insertSelective(store);
}
@Override
public int updateStore(PmsStore store) {
return pmsStoreMapper.updateByPrimaryKeySelective(store);
}
@Override
public void delStores(Long[] ids) {
for (Long id : ids) {
pmsStoreMapper.deleteByPrimaryKey(id);
}
}
@Override
public void download(List<PmsStore> stores, HttpServletResponse response) {
List<Map<String, Object>> list = new ArrayList<>();
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
for (PmsStore store : stores) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("门店名称", store.getName());
map.put("简介", store.getIntroduction());
map.put("手机号码", store.getPhone());
map.put("省市区", store.getAddress());
map.put("详细地址", store.getDetailedAddress());
map.put("门店logo", store.getImage());
map.put("纬度", store.getLatitude());
map.put("经度", store.getLongitude());
map.put("核销有效日期", store.getValidTime());
map.put("每日营业开关时间", store.getDayTime());
map.put("添加时间", sdf.format(store.getAddTime()));
map.put("是否显示", store.getIsShow());
map.put("是否删除", store.getIsDel());
list.add(map);
}
try {
FileUtil.downloadExcel(list, response);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| [
"[email protected]"
]
| |
a660d9550df9f345b3581000d30c7d11675b13ae | 9afa19d154c745d3fac4dd35d67dc17e9ac688d9 | /src/main/java/pageObjects/produto/campanha/EditarCampanhaPage.java | 0f1e0a1b092e1b137ac1d6fe2824e552ab57aa23 | []
| no_license | leoacmedeiros/ncbtur | de4cdbdc8f9d3e388a92ae90a2257843ca65c4ca | 0be1fcebe758e4748bc5a5ff41a753059567c8f7 | refs/heads/master | 2020-09-08T23:14:18.174331 | 2019-11-12T17:25:17 | 2019-11-12T17:25:17 | 221,272,887 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,858 | java | package pageObjects.produto.campanha;
import org.junit.Assert;
import org.openqa.selenium.By;
import core.BasePage;
public class EditarCampanhaPage extends BasePage {
public void setCodigoPromocional(String codigoPromocional) {
escrever(By.xpath("//input[@id='codigoPromocional']"), codigoPromocional);
}
public void setNome(String nome) {
escrever(By.xpath("//input[@name='nome']"), nome);
}
public void setTipo(String tipo) {
selecionarComboPeloXPath("//select[@name='tipo']", tipo);
}
public void setDescricao(String descricao) {
escrever(By.xpath("//textarea[@name='descricao']"), descricao);
}
public void setSituacao(String situacao) {
if (situacao.trim().equals("Inativa"))
clicarCheck(By.xpath(
"(//div[@class='tab-pane active']//div[@class='row ng-untouched ng-pristine ng-valid']//div)[12]//span"));
}
public void setRestricoes(String restricoes) {
escrever(By.xpath("//textarea[@name='observacoes']"), restricoes);
}
public void clicarProximo() {
clicarBotao(By.xpath("//button[@class='btn blue button-next']"));
}
public void setTipoVigencia(String vigencia) {
if (vigencia.trim().equals("Período definido")) {
clicarRadio(By.xpath("//input[@value='periodo']"));
} else if (vigencia.trim().equals("Meses")) {
clicarRadio(By.xpath("//input[@value='meses']"));
}
}
public void setVigencia(String tempoIndeterminado, String dataInicio, String dataFim) {
if (tempoIndeterminado.trim().equals("Não")) {
clicarCheck(By.xpath("//div[@class='form-group'])[11]//span"));
escrever(By.xpath("//input[@name='inicioVigencia']"), dataInicio);
escrever(By.xpath("//input[@name='fimVigencia']"), dataFim);
} else if (tempoIndeterminado.trim().equals("Sim")) {
escrever(By.xpath("//input[@name='inicioVigencia']"), dataInicio);
}
}
public void setProduto(String produto) {
scrollPageUP();
if (produto.trim().equals("Todos") && isCheckMarcado(By.xpath("//div[@class='form-group']//div//label[1]"))) {
}
}
public void setCanaisDeVenda(String canais) {
scrollPageUP();
clicarBotao(By.xpath("//button[@class='btn green']"));
if (canais.trim().equals("Todos")) {
clicarBotao(By.xpath("//button[contains(text(),'Pesquisar')]"));
clicarRadio(By.xpath(
"//table[@class='table table-striped table-bordered table-advance table-hover']//thead//tr//th//span"));
clicarBotao(By.xpath("//button[contains(text(),'Adicionar Canais')]"));
} else {
escrever(By.xpath("//form[@class='row ng-untouched ng-pristine ng-valid']//input[@name='nome']"), canais);
clicarBotao(By.xpath("//button[contains(text(),'Pesquisar')]"));
clicarCheck(By.xpath("//tbody//label[@class='mt-checkbox mt-checkbox-outline']//span"));
clicarBotao(By.xpath("//button[contains(text(),'Adicionar Canais')]"));
}
}
public void setAbrangencia(String abrangencia) {
if (!abrangencia.trim().equals("Todos")) {
clicarBotao(By.xpath(
"//body[@class='page-header-fixed page-content-white page-md']/div[@class='page-wrapper']/cbtur-root/div[@class='page-container']/div[@class='page-content-wrapper']/div[@class='page-content']/div[@class='content-outlet-ct']/produto/campanha/cadastrar-campanha/div[@class='portlet light']/div[@class='portlet-body form']/form-wizard[@class='step-width']/div[@class='form-wizard']/div[@class='form-body']/div[@class='tab-content']/div[@class='tab-pane active']/div[@class='tab-5']/canais-venda-form/div[@class='row hide-value-disable ng-untouched ng-pristine ng-valid']/div[@class='col-md-12']/div[@class='form-group mult']/abrangenciaufs/div[@class='col-md-12']/label[1]/span"));
}
}
public void salvar() {
// clicarBotao(By.xpath("//button[@class='btn green button-submit']"));
}
public void mensagemSucesso() {
Assert.assertEquals("Dados gravados com sucesso!", obterTexto(By.xpath("//div[@class='toast-message']")));
}
}
| [
"[email protected]"
]
| |
9e315b12ac392d55877fa7fc33d0382f6d3cb8d3 | 1504b4fc9f37f60761f534b8196f5898fb266648 | /src/java/entidades/Atencion.java | ec1e6880612c3d56955ca29e72e782765c0e911d | []
| no_license | NILCARDENAS1997/MASCOTA-FINAL | 17f3d23553740f2bf5ab3cec836da66937a79332 | 79b509e32311b5f24167402a176a8561139f44b5 | refs/heads/master | 2022-01-24T01:02:18.402063 | 2019-07-19T23:16:38 | 2019-07-19T23:16:38 | 197,855,197 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,983 | java | package entidades;
// Generated 19-jul-2019 9:58:34 by Hibernate Tools 4.3.1
import java.util.Date;
/**
* Atencion generated by hbm2java
*/
public class Atencion implements java.io.Serializable {
private int idAtencion;
private Mascotaporcliente mascotaporcliente;
private Personal personal;
private Date fechaAtencion;
private Date horaAtencion;
private String diagnostico;
public Atencion() {
}
public Atencion(int idAtencion, Mascotaporcliente mascotaporcliente, Personal personal, Date fechaAtencion, Date horaAtencion, String diagnostico) {
this.idAtencion = idAtencion;
this.mascotaporcliente = mascotaporcliente;
this.personal = personal;
this.fechaAtencion = fechaAtencion;
this.horaAtencion = horaAtencion;
this.diagnostico = diagnostico;
}
public int getIdAtencion() {
return this.idAtencion;
}
public void setIdAtencion(int idAtencion) {
this.idAtencion = idAtencion;
}
public Mascotaporcliente getMascotaporcliente() {
return this.mascotaporcliente;
}
public void setMascotaporcliente(Mascotaporcliente mascotaporcliente) {
this.mascotaporcliente = mascotaporcliente;
}
public Personal getPersonal() {
return this.personal;
}
public void setPersonal(Personal personal) {
this.personal = personal;
}
public Date getFechaAtencion() {
return this.fechaAtencion;
}
public void setFechaAtencion(Date fechaAtencion) {
this.fechaAtencion = fechaAtencion;
}
public Date getHoraAtencion() {
return this.horaAtencion;
}
public void setHoraAtencion(Date horaAtencion) {
this.horaAtencion = horaAtencion;
}
public String getDiagnostico() {
return this.diagnostico;
}
public void setDiagnostico(String diagnostico) {
this.diagnostico = diagnostico;
}
}
| [
"[email protected]"
]
| |
064e0692e49edd945b66202a3f95a1826ee48e65 | d72f8d5e6cc72e3851fe3d91400335dc42001991 | /app/src/main/java/com/sanjogstha/codewars/database/dao/DetailDao.java | 1e33e6e4393856f048031951bcf2c84b32275689 | []
| no_license | sanjogshrestha/Codewars | 64cd6b324d7bd1d5d66b581af281e7956961a088 | 906e28cc5f46426b94898c4726b81e60f85833de | refs/heads/master | 2020-04-01T11:11:10.236537 | 2018-10-15T17:04:35 | 2018-10-15T17:04:35 | 153,151,024 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 870 | java | package com.sanjogstha.codewars.database.dao;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.OnConflictStrategy;
import android.arch.persistence.room.Query;
import com.sanjogstha.codewars.database.DbConstant;
import com.sanjogstha.codewars.database.tables.DetailTable;
/**
* Created by sanjogstha on 10/15/18.
* [email protected]
*/
@Dao
public interface DetailDao {
@Query("SELECT * FROM " + DbConstant.DETAIL_TABLE + " WHERE id = :slug")
DetailTable getDetailBySlug(String slug);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertDetail(DetailTable table);
/**
* Counts the number of data in the table.
*
* @return The number of data.
*/
@Query("SELECT COUNT(*) FROM " + DbConstant.DETAIL_TABLE)
int count();
}
| [
"[email protected]"
]
| |
77909d36ea4e06f7dcff36df3a56ecb4fa5f4c86 | 9d2b4147ed1ca0168885a2d06662b0a00c1f2b26 | /src/main/java/com/assure/qa/pages/AbandonedVehiclesPopUp.java | 30a943d71e6678a83c7e0bc5aac44e077d94c643 | []
| no_license | jigarmehta1999/ProjectObjectModel | fd02f8eb45aa337f41e9ac56575f914ca3ea7c16 | 689d73e249c10eec9ad64262de695959cdce96f8 | refs/heads/master | 2021-12-14T22:28:04.374474 | 2019-08-31T17:47:30 | 2019-08-31T17:47:30 | 200,692,403 | 0 | 0 | null | 2021-12-14T21:32:38 | 2019-08-05T16:35:25 | HTML | UTF-8 | Java | false | false | 2,138 | java | package com.assure.qa.pages;
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.Select;
import com.assure.qa.base.TestBase;
public class AbandonedVehiclesPopUp extends TestBase{
@FindBy(id="ui-id-1")
List<WebElement> AbandonedVehiclesPopUpDialogTitle;
@FindBy(xpath="//label[contains(text(),'Abandoned Vehicles Type')]")
WebElement AbandonedVehiclesTypeText;
@FindBy(id="ApplicationType")
WebElement AbandonedVehicleDropDown;
@FindBy(id="btnContinue")
WebElement ContinueButton;
@FindBy(id="Cancel")
WebElement CancelButton;
public AbandonedVehiclesPopUp() {
PageFactory.initElements(driver, this);
}
public boolean isAbandonedVehiclesPopUpDialogTitleDisplayed() {
return(AbandonedVehiclesPopUpDialogTitle.get(1).isDisplayed());
}
public boolean isAbandonedVehiclesTypeTextDisplayed() {
return(AbandonedVehiclesTypeText.isDisplayed());
}
public boolean isAbandonedVehiclesTypeDropDownEnabled() {
return(AbandonedVehicleDropDown.isEnabled());
}
public boolean isAbandonedVehiclesTypeDropDownDisplayed() {
return(AbandonedVehicleDropDown.isDisplayed());
}
public boolean isContinueButtonEnabled() {
return(ContinueButton.isEnabled());
}
public boolean isContinueButtonDisplayed() {
return(ContinueButton.isDisplayed());
}
public boolean isCancelButtonEnabled() {
return(CancelButton.isEnabled());
}
public boolean isCancelButtonDisplayed() {
return(CancelButton.isDisplayed());
}
public String getAbandonedVehiclesPopUpDialogTitleText() {
return(AbandonedVehiclesPopUpDialogTitle.get(1).getText());
}
public String getAbandonedVehiclesTypeText() {
return(AbandonedVehiclesTypeText.getText());
}
public void clickContinueButton() {
ContinueButton.click();
}
public void selectAbandonedVehiclesType(String VehicleTypeValue) {
Select VehicleType = new Select(AbandonedVehicleDropDown);
VehicleType.selectByValue(VehicleTypeValue);
}
}
| [
"[email protected]"
]
| |
735f5a8e2bd4c484155425be266b8205c69d432f | ee0c6942fa44a94da98550842a16236148268a6a | /src/com/bonus/service/BalanceService.java | 18beb2ff1e13dfdcc1e3cd3fbbf5f03f57ff7a9d | []
| no_license | cheeryfly/bonus | 55a48a510b39e2467388fe70a7d0eb6c30632cec | 1968ec33a95fc3f4e8c487334a7359fe69b52491 | refs/heads/master | 2020-12-30T10:12:08.309847 | 2017-09-02T03:18:11 | 2017-09-02T03:18:11 | 98,864,817 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 203 | java | package com.bonus.service;
import java.util.List;
import com.bonus.bean.Equity;
public interface BalanceService {
public void createBalance(Equity e);
public void initiateBalance(Equity e);
}
| [
"[email protected]"
]
| |
9c352d3ea8672fc618727d3cbd44de0fdcef5b5d | 6b347e235d1dd9f8475bfca84a4950ef23cc2d92 | /src/main/java/com/offcn/client/Server.java | e6f073b21526389084aeb6d23d211564fa3453fd | []
| no_license | 349683592/Deom | c98a54103fa28ef8e1a8a94863eb8cd5b210ef1b | fd72d99df0714f413e0173c23804f8089575d33b | refs/heads/master | 2020-04-14T10:30:16.373138 | 2019-01-02T06:06:22 | 2019-01-02T06:06:22 | 163,788,745 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 919 | java |
package com.offcn.client;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
* This class was generated by the JAX-WS RI. JAX-WS RI 2.1.3-hudson-390-
* Generated source version: 2.0
*
*/
@WebService(name = "Server", targetNamespace = "http://offcn.com/")
public interface Server {
/**
*
* @param arg0
* @return returns java.lang.String
*/
@WebMethod
@WebResult(targetNamespace = "")
@RequestWrapper(localName = "getValue", targetNamespace = "http://offcn.com/", className = "com.offcn.client.GetValue")
@ResponseWrapper(localName = "getValueResponse", targetNamespace = "http://offcn.com/", className = "com.offcn.client.GetValueResponse")
public String getValue(@WebParam(name = "arg0", targetNamespace = "") String arg0);
}
| [
"[email protected]"
]
| |
5aacae8937d2eda41d61d644268fe62f4ab8eee1 | ed3cb95dcc590e98d09117ea0b4768df18e8f99e | /project_1_2/src/b/i/i/f/Calc_1_2_18853.java | 1caec3de314ebd5c3af366c4d6d637fa0b1ba723 | []
| no_license | chalstrick/bigRepo1 | ac7fd5785d475b3c38f1328e370ba9a85a751cff | dad1852eef66fcec200df10083959c674fdcc55d | refs/heads/master | 2016-08-11T17:59:16.079541 | 2015-12-18T14:26:49 | 2015-12-18T14:26:49 | 48,244,030 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 134 | java | package b.i.i.f;
public class Calc_1_2_18853 {
/** @return the sum of a and b */
public int add(int a, int b) {
return a+b;
}
}
| [
"[email protected]"
]
| |
bcc0bda2aaf41ea4a8351262a63e905b0ed0fe27 | 543a45c172d49501be7075e96f7936aa4d92ab8b | /app/src/main/java/com/moldedbits/android/api/APIProvider.java | 878352d50f51e7846b127808d25b0dd71705330c | []
| no_license | shishanksingh2015/topsy | e0fdc2d2b173f9831b803aa45fe9766a094950bc | bb40330b116478580fc7792e1856289e3e1058c0 | refs/heads/master | 2021-01-12T12:03:44.554376 | 2016-09-24T16:12:26 | 2016-09-24T16:12:26 | 69,112,443 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,489 | java | package com.moldedbits.android.api;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.moldedbits.android.BuildConfig;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import lombok.Getter;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
*
* Created by abhishek on 05/04/16.
*/
public class APIProvider {
private static Retrofit sRetrofit;
@Getter
private static APIService service;
static {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
// TODO: 08/04/16 might want to remove this in prod
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
builder.connectTimeout(30, TimeUnit.SECONDS);
builder.readTimeout(30, TimeUnit.SECONDS);
builder.writeTimeout(30, TimeUnit.SECONDS);
// Add headers
builder.interceptors().add(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
request = request.newBuilder()
// // TODO: 08/04/16 add project specific stuff here
.addHeader("Authorization", "Basic YWRtaW46ZG90c2xhc2g=")
.build();
return chain.proceed(request);
}
});
// Logging
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
builder.interceptors().add(interceptor);
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.setDateFormat("yyyy-MM-dd")
.create();
sRetrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.API_URL)
.client(builder.build())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
service = sRetrofit.create(APIService.class);
}
} | [
"[email protected]"
]
| |
6193cca5048aa33d1fa666e8991a780f1d4fa926 | 44b44533de9153779e91536b2e0e71ef1c0b301c | /src/main/java/com/yorum/plaka/PlateUtils.java | 9a7e2a2222f6479a0347d097a8ac011ff308d4a0 | []
| no_license | burcuyamn/plate-comment | f51b94af2c2dd53bd7aa00c41ed6d3d894df65bf | c3c86eaec13bc6a52769bec5836207c6eb8fe4c5 | refs/heads/master | 2021-06-26T01:43:57.943786 | 2019-03-01T19:23:15 | 2019-03-01T19:23:15 | 173,351,361 | 1 | 0 | null | 2020-12-20T10:20:54 | 2019-03-01T18:42:02 | Java | UTF-8 | Java | false | false | 899 | java | package com.yorum.plaka;
import java.util.regex.*;
import com.yorum.plaka.dao.pojo.Plate;
public class PlateUtils {
public static final String PLATE_PATTERN = "^(0[1-9]|[1-7][0-9]|8[01])(([A-PR-VYZ])(\\d{4,5})|([A-PR-VYZ]{2})(\\d{3,4})|([A-PR-VYZ]{3})(\\d{2,3}))";
/**
* Gelen plaka stringini PLATE_PATTERN ile karsilastirir ve plaka standardina uygun olup olmadigini kontrol eder.
* @param plate string tipte plaka verisidir.
* @return boolean deger dondurur.
*/
public static boolean validate(String plate) {
return Pattern.matches(PLATE_PATTERN, standardize(plate));
}
/**
* Parametre olarak gelen plakanin bosluklari temizler ve tum harfleri buyuk harfe cevirir.
* @param plate string tipte plaka verisidir.
* @return string tipte {@link Plate} doner.
*/
public static String standardize(String plate) {
return plate.replaceAll("\\s+", "").toUpperCase();
}
} | [
"[email protected]"
]
| |
fb684446c9d09f7f4de3798181775323b5dc5268 | d3c77987f581929c98d90260bf505ff478dd6c6c | /easyPhotos/src/main/java/com/huantansheng/easyphotos/utils/file/FileUtils.java | 444756f7c4bdd6ecd052ee7c6ea46205895b3dd1 | []
| no_license | wztxyxw/trtc | 5fae7c01b1b8101e1aef950a6c1a45bd613a562f | 6ef08fd06f1553f79637c9d7d68a3d3e0548898c | refs/heads/main | 2023-02-24T12:59:57.564112 | 2021-01-25T01:21:48 | 2021-01-25T01:21:48 | 332,594,674 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 21,475 | java | package com.huantansheng.easyphotos.utils.file;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.util.Log;
import android.webkit.MimeTypeMap;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
public class FileUtils {
public static final String DOCUMENTS_DIR = "documents";
// configured android:authorities in AndroidManifest (https://developer.android
// .com/reference/android/support/v4/content/FileProvider)
public static final String HIDDEN_PREFIX = ".";
/**
* TAG for log messages.
*/
static final String TAG = "FileUtils";
private static final boolean DEBUG = false; // Set to true to enable logging
/**
* File and folder comparator. TODO Expose sorting option method
*/
/**
* Folder (directories) filter.
*/
private FileUtils() {
} //private constructor to enforce Singleton pattern
/**
* Gets the extension of a file name, like ".png" or ".jpg".
*
* @param uri
* @return Extension including the dot("."); "" if there is no extension;
* null if uri was null.
*/
public static String getExtension(String uri) {
if (uri == null) {
return null;
}
int dot = uri.lastIndexOf(".");
if (dot >= 0) {
return uri.substring(dot);
} else {
// No extension.
return "";
}
}
/**
* @return Whether the URI is a local one.
*/
public static boolean isLocal(String url) {
return url != null && !url.startsWith("http://") && !url.startsWith("https://");
}
/**
* @return True if Uri is a MediaStore Uri.
* @author paulburke
*/
public static boolean isMediaUri(Uri uri) {
return "media".equalsIgnoreCase(uri.getAuthority());
}
/**
* Convert File into Uri.
*
* @param file
* @return uri
*/
public static Uri getUri(File file) {
return (file != null) ? Uri.fromFile(file) : null;
}
/**
* Returns the path only (without file name).
*
* @param file
* @return
*/
public static File getPathWithoutFilename(File file) {
if (file != null) {
if (file.isDirectory()) {
// no file to be split off. Return everything
return file;
} else {
String filename = file.getName();
String filepath = file.getAbsolutePath();
// Construct path without file name.
String pathwithoutname = filepath.substring(0,
filepath.length() - filename.length());
if (pathwithoutname.endsWith("/")) {
pathwithoutname = pathwithoutname.substring(0, pathwithoutname.length() - 1);
}
return new File(pathwithoutname);
}
}
return null;
}
/**
* @return The MIME type for the given file.
*/
public static String getMimeType(File file) {
String extension = getExtension(file.getName());
if (extension.length() > 0)
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1));
return "application/octet-stream";
}
/**
* @return The MIME type for the give Uri.
*/
public static String getMimeType(Context context, Uri uri) {
File file = new File(getPath(context, uri));
return getMimeType(file);
}
/**
* @return The MIME type for the give String Uri.
*/
public static String getMimeType(Context context, String url) {
String type = context.getContentResolver().getType(Uri.parse(url));
if (type == null) {
type = "application/octet-stream";
}
return type;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is local.
*/
public static boolean isLocalStorageDocument(Context cxt, Uri uri) {
return (cxt.getApplicationContext().getPackageName() + ".fileProvider").equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = MediaStore.Files.FileColumns.DATA;
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs
, null);
if (cursor != null && cursor.moveToFirst()) {
if (DEBUG) DatabaseUtils.dumpCursor(cursor);
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) cursor.close();
}
return null;
}
/**
* Get a file path from a Uri. This will get the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.<br>
* <br>
* Callers should check whether the path is local before assuming it
* represents a local file.
*
* @param context The context.
* @param uri The Uri to query.
* @see #getFile(Context, Uri)
*/
public static String getPath(final Context context, final Uri uri) {
String absolutePath = getLocalPath(context, uri);
return absolutePath != null ? absolutePath : uri.toString();
}
private static String getLocalPath(final Context context, final Uri uri) {
if (DEBUG)
Log.d(TAG + " File -",
"Authority: " + uri.getAuthority() + ", Fragment: " + uri.getFragment() + ", "
+ "Port: " + uri.getPort() + ", Query: " + uri.getQuery() + ", Scheme"
+ ": " + uri.getScheme() + ", Host: " + uri.getHost() + ", Segments: "
+ uri.getPathSegments().toString());
// DocumentProvider
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, uri)) {
// LocalStorageProvider
if (isLocalStorageDocument(context, uri)) {
// The path is the id
return DocumentsContract.getDocumentId(uri);
}
// ExternalStorageProvider
else if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
} else if ("home".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/documents/" + split[1];
}
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
if (id != null && id.startsWith("raw:")) {
return id.substring(4);
}
String[] contentUriPrefixesToTry = new String[]{"content://downloads" +
"/public_downloads", "content://downloads/my_downloads"};
for (String contentUriPrefix : contentUriPrefixesToTry) {
Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix),
Long.valueOf(id));
try {
String path = getDataColumn(context, contentUri, null, null);
if (path != null) {
return path;
}
} catch (Exception e) {
}
}
// path could not be retrieved using ContentResolver, therefore copy file to
// accessible cache using streams
String fileName = getFileName(context, uri);
File cacheDir = getDocumentCacheDir(context);
File file = generateFileName(fileName, cacheDir);
String destinationPath = null;
if (file != null) {
destinationPath = file.getAbsolutePath();
saveFileFromUri(context, uri, destinationPath);
}
return destinationPath;
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri)) {
return uri.getLastPathSegment();
}
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Convert Uri into File, if possible.
*
* @return file A local file that the Uri was pointing to, or null if the
* Uri is unsupported or pointed to a remote resource.
* @author paulburke
* @see #getPath(Context, Uri)
*/
public static File getFile(Context context, Uri uri) {
if (uri != null) {
String path = getPath(context, uri);
if (path != null && isLocal(path)) {
return new File(path);
}
}
return null;
}
/**
* Get the file size in a human-readable string.
*
* @param size
* @return
* @author paulburke
*/
public static String getReadableFileSize(int size) {
final int BYTES_IN_KILOBYTES = 1024;
final DecimalFormat dec = new DecimalFormat("###.#");
final String KILOBYTES = " KB";
final String MEGABYTES = " MB";
final String GIGABYTES = " GB";
float fileSize = 0;
String suffix = KILOBYTES;
if (size > BYTES_IN_KILOBYTES) {
fileSize = size / BYTES_IN_KILOBYTES;
if (fileSize > BYTES_IN_KILOBYTES) {
fileSize = fileSize / BYTES_IN_KILOBYTES;
if (fileSize > BYTES_IN_KILOBYTES) {
fileSize = fileSize / BYTES_IN_KILOBYTES;
suffix = GIGABYTES;
} else {
suffix = MEGABYTES;
}
}
}
return String.valueOf(dec.format(fileSize) + suffix);
}
/**
* Get the Intent for selecting content to be used in an Intent Chooser.
*
* @return The intent for opening a file with Intent.createChooser()
*/
public static Intent createGetContentIntent() {
// Implicitly allow the user to select a particular kind of data
final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// The MIME data type filter
intent.setType("*/*");
// Only return URIs that can be opened with ContentResolver
intent.addCategory(Intent.CATEGORY_OPENABLE);
return intent;
}
/**
* Creates View intent for given file
*
* @param file
* @return The intent for viewing file
*/
public static Intent getViewIntent(Context context, File file) {
//Uri uri = Uri.fromFile(file);
Uri uri = FileProvider.getUriForFile(context,
(context.getApplicationContext().getPackageName() + ".fileProvider"), file);
Intent intent = new Intent(Intent.ACTION_VIEW);
String url = file.toString();
if (url.contains(".doc") || url.contains(".docx")) {
// Word document
intent.setDataAndType(uri, "application/msword");
} else if (url.contains(".pdf")) {
// PDF file
intent.setDataAndType(uri, "application/pdf");
} else if (url.contains(".ppt") || url.contains(".pptx")) {
// Powerpoint file
intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
} else if (url.contains(".xls") || url.contains(".xlsx")) {
// Excel file
intent.setDataAndType(uri, "application/vnd.ms-excel");
} else if (url.contains(".zip") || url.contains(".rar")) {
// WAV audio file
intent.setDataAndType(uri, "application/x-wav");
} else if (url.contains(".rtf")) {
// RTF file
intent.setDataAndType(uri, "application/rtf");
} else if (url.contains(".wav") || url.contains(".mp3")) {
// WAV audio file
intent.setDataAndType(uri, "audio/x-wav");
} else if (url.contains(".gif")) {
// GIF file
intent.setDataAndType(uri, "image/gif");
} else if (url.contains(".jpg") || url.contains(".jpeg") || url.contains(".png")) {
// JPG file
intent.setDataAndType(uri, "image/jpeg");
} else if (url.contains(".txt")) {
// Text file
intent.setDataAndType(uri, "text/plain");
} else if (url.contains(".3gp") || url.contains(".mpg") || url.contains(".mpeg") || url.contains(".mpe") || url.contains(".mp4") || url.contains(".avi")) {
// Video files
intent.setDataAndType(uri, "video/*");
} else {
intent.setDataAndType(uri, "*/*");
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
return intent;
}
public static File getDownloadsDir() {
return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
}
public static File getDocumentCacheDir(@NonNull Context context) {
File dir = new File(context.getCacheDir(), DOCUMENTS_DIR);
if (!dir.exists()) {
dir.mkdirs();
}
logDir(context.getCacheDir());
logDir(dir);
return dir;
}
private static void logDir(File dir) {
if (!DEBUG) return;
Log.d(TAG, "Dir=" + dir);
File[] files = dir.listFiles();
for (File file : files) {
Log.d(TAG, "File=" + file.getPath());
}
}
@Nullable
public static File generateFileName(@Nullable String name, File directory) {
if (name == null) {
return null;
}
File file = new File(directory, name);
if (file.exists()) {
String fileName = name;
String extension = "";
int dotIndex = name.lastIndexOf('.');
if (dotIndex > 0) {
fileName = name.substring(0, dotIndex);
extension = name.substring(dotIndex);
}
int index = 0;
while (file.exists()) {
index++;
name = fileName + '(' + index + ')' + extension;
file = new File(directory, name);
}
}
try {
if (!file.createNewFile()) {
return null;
}
} catch (IOException e) {
Log.w(TAG, e);
return null;
}
logDir(directory);
return file;
}
private static void saveFileFromUri(Context context, Uri uri, String destinationPath) {
InputStream is = null;
BufferedOutputStream bos = null;
try {
is = context.getContentResolver().openInputStream(uri);
bos = new BufferedOutputStream(new FileOutputStream(destinationPath, false));
byte[] buf = new byte[1024];
is.read(buf);
do {
bos.write(buf);
} while (is.read(buf) != -1);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) is.close();
if (bos != null) bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static byte[] readBytesFromFile(String filePath) {
FileInputStream fileInputStream = null;
byte[] bytesArray = null;
try {
File file = new File(filePath);
bytesArray = new byte[(int) file.length()];
//read file into bytes[]
fileInputStream = new FileInputStream(file);
fileInputStream.read(bytesArray);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bytesArray;
}
public static File createTempImageFile(Context context, String fileName) throws IOException {
// Create an image file name
File storageDir = new File(context.getCacheDir(), DOCUMENTS_DIR);
return File.createTempFile(fileName, ".jpg", storageDir);
}
public static String getFileName(@NonNull Context context, Uri uri) {
String mimeType = context.getContentResolver().getType(uri);
String filename = null;
if (mimeType == null && context != null) {
String path = getPath(context, uri);
if (path == null) {
filename = getName(uri.toString());
} else {
File file = new File(path);
filename = file.getName();
}
} else {
Cursor returnCursor = context.getContentResolver().query(uri, null, null, null, null);
if (returnCursor != null) {
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
returnCursor.moveToFirst();
filename = returnCursor.getString(nameIndex);
returnCursor.close();
}
}
return filename;
}
public static String getName(String filename) {
if (filename == null) {
return null;
}
int index = filename.lastIndexOf('/');
return filename.substring(index + 1);
}
}
| [
"[email protected]"
]
| |
d32ee5c6b5bd47a539d110822173224fc99596a0 | 6cfcd43df00c6142d51af12992c6d3041ab7c453 | /src/test/java/io/github/richardstartin/rangeindex/GenericBaseRangeIndexTest.java | e59bbeaf8c97100b4d2a09fae9de19234c852e1f | [
"Apache-2.0"
]
| permissive | richardstartin/range-index | 42880934a495b45517a1990395137a70e3f984f0 | e6a526cf4d3ca4b383435864f400144868a936d3 | refs/heads/main | 2023-08-17T00:44:25.832221 | 2021-09-26T17:49:41 | 2021-09-26T17:51:26 | 398,568,710 | 3 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,024 | java | package io.github.richardstartin.rangeindex;
public abstract class GenericBaseRangeIndexTest extends AbstractIndexTest<GenericBaseRangeIndex> {
private final int base;
protected GenericBaseRangeIndexTest(int base) {
this.base = base;
}
@Override
Accumulator<GenericBaseRangeIndex> create() {
return GenericBaseRangeIndex.accumulator(base);
}
}
class GenericBase10RangeIndexTest extends GenericBaseRangeIndexTest {
public GenericBase10RangeIndexTest() {
super(10);
}
}
class GenericBase2RangeIndexTest extends GenericBaseRangeIndexTest {
public GenericBase2RangeIndexTest() {
super(2);
}
}
class GenericBase4RangeIndexTest extends GenericBaseRangeIndexTest {
public GenericBase4RangeIndexTest() {
super(4);
}
}
class GenericBase8RangeIndexTest extends GenericBaseRangeIndexTest {
public GenericBase8RangeIndexTest() {
super(8);
}
}
class GenericBase16RangeIndexTest extends GenericBaseRangeIndexTest {
public GenericBase16RangeIndexTest() {
super(16);
}
}
| [
"[email protected]"
]
| |
e518c0c9bd74f9c15afb0f42c26bfb8419890ad5 | fc6d6dcc160e6ccec7ab2e447e979c6e82fb6879 | /testnetty/src/main/java/simulateChat/chat/client/SimpleChatClientHandler.java | 5ab2c2b786d13eefdb233083ee26621ef071cd5e | []
| no_license | su-li/mytoolkit | 7db264d28fd5b3fe5476a4d63e66a040c9512fbc | eae526d902bd4d6a11833bea286cd9008cef9928 | refs/heads/master | 2021-09-07T21:47:20.359310 | 2018-03-01T13:37:36 | 2018-03-01T13:37:36 | 110,805,245 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 409 | java | package simulateChat.chat.client;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
/**
* Created by Administrator on 2017/6/12.
*/
public class SimpleChatClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
System.out.println(s);
}
} | [
"[email protected]"
]
| |
5bf6cbda798956df3a9963b6af6f297416cd8b88 | 51b8bce9beb106d8f082ba84e2341cbbd0edc1d3 | /app/src/main/java/com/example/yandexweather/ui/main/FragmentWeatherToday.java | 1ae2c7d626a6ed62aef269196c3281ee871eb15b | []
| no_license | Dimas038/WeatherApp | f685f86dfaec64e4064c10bb3ce5396cee5937bb | 6307143622ba43f883371d76a29949e0f851a83f | refs/heads/master | 2023-02-07T23:20:37.427705 | 2020-12-31T11:01:22 | 2020-12-31T11:01:22 | 261,788,155 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,949 | java | package com.example.yandexweather.ui.main;
import android.graphics.Color;
import android.graphics.drawable.PictureDrawable;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.arellomobile.mvp.presenter.InjectPresenter;
import com.arellomobile.mvp.presenter.ProvidePresenter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.example.yandexweather.App;
import com.example.yandexweather.R;
import com.example.yandexweather.main.FragmentWeatherTodayMvpPresenter;
import com.example.yandexweather.main.FragmentWeatherTodayMvpView;
import com.example.yandexweather.model.CoordinatesModel;
import com.example.yandexweather.model.DayModel;
import com.example.yandexweather.model.ForecastModel;
import com.example.yandexweather.retrofit.response.WeatherResponse;
import com.example.yandexweather.ui.base.fragment.BaseFragment;
import com.example.yandexweather.ui.common.BackButtonListener;
import com.example.yandexweather.ui.recyclerview.adapter.DayModelsAdapter;
import com.example.yandexweather.ui.recyclerview.adapter.HoursModelsAdapter;
import com.pnikosis.materialishprogress.ProgressWheel;
import java.util.List;
import javax.inject.Inject;
import butterknife.BindView;
import ru.terrakok.cicerone.Router;
public class FragmentWeatherToday extends BaseFragment implements FragmentWeatherTodayMvpView, BackButtonListener, AppBarLayout.OnOffsetChangedListener {
private static final int PERCENTAGE_TO_SHOW_IMAGE = 1;
@Inject
Router router;
@InjectPresenter
FragmentWeatherTodayMvpPresenter presenter;
// @BindView(R.id.content)
// View content;
@BindView(R.id.background)
ImageView background;
@BindView(R.id.textViewLocation)
TextView textViewLocation;
@BindView(R.id.weatherIcon)
ImageView weatherIcon;
@BindView(R.id.textViewCurrentTemp)
TextView textViewCurrentTemp;
// @BindView(R.id.progressWheel)
// ProgressWheel progressWheel;
@BindView(R.id.textViewDate)
TextView textViewDate;
@BindView(R.id.textViewSunrise)
TextView textViewSunrise;
@BindView(R.id.recyclerView)
RecyclerView recyclerView;
@BindView(R.id.scrollView)
NestedScrollView scrollView;
@BindView(R.id.linLayout)
LinearLayout linLayout;
@BindView(R.id.upperDivider)
View upperDivider;
@BindView(R.id.lowerDivider)
View lowerDivider;
@BindView(R.id.appbar)
AppBarLayout appbar;
private int mMaxScrollSize;
private boolean mIsImageHidden;
private RequestBuilder<PictureDrawable> requestBuilder;
public FragmentWeatherToday() {
super(true);
}
public static FragmentWeatherToday getNewInstance(InstantiateObject instantiateObject) {
FragmentWeatherToday fragment = new FragmentWeatherToday();
Bundle bundle = new Bundle();
bundle.putParcelable(INSTANTIATE_OBJECT, instantiateObject);
fragment.setArguments(bundle);
return fragment;
}
@ProvidePresenter
public FragmentWeatherTodayMvpPresenter createPresenter() {
return new FragmentWeatherTodayMvpPresenter(getCoordinatesModel(), getDayModel());
}
private CoordinatesModel getCoordinatesModel() {
return getInstantiateObject().getCoordinatesModel();
}
private DayModel getDayModel() {
return getInstantiateObject().getDayModel();
}
private InstantiateObject getInstantiateObject() {
return getArguments().getParcelable(INSTANTIATE_OBJECT);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
App.INSTANCE.getAppComponent().inject(this);
requestBuilder =
Glide.with(this)
.as(PictureDrawable.class);
}
@Override
public void onViewInflated(View view, @Nullable Bundle savedInstanceState) {
textViewLocation.setText(getCoordinatesModel().getTitle());
// progressWheel.setBarColor(Color.WHITE);
upperDivider.setVisibility(View.GONE);
lowerDivider.setVisibility(View.GONE);
appbar.addOnOffsetChangedListener(this);
}
@Override
public int onInflateLayout() {
return R.layout.fragment_weather_today;
}
@Override
public void onComplete(WeatherResponse weatherResponse) {
textViewCurrentTemp.setText(weatherResponse.getFact().getTemperature());
loadIcon(weatherResponse);
loadBackground(weatherResponse);
recyclerView.setHasFixedSize(true);
LinearLayoutManager layoutManager = new LinearLayoutManager(recyclerView.getContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(layoutManager);
HoursModelsAdapter adapter = new HoursModelsAdapter(recyclerView);
adapter.setModels(weatherResponse.getForecasts().get(0).getHours());
recyclerView.setAdapter(adapter);
// content.setVisibility(View.VISIBLE);
// progressWheel.setVisibility(View.GONE);
upperDivider.setVisibility(View.VISIBLE);
lowerDivider.setVisibility(View.VISIBLE);
List<ForecastModel> forecastModels = weatherResponse.getForecasts();
if (getDayModel().getId() == DayModelsAdapter.TYPE_TODAY) {
for (int i = 0; i < 6; i++)
forecastModels.remove(1);
}
textViewDate.setText(weatherResponse.getForecasts().get(0).getDateReverse() + getString(R.string.today));
textViewSunrise.setText(getString(R.string.sunrise_is_in) + weatherResponse.getForecasts().get(0).getSunrise());
for (int i = 0; i < forecastModels.size(); i++) {
LayoutInflater ltInflater = getLayoutInflater();
View item = ltInflater.inflate(R.layout.item_weather_today, linLayout, false);
TextView textViewNight = item.findViewById(R.id.textViewNightDefinition);
TextView textViewMorning = item.findViewById(R.id.textViewMorningDefinition);
TextView textViewDay = item.findViewById(R.id.textViewDayDefinition);
TextView textViewEvening = item.findViewById(R.id.textViewEveningDefinition);
if (forecastModels.get(i).getParts() != null && forecastModels.get(i).getParts().getNight() != null)
textViewNight.setText(forecastModels.get(i).getParts().getNight().getDayPartForecast() + "\n");
else textViewNight.setText("");
if (forecastModels.get(i).getParts() != null && forecastModels.get(i).getParts().getMorning() != null)
textViewMorning.setText(forecastModels.get(i).getParts().getMorning().getDayPartForecast() + "\n");
else textViewMorning.setText("");
if (forecastModels.get(i).getParts() != null && forecastModels.get(i).getParts().getDay() != null)
textViewDay.setText(forecastModels.get(i).getParts().getDay().getDayPartForecast() + "\n");
else textViewDay.setText("");
if (forecastModels.get(i).getParts() != null && forecastModels.get(i).getParts().getEvening() != null)
textViewEvening.setText(forecastModels.get(i).getParts().getEvening().getDayPartForecast());
else textViewEvening.setText("");
linLayout.addView(item);
}
}
private void loadBackground(WeatherResponse weatherResponse) {
Integer backgroundResourceId = weatherResponse.getBackground();
if (weatherResponse.getBackground() != null)
Glide.with(this).load(backgroundResourceId).into(background);
}
public void loadIcon(WeatherResponse weatherResponse) {
requestBuilder.load(weatherResponse.getFact().getIcon()).into(weatherIcon);
}
@Override
public void onError() {
router.exitWithMessage("ERROR");
}
@Override
public void onDestroyView() {
super.onDestroyView();
}
@Override
public boolean onBackPressed() {
if (router != null) router.exit();
return true;
}
@Override
public void onOffsetChanged(AppBarLayout appbar, int i) {
if (mMaxScrollSize == 0)
mMaxScrollSize = appbar.getTotalScrollRange();
int currentScrollPercentage = (Math.abs(i)) * 100 / mMaxScrollSize;
if (currentScrollPercentage >= PERCENTAGE_TO_SHOW_IMAGE) {
if (!mIsImageHidden) {
mIsImageHidden = true;
ViewCompat.animate(textViewCurrentTemp).alpha(0);
ViewCompat.animate(textViewDate).alpha(0);
ViewCompat.animate(textViewSunrise).alpha(0);
}
}
if (currentScrollPercentage < PERCENTAGE_TO_SHOW_IMAGE) {
if (mIsImageHidden) {
mIsImageHidden = false;
ViewCompat.animate(textViewCurrentTemp).alpha(1);
ViewCompat.animate(textViewDate).alpha(1);
ViewCompat.animate(textViewSunrise).alpha(1);
}
}
}
public static class InstantiateObject implements Parcelable {
public static final Creator<InstantiateObject> CREATOR = new Creator<InstantiateObject>() {
@Override
public InstantiateObject createFromParcel(Parcel in) {
return new InstantiateObject(in);
}
@Override
public InstantiateObject[] newArray(int size) {
return new InstantiateObject[size];
}
};
private final CoordinatesModel coordinatesModel;
private final DayModel dayModel;
public InstantiateObject(CoordinatesModel coordinatesModel, DayModel dayModel) {
this.coordinatesModel = coordinatesModel;
this.dayModel = dayModel;
}
protected InstantiateObject(Parcel in) {
coordinatesModel = in.readParcelable(CoordinatesModel.class.getClassLoader());
dayModel = in.readParcelable(DayModel.class.getClassLoader());
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(coordinatesModel, flags);
dest.writeParcelable(dayModel, flags);
}
@Override
public int describeContents() {
return 0;
}
public CoordinatesModel getCoordinatesModel() {
return coordinatesModel;
}
public DayModel getDayModel() {
return dayModel;
}
}
}
| [
"[email protected]"
]
| |
4c0b41bc9b1817e253f22c68c607b7dca64caf27 | 2ac666ef1a1e458ad6d66bd22dd4cd012462efc0 | /src/main/java/com/icloud/itfukui0922/util/DiceUtil.java | 5399c025526b85b981e5dcf79ccfec885929a655 | []
| no_license | LongDistanceRider/AITWolfAgent2018 | 03acfd34f0f3cf37a895dcf27187d57c00acfe56 | 17c359bfb3680b8844bf291f40251242e690948a | refs/heads/master | 2021-01-20T13:06:19.325830 | 2018-06-16T10:53:47 | 2018-06-16T10:53:47 | 101,735,145 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 293 | java | package com.icloud.itfukui0922.util;
public class DiceUtil {
/**
* booleanをintに変換
* @param boo
* @return
*/
public static int convertInteger (boolean boo) {
if (boo) {
return 1;
} else {
return 0;
}
}
}
| [
""
]
| |
8b5205c05d06bc2207875de1bcd3139180bc0047 | 761c40ce8dc5095dd44a36acbd1584c5b3dbdff6 | /src/main/java/ru/reksoft/demo/dto/UserDTO.java | fa1ac05f7f1a1b1ee2f02b1b5ab1270647101835 | []
| no_license | 4val0v/REKSOFT-DEMO | b34cd8d2980c394f674c6db77dfce714b8fe084e | 78c9576eab8e0ef8bca5f339dc8bc6704c52a6a8 | refs/heads/master | 2020-04-07T06:49:59.642919 | 2018-09-03T12:48:41 | 2018-09-03T12:48:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,033 | java | package ru.reksoft.demo.dto;
import ru.reksoft.demo.dto.generic.AbstractIdentifiedDTO;
import ru.reksoft.demo.dto.validation.annotations.Phone;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Null;
import javax.validation.constraints.Size;
public class UserDTO extends AbstractIdentifiedDTO {
@NotNull(groups = IdCheck.class)
@Min(value = 1, groups = IdCheck.class)
private Integer id;
@NotNull(groups = FieldCheck.class)
@Size(min = 4, max = 45, groups = FieldCheck.class)
private String login;
@NotNull(groups = FieldCheck.class)
@Size(min = 4, max = 90, groups = FieldCheck.class)
private String password;
@NotNull(groups = FieldCheck.class)
@Size(min = 1, max = 45, groups = FieldCheck.class)
private String name;
@NotNull(groups = FieldCheck.class)
@Size(min = 1, max = 45, groups = FieldCheck.class)
private String surname;
@NotNull(groups = FieldCheck.class)
@Size(min = 1, max = 45, groups = FieldCheck.class)
private String patronymic;
@NotNull(groups = FieldCheck.class)
@Size(min = 1, max = 90, groups = FieldCheck.class)
private String address;
@NotNull(groups = FieldCheck.class)
@Phone(groups = FieldCheck.class)
private String phone;
@Null(groups = FieldCheck.class)
private UserRoleDTO role;
@Override
public Integer getId() {
return id;
}
@Override
public UserDTO setId(Integer id) {
this.id = id;
return this;
}
public String getLogin() {
return login;
}
public UserDTO setLogin(String login) {
this.login = login;
return this;
}
public String getPassword() {
return password;
}
public UserDTO setPassword(String password) {
this.password = password;
return this;
}
public String getName() {
return name;
}
public UserDTO setName(String name) {
this.name = name;
return this;
}
public String getSurname() {
return surname;
}
public UserDTO setSurname(String surname) {
this.surname = surname;
return this;
}
public String getPatronymic() {
return patronymic;
}
public UserDTO setPatronymic(String patronymic) {
this.patronymic = patronymic;
return this;
}
public String getAddress() {
return address;
}
public UserDTO setAddress(String address) {
this.address = address;
return this;
}
public String getPhone() {
return phone;
}
public UserDTO setPhone(String phone) {
this.phone = phone;
return this;
}
public UserRoleDTO getRole() {
return role;
}
public UserDTO setRole(UserRoleDTO role) {
this.role = role;
return this;
}
public interface IdCheck {
}
public interface FieldCheck extends UserRoleDTO.IdCheck {
}
}
| [
"[email protected]"
]
| |
6c2a9024135782c7d1236cb0f0e656121c44015f | 3f4071b371e3867fc3d97d674450e13f4e8ac271 | /spds-benchmark/spds-storm/spds-storm-gira-topology/src/main/java/org/isel/thesis/impads/storm/topology/bolts/join/ObservableJoinBolt.java | 4466b89fa1d8ff1c56bec6297bba60219fb6139e | [
"Apache-2.0"
]
| permissive | YutingYao/infrastructure-and-programming-models-for-stream-data-analysis | 43330e137030af7abf2234357d5aa02642a784c8 | e217333edeb7c35bbc79f1fa06e4b1a5e75e7c73 | refs/heads/master | 2023-06-18T18:52:20.211536 | 2021-07-06T22:49:46 | 2021-07-06T22:49:46 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,686 | java | package org.isel.thesis.impads.storm.topology.bolts.join;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseWindowedBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;
import org.apache.storm.windowing.TimestampExtractor;
import org.apache.storm.windowing.TupleWindow;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class ObservableJoinBolt<T1, T2, K> extends BaseWindowedBolt {
private final JoinSelector joinSelectorType;
private final String fromStream;
private final KeySelector<T1, K> fromStreamKeySelector;
private final TupleFieldSelector<T1> fromStreamTupleFieldSelector;
private final String joinStream;
private final KeySelector<T2, K> joinStreamKeySelector;
private final TupleFieldSelector<T2> joinStreamTupleFieldSelector;
private final JoinType joinType;
private final JoinFunction<T1, T2, Values> joinFunction;
private final String[] outputFields;
private OutputCollector collector;
public ObservableJoinBolt(JoinSelector joinSelectorType
, String fromStream
, KeySelector<T1, K> fromStreamKeySelector
, TupleFieldSelector<T1> fromStreamTupleFieldSelector
, String joinStream
, KeySelector<T2, K> joinStreamKeySelector
, TupleFieldSelector<T2> joinStreamTupleFieldSelector
, JoinType joinType
, JoinFunction<T1, T2, Values> joinFunction
, String[] outputFields) {
this.joinSelectorType = joinSelectorType;
this.fromStream = fromStream;
this.fromStreamKeySelector = fromStreamKeySelector;
this.fromStreamTupleFieldSelector = fromStreamTupleFieldSelector;
this.joinStream = joinStream;
this.joinStreamKeySelector = joinStreamKeySelector;
this.joinStreamTupleFieldSelector = joinStreamTupleFieldSelector;
this.joinType = joinType;
this.joinFunction = joinFunction;
this.outputFields = outputFields;
}
@Override
public void prepare(Map<String, Object> topoConf, TopologyContext context, OutputCollector collector) {
this.collector = collector;
}
@Override
public void execute(TupleWindow inputWindow) {
List<Tuple> currentWindow = inputWindow.get();
List<Values> joinResult = hashJoin(currentWindow);
for (Values result : joinResult) {
collector.emit(result);
}
}
protected List<Values> hashJoin(List<Tuple> tuples) {
List<T1> fromInputs = new LinkedList<>();
List<T2> joinInputs = new LinkedList<>();
for (Tuple tuple : tuples) {
String streamId = getStreamSelector(tuple);
if (!streamId.equals(fromStream)) {
joinInputs.add(joinStreamTupleFieldSelector.getSelector().apply(tuple));
}
else {
fromInputs.add(fromStreamTupleFieldSelector.getSelector().apply(tuple));
}
}
return doJoin(fromInputs, joinInputs);
}
private String getStreamSelector(Tuple tuple) {
switch (joinSelectorType) {
case STREAM:
return tuple.getSourceStreamId();
case SOURCE:
return tuple.getSourceComponent();
default:
throw new RuntimeException(joinSelectorType + " stream selector type not yet supported");
}
}
protected List<Values> doJoin(List<T1> fromInputs
, List<T2> joinInputs) {
switch (joinType) {
case INNER:
return doInnerJoin(fromInputs, joinInputs);
case LEFT:
case RIGHT:
case OUTER:
default:
throw new RuntimeException("Unsupported join type : " + joinType);
}
}
// inner join - core implementation
protected List<Values> doInnerJoin(List<T1> fromInputs
, List<T2> joinInputs) {
final List<Values> output = new LinkedList<>();
for (T1 from : fromInputs) {
for (T2 join : joinInputs) {
K fromKey = fromStreamKeySelector.getSelector().apply(from);
K joinKey = joinStreamKeySelector.getSelector().apply(join);
if (fromKey.equals(joinKey)) {
output.add(joinFunction.apply(from, join));
}
}
}
return output;
}
@Override
public ObservableJoinBolt withWindow(Count windowLength, Count slidingInterval) {
return (ObservableJoinBolt) super.withWindow(windowLength, slidingInterval);
}
@Override
public ObservableJoinBolt withWindow(Count windowLength, Duration slidingInterval) {
return (ObservableJoinBolt) super.withWindow(windowLength, slidingInterval);
}
@Override
public ObservableJoinBolt withWindow(Duration windowLength, Count slidingInterval) {
return (ObservableJoinBolt) super.withWindow(windowLength, slidingInterval);
}
@Override
public ObservableJoinBolt withWindow(Duration windowLength, Duration slidingInterval) {
return (ObservableJoinBolt) super.withWindow(windowLength, slidingInterval);
}
@Override
public ObservableJoinBolt withWindow(Count windowLength) {
return (ObservableJoinBolt) super.withWindow(windowLength);
}
@Override
public ObservableJoinBolt withWindow(Duration windowLength) {
return (ObservableJoinBolt) super.withWindow(windowLength);
}
@Override
public ObservableJoinBolt withTumblingWindow(Count count) {
return (ObservableJoinBolt) super.withTumblingWindow(count);
}
@Override
public ObservableJoinBolt withTumblingWindow(Duration duration) {
return (ObservableJoinBolt) super.withTumblingWindow(duration);
}
@Override
public ObservableJoinBolt withTimestampField(String fieldName) {
return (ObservableJoinBolt) super.withTimestampField(fieldName);
}
@Override
public ObservableJoinBolt withTimestampExtractor(TimestampExtractor timestampExtractor) {
return (ObservableJoinBolt) super.withTimestampExtractor(timestampExtractor);
}
@Override
public ObservableJoinBolt withLateTupleStream(String streamId) {
return (ObservableJoinBolt) super.withLateTupleStream(streamId);
}
@Override
public ObservableJoinBolt withLag(Duration duration) {
return (ObservableJoinBolt) super.withLag(duration);
}
@Override
public ObservableJoinBolt withWatermarkInterval(Duration interval) {
return (ObservableJoinBolt) super.withWatermarkInterval(interval);
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields(outputFields));
}
public static class JoinBuilder<T1, T2, K> {
private final JoinSelector joinSelectorType;
private final String fromStream;
private final KeySelector<T1, K> fromStreamKeySelector;
private final TupleFieldSelector<T1> fromStreamTupleFieldSelector;
private String joinStream;
private KeySelector<T2, K> joinStreamKeySelector;
private TupleFieldSelector<T2> joinStreamTupleFieldSelector;
private JoinType joinType;
private JoinFunction<T1, T2, Values> joinFunction;
private String[] outputFields;
private JoinBuilder(JoinSelector joinSelectorType
, String fromStream
, KeySelector<T1, K> fromStreamKeySelector
, TupleFieldSelector<T1> fromStreamTupleFieldSelector) {
this.joinSelectorType = joinSelectorType;
this.fromStream = fromStream;
this.fromStreamKeySelector = fromStreamKeySelector;
this.fromStreamTupleFieldSelector = fromStreamTupleFieldSelector;
}
public static <T1, T2, K> JoinBuilder<T1, T2, K> from(String fromStream
, KeySelector<T1, K> fromStreamKeySelector
, TupleFieldSelector<T1> fromStreamTupleFieldSelector) {
return new JoinBuilder<>(JoinSelector.SOURCE, fromStream, fromStreamKeySelector, fromStreamTupleFieldSelector);
}
public JoinBuilder<T1, T2, K> join(String joinStream
, KeySelector<T2, K> joinStreamKeySelector
, TupleFieldSelector<T2> joinStreamTupleFieldSelector) {
this.joinStream = joinStream;
this.joinStreamKeySelector = joinStreamKeySelector;
this.joinStreamTupleFieldSelector = joinStreamTupleFieldSelector;
this.joinType = JoinType.INNER;
return this;
}
public JoinBuilder<T1, T2, K> apply(JoinFunction<T1, T2, Values> joinFunction) {
this.joinFunction = joinFunction;
return this;
}
public JoinBuilder<T1, T2, K> outputFields(String... outputFields) {
this.outputFields = outputFields;
return this;
}
public ObservableJoinBolt<T1, T2, K> build() {
return new ObservableJoinBolt<>(joinSelectorType
, fromStream
, fromStreamKeySelector
, fromStreamTupleFieldSelector
, joinStream
, joinStreamKeySelector
, joinStreamTupleFieldSelector
, joinType
, joinFunction
, outputFields);
}
}
}
| [
"[email protected]"
]
| |
4de1ce363a8c50c42945cd3a341f26b3ed721ab1 | 9a4d29a12cd55eb615e281cf80c10cb840fbe2de | /src/main/java/controllers/GameOverDialogController.java | 96d018636b3d4c8e9d0e111f471f034cac5b86ab | [
"MIT"
]
| permissive | TCT2001/Bomberman_MainVersion | aeef82fbb3a8edb9e144e34e29d56286d3b33f7b | 62a92eae801bf40425f203c90d61ae4db63b0efa | refs/heads/main | 2023-01-12T06:50:17.448276 | 2020-11-09T05:18:17 | 2020-11-09T05:18:17 | 311,568,883 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 443 | java | package controllers;
import javafx.fxml.FXML;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import sample.Main;
/**
* Created by maemr on 13.06.2016.
*/
public class GameOverDialogController {
@FXML
VBox rootBox;
@FXML
public void goHome() {
Main.getMainWindow().setScene(Main.getGameInterface().getMainMenu());
((Stage) rootBox.getScene().getWindow()).close();
}
}
| [
"[email protected]"
]
| |
5645f38fb154279f1461ba0dbda0ce9ff69547e6 | fee36ba1d4fd00180de95287818416f1be54aa04 | /Java/src/baekjoon/Main_constructor_jw.java | 793d514fdbf960b594ac404c347988503b5022eb | []
| no_license | JungWonHong/Spring | 721f53f48ca1795198ae87211cee6e899e32d706 | bfdaaeb286fb9b1770db68f5c39f5d86b19eceb6 | refs/heads/master | 2020-04-16T13:40:14.444198 | 2019-01-14T09:56:16 | 2019-01-14T09:56:16 | 165,637,644 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,019 | java | package baekjoon;
public class Main_constructor_jw {
public static void main(String[] args) {
int[] N = new int[10000];
int[] n = new int[10000];
for (int i = 0; i < N.length; i++) {
N[i] = i + 1;
n[i] = d(i + 1);
}
for (int i = 0; i < N.length; i++) {
int cnt = 0;
for (int j = 0; j < n.length; j++) {
if (N[i] == n[j])
cnt++;
}
if (cnt == 0)
System.out.println(N[i]);
}
}
static int d(int n) {
int result = 0;
if (n >= 10000) {
result = n + n / 10000 + (n % 10000) / 1000 + ((n % 10000) % 1000) / 100 + (((n % 10000) % 1000) % 100) / 10
+ (((n % 10000) % 1000) % 100) % 10;
} else if (n >= 1000 && n < 10000) {
result = n + n / 1000 + (n % 1000) / 100 + ((n % 1000) % 100) / 10 + ((n % 1000) % 100) % 10;
} else if (n >= 100 && n < 1000) {
result = n + n / 100 + (n % 100) / 10 + (n % 100) % 10;
} else if (n >= 10 && n < 100) {
result = n + n / 10 + n % 10;
} else if (n > 0 && n < 10) {
result = n + n;
}
return result;
}
}
| [
"[email protected]"
]
| |
8f734ad4c4ce19aaa9462436acdf937ad0c515b0 | df7966fdc0684a8d675efb555afeb055afa7a259 | /arch-pattern/dci/src/main/java/manfred/end/dci/domain/data/BalanceData.java | f7577b8562ee1128a79d9989ff282a5c7e1bc509 | [
"Apache-2.0"
]
| permissive | manfredma/exercises | 90760db34c33d6d38d92edf1377e54e8029bef72 | f487ece7b0cd761e8afb14ae8be0b1b668f97d8c | refs/heads/master | 2023-09-06T04:15:15.960344 | 2023-08-25T06:15:46 | 2023-08-25T06:15:46 | 176,470,365 | 3 | 0 | null | 2021-04-08T07:11:50 | 2019-03-19T09:07:26 | Java | UTF-8 | Java | false | false | 2,054 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package manfred.end.dci.domain.data;
import org.apache.polygene.api.common.UseDefaults;
import org.apache.polygene.api.injection.scope.State;
import org.apache.polygene.api.mixin.Mixins;
import org.apache.polygene.api.property.Property;
import org.apache.polygene.library.constraints.annotation.GreaterThan;
/**
* Maintain a balance for an account, of any type. Methods are in past tense,
* and are considered events. Only minimal sanity checks are performed.
* The roles invoking these methods decide if it's ok to perform the change or not.
*/
@Mixins(BalanceData.Mixin.class)
public interface BalanceData {
void increasedBalance(@GreaterThan(0) Integer amount);
void decreasedBalance(@GreaterThan(0) Integer amount);
Integer getBalance();
// Default implementation
class Mixin implements BalanceData {
@State
@UseDefaults
Property<Integer> balance;
public void increasedBalance(Integer amount) {
balance.set(balance.get() + amount);
}
public void decreasedBalance(Integer amount) {
balance.set(balance.get() - amount);
}
public Integer getBalance() {
return balance.get();
}
}
}
| [
"[email protected]"
]
| |
013bf533796cf1a944d0d540ba6db5c526676f0d | f35d4f4c2f106c25059eb023d20c0033cf501494 | /app/src/main/java/com/seabreeze/life/video/model/SwitchVideoModel.java | ca0bffbc00d2a62266f0656478c6cda66e41e339 | []
| no_license | milanxiaotiejiang/Life | 3448ab020cad46b7fb90e7ae21534df17af6d6f4 | 7cd1083054a6b34d9b09456ad558eb5c4de00b33 | refs/heads/master | 2020-03-19T13:20:14.675377 | 2018-07-19T08:55:54 | 2018-07-19T08:55:54 | 136,574,084 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 569 | java | package com.seabreeze.life.video.model;
public class SwitchVideoModel {
private String name;
private String url;
public SwitchVideoModel(String name, String url) {
this.name = name;
this.url = url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public String toString() {
return this.name;
}
}
| [
"[email protected]"
]
| |
ce4329d37be5577b4049d83db53729dfad9b6a44 | e75ec8ac21a8ab5c56666daff7b29b904abaad2c | /DataStructureAndAlgorithm/DataStructure/LineList/src/main/java/com/clguo/maintest/PrintN.java | 95a6f58c932bdfa252d784da67db6dd884b7ee7b | []
| no_license | cunleiguo/Replay | 50d637b1cb68d1a310f9361edfbede1586136dff | dceb081d7d6d96fe7240f03124ce63f10a1c5060 | refs/heads/master | 2023-06-03T16:03:54.270243 | 2021-06-14T10:55:18 | 2021-06-14T10:55:18 | 360,573,732 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 648 | java | package com.clguo.maintest;
public class PrintN {
public static void main(String[] args) {
long starTime = System.currentTimeMillis();
print2(20000);
//print1(100000);
long endTime = System.currentTimeMillis();
System.out.println("耗时:" + (endTime - starTime) + "hao秒");
}
public static void print1(int N) {
for (int i = 0; i <= N; i++) {
System.out.println(i);
}
}
public static void print2(int N) {
if (N != 0) {
print2(N -1);
System.out.println("============");
System.out.print(N);
}
}
}
| [
"[email protected]"
]
| |
8f8353e028a60a13a478705b020bbb4681136f0a | 352d5526ff9ff9f0fcd2564d0f72691ccdc71d92 | /demo25/feign-consumer/src/main/java/com/wasu/demo25/service/UserServiceFallback.java | cb54bea4238399c52d6f7e971aaa29c350c8ce18 | [
"MIT"
]
| permissive | lg5689134/SpringAll-1 | 7ab5d924932a902f558338d833907bdef60c34ff | f5f3b60b3ddd529cfcff9f959fe755bde45fefe4 | refs/heads/master | 2023-08-16T00:34:00.223070 | 2021-09-14T01:47:37 | 2021-09-14T01:47:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 785 | java | package com.wasu.demo25.service;
import com.wasu.demo25.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class UserServiceFallback implements UserService{
private Logger log = LoggerFactory.getLogger(this.getClass());
@Override
public User get(Long id) {
return new User(-1L, "fallback", "123456");
}
@Override
public List<User> get() {
return null;
}
@Override
public void add(User user) {
log.info("test fallback");
}
@Override
public void update(User user) {
log.info("test fallback");
}
@Override
public void delete(Long id) {
log.info("test fallback");
}
}
| [
"[email protected]"
]
| |
64d11e0a23392b3b1bd18b0929f641545c3dea23 | db2cd2a4803e546d35d5df2a75b7deb09ffadc01 | /nemo-tfl-common/src/test/java/com/novacroft/nemo/tfl/common/application_service/impl/RefundSelectListServiceTest.java | 7dc5bbe2e81ac834c2b57b87bf3bd22f4cf3e094 | []
| no_license | balamurugan678/nemo | 66d0d6f7062e340ca8c559346e163565c2628814 | 1319daafa5dc25409ae1a1872b1ba9b14e5a297e | refs/heads/master | 2021-01-19T17:47:22.002884 | 2015-06-18T12:03:43 | 2015-06-18T12:03:43 | 37,656,983 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 7,006 | java | package com.novacroft.nemo.tfl.common.application_service.impl;
import static com.novacroft.nemo.tfl.common.constant.GoodwillReasonType.OYSTER;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import com.novacroft.nemo.common.application_service.CountrySelectListService;
import com.novacroft.nemo.common.application_service.SelectListService;
import com.novacroft.nemo.test_support.SelectListTestUtil;
import com.novacroft.nemo.tfl.common.application_service.BackdatedRefundReasonService;
import com.novacroft.nemo.tfl.common.application_service.GoodwillService;
import com.novacroft.nemo.tfl.common.application_service.LocationSelectListService;
import com.novacroft.nemo.tfl.common.application_service.ProductService;
import com.novacroft.nemo.tfl.common.constant.PageAttribute;
import com.novacroft.nemo.tfl.common.data_service.ProductDataService;
/**
* Unit tests for RefundSelectListService
*/
public class RefundSelectListServiceTest {
private RefundSelectListServiceImpl service;
private SelectListService mockSelectListService;
private ProductDataService mockProductDataService;
private LocationSelectListService mockLocationSelectListService;
private GoodwillService mockGoodwillService;
private CountrySelectListService mockCountrySelectListService;
private BackdatedRefundReasonService mockBackdatedRefundreasonService;
private ProductService mockProductService;
private final Model model = new ExtendedModelMap();
@Before
public void setUp() throws Exception {
service = new RefundSelectListServiceImpl();
mockSelectListService = mock(SelectListService.class);
mockProductDataService = mock(ProductDataService.class);
mockLocationSelectListService = mock(LocationSelectListService.class);
mockGoodwillService = mock(GoodwillService.class);
mockBackdatedRefundreasonService = mock(BackdatedRefundReasonService.class);
mockCountrySelectListService = mock(CountrySelectListService.class);
mockProductService = mock(ProductServiceImpl.class);
ReflectionTestUtils.setField(service, "selectListService", mockSelectListService);
ReflectionTestUtils.setField(service, "productDataService", mockProductDataService);
ReflectionTestUtils.setField(service, "locationSelectListService", mockLocationSelectListService);
ReflectionTestUtils.setField(service, "goodwillService", mockGoodwillService);
ReflectionTestUtils.setField(service, "backdatedRefundreasonService", mockBackdatedRefundreasonService);
service.countrySelectListService = mockCountrySelectListService;
service.productService = mockProductService;
when(mockSelectListService.getSelectList(anyString())).thenReturn(SelectListTestUtil.getTestSelectListDTO());
when(mockLocationSelectListService.getLocationSelectList()).thenReturn(SelectListTestUtil.getTestSelectListDTO());
when(mockGoodwillService.getGoodwillRefundTypes(OYSTER.code())).thenReturn(SelectListTestUtil.getTestSelectListDTO());
when(mockGoodwillService.getGoodwillRefundExtraValidationMessages(OYSTER.code())).thenReturn("");
when(mockBackdatedRefundreasonService.getBackdatedRefundTypes()).thenReturn(SelectListTestUtil.getTestSelectListDTO());
when(mockProductService.getPassengerTypeList()).thenReturn(SelectListTestUtil.getTestSelectListDTO());
}
@Test
public void getSelectListModelShouldContainModelAttributes() {
service.getSelectListModel(model);
model.containsAttribute(PageAttribute.REFUND_CALCULATION_BASIS);
model.containsAttribute(PageAttribute.TRAVEL_CARD_TYPES);
model.containsAttribute(PageAttribute.TRAVEL_CARD_ZONES);
model.containsAttribute(PageAttribute.TRAVEL_CARD_RATES);
model.containsAttribute(PageAttribute.GOODWILL_REFUND_TYPES);
model.containsAttribute(PageAttribute.GOODWILL_REFUND_EXTRA_VALIDATION_MESSAGES);
model.containsAttribute(PageAttribute.BACKDATED_REFUND_TYPES);
model.containsAttribute(PageAttribute.PAYMENT_TYPE);
model.containsAttribute(PageAttribute.FIELD_SELECT_PICKUP_STATION);
}
@Test
public void getStandaloneGoodwillSelectListModelShouldContainModelAttributes() {
service.getStandaloneGoodwillSelectListModel(model);
model.containsAttribute(PageAttribute.GOODWILL_REFUND_TYPES);
model.containsAttribute(PageAttribute.GOODWILL_REFUND_EXTRA_VALIDATION_MESSAGES);
model.containsAttribute(PageAttribute.PAYMENT_TYPE);
model.containsAttribute(PageAttribute.FIELD_SELECT_PICKUP_STATION);
}
@Test
public void getAnonymousGoodwillSelectListModelShouldContainModelAttributes() {
service.getAnonymousGoodwillSelectListModel(model);
model.containsAttribute(PageAttribute.GOODWILL_REFUND_TYPES);
model.containsAttribute(PageAttribute.GOODWILL_REFUND_EXTRA_VALIDATION_MESSAGES);
model.containsAttribute(PageAttribute.PAYMENT_TYPE);
model.containsAttribute(PageAttribute.FIELD_SELECT_PICKUP_STATION);
}
@Test
public void populateRefundCalculationBasisSelectListShouldContainRefundCalculationBasis() {
service.populateRefundCalculationBasisSelectList(model);
model.containsAttribute(PageAttribute.REFUND_CALCULATION_BASIS);
}
@Test
public void populateStationSelectListShouldContainFieldSelectPickupStation() {
service.populateStationSelectList(model);
model.containsAttribute(PageAttribute.FIELD_SELECT_PICKUP_STATION);
}
@Test
public void populateTravelCardTypesSelectListShouldContainTravelCardTypes() {
service.populateTravelCardTypesSelectList(model);
model.containsAttribute(PageAttribute.TRAVEL_CARD_TYPES);
}
@Test
public void populateTravelCardZonesSelectListShouldContainTravelCardZones() {
service.populateTravelCardZonesSelectList(model);
model.containsAttribute(PageAttribute.TRAVEL_CARD_ZONES);
}
@Test
public void populateTravelCardRatesSelectListShouldContainTravelCardRates() {
service.populateTravelCardRatesSelectList(model);
model.containsAttribute(PageAttribute.TRAVEL_CARD_RATES);
}
@Test
public void populateGoodwillRefundTypesShouldContainGoodwillRefundTypesAndGoodwillRefundExtraValidationMessages() {
service.populateGoodwillRefundTypes(model, OYSTER.code());
model.containsAttribute(PageAttribute.GOODWILL_REFUND_TYPES);
model.containsAttribute(PageAttribute.GOODWILL_REFUND_EXTRA_VALIDATION_MESSAGES);
}
@Test
public void populateBackdatedRefundTypesShouldContainBackdatedRefundTypes() {
service.populateBackdatedRefundTypes(model);
model.containsAttribute(PageAttribute.BACKDATED_REFUND_TYPES);
}
@Test
public void populatePaymentTypesShouldContainPaymentType() {
service.populatePaymentTypes(model);
model.containsAttribute(PageAttribute.PAYMENT_TYPE);
}
}
| [
"[email protected]"
]
| |
01c717595b8106922af249a755117232de1be9eb | 18ad26cf66a101b3094498e08658bc6c5d336128 | /app/src/main/java/com/hitstreamr/hitstreamrbeta/CommentReplyAdapter.java | cf5c33ae63359e1383a280b953cb0eb2adfce378 | []
| no_license | chgmxx/BETA-app | 0a81d9828905349f8a7e5f80c433c8081838e387 | c12f2667e47d825eb7e229ff168fecf946e6f005 | refs/heads/master | 2022-02-18T23:19:41.912516 | 2019-09-10T19:49:19 | 2019-09-10T19:49:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,073 | java | package com.hitstreamr.hitstreamrbeta;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import de.hdodenhof.circleimageview.CircleImageView;
public class CommentReplyAdapter extends RecyclerView.Adapter<CommentReplyAdapter.ReplyHolder> {
private List<Comment> replyList;
/**
* Constructor
*/
public CommentReplyAdapter(List<Comment> replyList) { this.replyList = replyList; }
@Override
public void onBindViewHolder(@NonNull ReplyHolder holder, int position) {
holder.username.setText(replyList.get(position).getUsername());
holder.message.setText(replyList.get(position).getMessage());
// Set the profile picture
FirebaseStorage.getInstance().getReference("profilePictures").child(replyList.get(position).getUserID())
.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
if (uri != null) {
Glide.with(holder.circleImageView.getContext()).load(uri).into(holder.circleImageView);
}
}
});
// Set the timestamp difference
String timestampDifference = getTimestampDifference(replyList.get(position));
if (!timestampDifference.equals("0")) {
// TODO: if needed, add more detailed time difference
holder.replyTimeStamp.setText(timestampDifference + "d");
} else {
holder.replyTimeStamp.setText("today");
}
}
@NonNull
@Override
public ReplyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.video_comment_reply_layout, parent, false);
return new ReplyHolder(itemView);
}
@Override
public int getItemCount() {
if (replyList != null) {
return replyList.size();
}
return 0;
}
/**
* Reply Holder - Inner Class
*/
public class ReplyHolder extends RecyclerView.ViewHolder {
public TextView username, message, replyTimeStamp;
public CircleImageView circleImageView;
public ReplyHolder(View itemView) {
super(itemView);
username = itemView.findViewById(R.id.username_comment_reply);
message = itemView.findViewById(R.id.message_comment_reply);
circleImageView = itemView.findViewById(R.id.profilePicture_commentReply);
replyTimeStamp = itemView.findViewById(R.id.replyTimeStamp);
}
}
/**
* Calculate the time difference between when a reply is posted and the present time.
* @return the time difference
*/
private String getTimestampDifference(Comment comment) {
String difference = "";
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
Date today = c.getTime();
sdf.format(today);
Date timestamp;
final String photoTimestamp = comment.getTimePosted();
if (photoTimestamp != null) {
try {
timestamp = sdf.parse(photoTimestamp);
difference = String.valueOf(Math.round(((today.getTime() - timestamp.getTime()) / 1000 / 60 / 60 / 24)));
} catch (ParseException e) {
difference = "0";
}
}
return difference;
}
}
| [
"[email protected]"
]
| |
4c221b2ff90f6f7ca805151409e8c1af31ff7b14 | 93ee3d84b6001544e18845533be42ac2fdd85f2b | /src/Classes/Reduction.java | c8e067b42edfded3b5928558048fc77a6bceb380 | []
| no_license | Djellool/Esi_Meal | 7f713c3eb30c88f131a5fc88f17b8949cb555976 | fb72353b9d3d76b1a8af303c8f044ac5847823dc | refs/heads/master | 2020-06-04T06:39:26.191428 | 2019-06-14T08:55:29 | 2019-06-14T08:55:29 | 191,908,255 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 317 | java | package Classes ;
public interface Reduction
{
//on definit les constantes de reductions.
int primeetudiant = 8;
int primefidelite = 5;
int primegroupedomicile = 7;
int primeevent = 10;
int primetableexterieur = 5;
int montantkilolivraison = 20;
float Note_avec_prime();
}
| [
"[email protected]"
]
| |
1068eae84170716144a0cd5bcd5bc7eeff9ff356 | 5db18db6a1529e58b3f0d9a9c78ebed3bc90d662 | /src/main/java/com/adventofcode/year2017/Day9Part1.java | 809e1fc15ea1d55953a54e2d4b13796ee463e762 | [
"Apache-2.0"
]
| permissive | thcathy/advent-of-code | 379497a1f7e6ab3faa73e93bbab1d94a1bb9d48a | c6c0385099ac1e702b4183791343bf01787911b0 | refs/heads/master | 2023-03-20T05:59:14.223512 | 2023-03-18T04:55:49 | 2023-03-18T04:55:49 | 48,277,433 | 7 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,009 | java | package com.adventofcode.year2017;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
public class Day9Part1 {
final static String inputFile = "2017/day9_1.txt";
public static void main(String... args) throws IOException {
Day9Part1 solution = new Day9Part1();
solution.run();
}
void run() throws IOException {
var lines = Resources.readLines(ClassLoader.getSystemResource(inputFile), Charsets.UTF_8);
var result = totalScore(lines.get(0).toCharArray());
System.out.printf("What is the total score for all groups in your input? %d %n", result);
}
int totalScore(char[] input) {
int score = 0;
int total = 0;
boolean isGarbage = false;
for (int i=0; i<input.length; i++) {
char c = input[i];
if (c == '!') {
i++;
} else if (c == '<') {
isGarbage = true;
} else if (c == '>') {
isGarbage = false;
} else if (c == '{' && !isGarbage) {
score++;
} else if (c == '}' && !isGarbage) {
total += score;
score--;
}
}
return total;
}
@Test
public void unitTest() {
Assert.assertEquals(1, totalScore("{}".toCharArray()));
Assert.assertEquals(6, totalScore("{{{}}}".toCharArray()));
Assert.assertEquals(5, totalScore("{{},{}}".toCharArray()));
Assert.assertEquals(16, totalScore("{{{},{},{{}}}}".toCharArray()));
Assert.assertEquals(1, totalScore("{<a>,<a>,<a>,<a>}".toCharArray()));
Assert.assertEquals(9, totalScore("{{<ab>},{<ab>},{<ab>},{<ab>}}".toCharArray()));
Assert.assertEquals(9, totalScore("{{<!!>},{<!!>},{<!!>},{<!!>}}".toCharArray()));
Assert.assertEquals(3, totalScore("{{<a!>},{<a!>},{<a!>},{<ab>}}".toCharArray()));
}
}
| [
"[email protected]"
]
| |
e034a0720af9cc2959335479e97e936d17d58243 | 85fb5e9cf71792c978fe8384a00d6f4be3600166 | /codec-redis/src/main/java/io/netty/contrib/handler/codec/redis/SimpleStringRedisMessage.java | dacb3511724870ec27ff281e0119d8850cb338dc | [
"Apache-2.0"
]
| permissive | gholdzhang/codec-redis | 9f520321553fbe5fcc914dcd9d48424f279765ca | 7ebaf6bd8b0ed8d04b2d3d83b1d63e085db86736 | refs/heads/main | 2023-09-02T23:14:50.803950 | 2021-11-19T14:49:09 | 2021-11-19T14:49:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,158 | java | /*
* Copyright 2021 The Netty Project
*
* The Netty Project licenses this file to you under the Apache License, version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at:
*
* 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 io.netty.contrib.handler.codec.redis;
import io.netty.util.internal.UnstableApi;
/**
* Simple Strings of <a href="https://redis.io/topics/protocol">RESP</a>.
*/
@UnstableApi
public final class SimpleStringRedisMessage extends AbstractStringRedisMessage {
/**
* Creates a {@link SimpleStringRedisMessage} for the given {@code content}.
*
* @param content the message content, must not be {@code null}.
*/
public SimpleStringRedisMessage(String content) {
super(content);
}
}
| [
"[email protected]"
]
| |
4aefcfd945feb34c6d3ef038c6e9377d2d1ec249 | 65742b14939ec7da9e88edab411b1e342a7e4d31 | /app/src/main/java/com/nanyixuan/zzyl_andorid/view/activity/MainActivityController.java | 8ccce696b72875bd18af67c36bb03ec1e59ef6d7 | []
| no_license | GavinDon/zzyl_android | 8d38a88139b3bf9c135aec381750b51a2081d49c | 7cb2759a0c33b4738aa204030b38977ebc4fbe59 | refs/heads/master | 2021-09-23T17:51:03.002544 | 2018-09-26T01:51:35 | 2018-09-26T01:51:35 | 105,295,992 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 377 | java | package com.nanyixuan.zzyl_andorid.view.activity;
import com.nanyixuan.zzyl_andorid.bean.LoginBean;
/**
* Created by YixuanNan on 2017/3/24.
*
* @author YixuanNan
* MainActivity控制类。
*/
public interface MainActivityController extends FragmentController {
void initMainActivity(LoginBean userInfoData);
void initAvatar();
void updateApp();
}
| [
"[email protected]"
]
| |
5ebe3fad005a654fa2cfa515e13ace9a8931231a | 8d6bd2c094a3c193330febd390cd011b40f7ca6b | /TiltSpider/src/com/awhittle/tiltspider/Head.java | b05462cc5b05145aaed07768be7a7972c3168038 | [
"Apache-2.0"
]
| permissive | awhittle3/Tilt-spider | b412bc029956944618df2d913ccc6cecb2ef63ba | bdab674d40464650d4eac389549b0d8144a66a64 | refs/heads/master | 2020-04-19T15:48:57.008337 | 2014-03-14T18:20:18 | 2014-03-14T18:20:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,413 | java | /*The following code was borrowed from
* http://developer.android.com/training/graphics/opengl/index.html
* and modified to suit the needs of the application.
*
*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.awhittle.tiltspider;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import android.opengl.GLES20;
/**
* A two-dimensional square for use as a drawn object in OpenGL ES 2.0.
*/
public class Head {
private final String vertexShaderCode =
// This matrix member variable provides a hook to manipulate
// the coordinates of the objects that use this vertex shader
"uniform mat4 uMVPMatrix;" +
"attribute vec4 vPosition;" +
"void main() {" +
// The matrix must be included as a modifier of gl_Position.
// Note that the uMVPMatrix factor *must be first* in order
// for the matrix multiplication product to be correct.
" gl_Position = uMVPMatrix * vPosition;" +
"}";
private final String fragmentShaderCode =
"precision mediump float;" +
"uniform vec4 vColor;" +
"void main() {" +
" gl_FragColor = vColor;" +
"}";
private final FloatBuffer vertexBuffer;
private final ShortBuffer drawListBuffer;
private final int mProgram;
private int mPositionHandle;
private int mColorHandle;
private int mMVPMatrixHandle;
public static float[] headCoords;
public static int[] headLocation = new int[2];
// number of coordinates per vertex in this array
static final int COORDS_PER_VERTEX = 3;
private static final float headTemplate[] = {
0.0f, 0.05f, 0.0f,
0.0f, -0.05f, 0.0f,
0.1f, 0.15f, 0.0f,
0.2f, 0.05f, 0.0f,
0.2f, -0.05f, 0.0f,
0.1f, -0.15f, 0.0f,
-0.1f, -0.15f, 0.0f,
-0.2f, -0.05f, 0.0f,
-0.2f, 0.05f, 0.0f,
-0.1f, 0.15f, 0.0f};
public static final float initHeadCoords[] = ShapeTools.scaleMatrix(headTemplate, 0.5f);
public static final int initHeadLocation[] = {0, 0};
private static final short drawOrder[] = { 0,1,2, 0,1,3, 0,1,4, 0,1,5, 0,1,6, 0,1,7, 0,1,8, 0,1,9 }; // order to draw vertices
private final int vertexStride = COORDS_PER_VERTEX * 4; // 4 bytes per vertex
float color[] = { 0.0f, 0.0f, 0.0f, 0.0f };
/**
* Sets up the drawing object data for use in an OpenGL ES context.
*/
public Head() {
resetHeadLocation();
// initialize vertex byte buffer for shape coordinates
ByteBuffer bb = ByteBuffer.allocateDirect(
// (# of coordinate values * 4 bytes per float)
headCoords.length * 4);
bb.order(ByteOrder.nativeOrder());
vertexBuffer = bb.asFloatBuffer();
vertexBuffer.put(headCoords);
vertexBuffer.position(0);
// initialize byte buffer for the draw list
ByteBuffer dlb = ByteBuffer.allocateDirect(
// (# of coordinate values * 2 bytes per short)
drawOrder.length * 2);
dlb.order(ByteOrder.nativeOrder());
drawListBuffer = dlb.asShortBuffer();
drawListBuffer.put(drawOrder);
drawListBuffer.position(0);
// prepare shaders and OpenGL program
int vertexShader = MyGLRenderer.loadShader(
GLES20.GL_VERTEX_SHADER,
vertexShaderCode);
int fragmentShader = MyGLRenderer.loadShader(
GLES20.GL_FRAGMENT_SHADER,
fragmentShaderCode);
mProgram = GLES20.glCreateProgram(); // create empty OpenGL Program
GLES20.glAttachShader(mProgram, vertexShader); // add the vertex shader to program
GLES20.glAttachShader(mProgram, fragmentShader); // add the fragment shader to program
GLES20.glLinkProgram(mProgram); // create OpenGL program executables
}
/**
* Encapsulates the OpenGL ES instructions for drawing this shape.
*
* @param mvpMatrix - The Model View Project matrix in which to draw
* this shape.
*/
public void draw(float[] mvpMatrix) {
// Add program to OpenGL environment
GLES20.glUseProgram(mProgram);
// get handle to vertex shader's vPosition member
mPositionHandle = GLES20.glGetAttribLocation(mProgram, "vPosition");
// Enable a handle to the triangle vertices
GLES20.glEnableVertexAttribArray(mPositionHandle);
// Prepare the triangle coordinate data
GLES20.glVertexAttribPointer(
mPositionHandle, COORDS_PER_VERTEX,
GLES20.GL_FLOAT, false,
vertexStride, vertexBuffer);
// get handle to fragment shader's vColor member
mColorHandle = GLES20.glGetUniformLocation(mProgram, "vColor");
// Set color for drawing the triangle
GLES20.glUniform4fv(mColorHandle, 1, color, 0);
// get handle to shape's transformation matrix
mMVPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVPMatrix");
MyGLRenderer.checkGlError("glGetUniformLocation");
// Apply the projection and view transformation
GLES20.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0);
MyGLRenderer.checkGlError("glUniformMatrix4fv");
// Draw the square
GLES20.glDrawElements(
GLES20.GL_TRIANGLES, drawOrder.length,
GLES20.GL_UNSIGNED_SHORT, drawListBuffer);
// Disable vertex array
GLES20.glDisableVertexAttribArray(mPositionHandle);
}
public static void resetHeadLocation() {
Head.headCoords = Head.initHeadCoords;
Head.headLocation = Head.initHeadLocation;
}
} | [
"[email protected]"
]
| |
64b995194e54eb62e788da86651f438cab33d1f0 | 3453bb5cca7fefd32471775ded8d2bc4ba651e1c | /cocoon/maven/sample/src/main/java/org/sapia/cocoon/generation/chunk/template/ComplexNode.java | 46c884d6bb37ecf89fbb9539eec9fd9d46f88a19 | []
| no_license | yduchesne/sapia | 7609be66c624175c38c78f937d1e10ffdf2f4984 | bb431a05140ea8e797e9955ac3ded6f7b88d201c | refs/heads/master | 2016-08-05T02:30:30.226011 | 2015-04-13T04:02:31 | 2015-04-13T04:02:31 | 33,846,591 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 262 | java | package org.sapia.cocoon.generation.chunk.template;
/**
* Extends the {@link Node} interface, and specifies behavior for adding
* child nodes.
*
* @author yduchesne
*
*/
public interface ComplexNode extends Node{
public void addChild(Node node);
}
| [
"yanickduchesne@5eff64f3-1e4c-0410-aaf5-d36480b9dcb2"
]
| yanickduchesne@5eff64f3-1e4c-0410-aaf5-d36480b9dcb2 |
765c8131c49234eaec4eabb77909d27212c8fef5 | 72c030579557e51e4f831e2686b802566ddfb38c | /src/dao/CollectDao.java | d0bc7f95bb0ca7ccb6e8f403a355e57488dcbf10 | []
| no_license | yc488/bbs | ae1315ea0bd5c18d1549b9c3aa68c11037c7d269 | ea6662381bbc7ad2d80713d9df2c4bcc9d92c9d9 | refs/heads/master | 2020-05-14T03:05:09.837173 | 2019-04-16T13:26:33 | 2019-04-16T13:26:33 | 181,692,735 | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 2,147 | java | package dao;
import java.util.List;
import java.util.Map;
import bean.User;
import bean.collect;
import utils.JDBCHelp;
import utils.Myutil;
public class CollectDao {
JDBCHelp db=new JDBCHelp();
/**
* 加入收藏
* @param col
* @return
*/
public int addCollect(collect col) {
String sql="insert into tbl_collect values(null,?,?,?,sysdate())";
return db.executeUpdate(sql, col.getTopicid(),col.getUid(),col.getBoardid());
}
/**
* 查看我的收藏
* @param col
* @return
*/
public List<collect> findMyCollect(collect col) {
String sql="SELECT\r\n" +
" *\r\n" +
"FROM\r\n" +
" (SELECT\r\n" +
" e.*,\r\n" +
" f.`uname` AS sendname\r\n" +
" FROM\r\n" +
" (SELECT\r\n" +
" a.cid,\r\n" +
" a.topicid,\r\n" +
" a.uid,\r\n" +
" a.boardid,\r\n" +
" DATE_FORMAT(\r\n" +
" a.collectime,\r\n" +
" '%Y-%m-%d %H:%i:%s'\r\n" +
" ) AS collectime,\r\n" +
" c.`title`,\r\n" +
" c.uid AS sendid,\r\n" +
" d.`boardname`\r\n" +
" FROM\r\n" +
" tbl_collect a\r\n" +
" LEFT JOIN tbl_topic c\r\n" +
" ON c.`topicid` = a.`topicid`\r\n" +
" LEFT JOIN tbl_board d\r\n" +
" ON d.`boardid` = a.`boardid`\r\n" +
" WHERE a.uid = ?) e\r\n" +
" LEFT JOIN tbl_user f\r\n" +
" ON e.sendid = f.`uid`) g";
List<Map<String,Object>> list = db.executeQuery(sql,col.getUid());
return Myutil.ListMapToJavaBean(list, collect.class);
}
/**
* 取消收藏
* @param col
* @return
*/
public int cancleCollect(collect col) {
String sql="delete from tbl_collect where cid=?";
return db.executeUpdate(sql, col.getCid());
}
/**
* 查出当前用户收藏帖子的总数
* @param user
*/
public int findAllCollect(User user) {
String sql="select count(cid) as total from tbl_collect where uid=?";
List<Map<String,Object>> executeQuery = db.executeQuery(sql, user.getUid());
int total=Integer.parseInt( executeQuery.get(0).get("total").toString()) ;
return total;
}
}
| [
"[email protected]"
]
| |
1cb93d4ab9d15fb9bddba6199964a9b821aaf2b8 | 361065fec289c3fe7c4db635a60536babde9e747 | /rabbitmq-learn/src/main/java/com/message/rabbitmqlearn/simple/Producer.java | 0eb352690eb811e5c1459c9ec4244c223f936525 | []
| no_license | AbrahamTemple/RabbitMQ-Learn | 49526ecd2435ef2e6ee614973615efd56376de5c | 1c648d4c62f09a57ad0f6af6356380ece577db7d | refs/heads/main | 2023-04-08T03:41:09.881350 | 2021-04-18T14:20:36 | 2021-04-18T14:20:36 | 359,150,493 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,924 | java | package com.message.rabbitmqlearn.simple;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Producer {
public static void main(String[] args) {
//创建连接工厂
ConnectionFactory connectionFactory = new ConnectionFactory();
//工厂代理的所有连接属性
connectionFactory.setHost("127.0.0.1");
connectionFactory.setPort(5672);
connectionFactory.setUsername("admin");
connectionFactory.setPassword("admin");
connectionFactory.setVirtualHost("/");
Connection connection = null;
Channel channel = null;
try {
//使用装配好属性的连接工厂进行连接
connection = connectionFactory.newConnection("生产者");
//通过连接来获取通道Channel
channel = connection.createChannel();
// String exchangeName = "myExchange";
// String exchangeType = "direct";
// channel.exchangeDeclare(exchangeName,exchangeType,true);
/* 声明队列 queueDeclare
* @param 队列名称
* @param 是否持久化
* @param 是否有排他性,独占队列
* @param 声明自动删除队列,最后一个消费者消费完毕后是否把队列自动删除
* @param 队列的其它属性
*/
String queueName = "queue1";
channel.queueDeclare(queueName,false,false,false,null);
// channel.queueBind(queueName,exchangeName,"av");
//准备消息内容
String message = "各位好儿子们,清明快乐!";
/*往队列queue里投放消息
* @param 要将消息发布到的交换机exchange
* @param 路由密钥,指向一个已声明过的队列
* @param 支持消息路由头等的其他属性
* @param body消息内容
*/
channel.basicPublish("",queueName,null,message.getBytes());
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
} finally {
// 关闭通道
if(channel != null && channel.isOpen()){
try {
channel.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//关闭连接
if(connection != null && connection.isOpen()){
try {
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
| [
"[email protected]"
]
| |
cb28139a72f7ea1f1bdbde22a697c86138e2c545 | a4095b66224c8fe9b9ee58d013995f424239c50b | /src/main/java/com/algaworks/algafoodapi/api/dto/response/UserResponseDTO.java | 030055eaf60b52641e80bb6511b01905892b828a | []
| no_license | carolinegoulart/algafood-api | f492bdc0f4051f1d3c256903c17f23eb1977eec7 | 2864f44a2aa80df2bf78e70d17be3d3a983717ef | refs/heads/master | 2023-07-12T17:37:21.749798 | 2021-08-30T00:28:23 | 2021-08-30T00:28:23 | 401,121,277 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 270 | java | package com.algaworks.algafoodapi.api.dto.response;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Builder
public class UserResponseDTO {
private final Long id;
private final String name;
private final String email;
} | [
"[email protected]"
]
| |
ecddd67aaed8bac85eb435d925f0180a55975868 | 236511efdf3a3f0fafc891f0764cfaceec1c6f2d | /android/src/main/java/com/woddp/keyboard_listen/KeyboardListenPlugin.java | 70e90f381101b8adebc7ff48d4a7c10c18d79c85 | []
| no_license | woddp/keyboard_listen | 650059f21b2dfc43bcb40d1be970d9924c557bfa | ef83affe187b32df06f7a683c30dc07ce78e311c | refs/heads/master | 2020-05-09T15:56:38.815076 | 2019-04-14T03:07:13 | 2019-04-14T03:07:13 | 181,251,276 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,651 | java | package com.woddp.keyboard_listen;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.EventChannel.EventSink;
import io.flutter.plugin.common.EventChannel.StreamHandler;
import io.flutter.plugin.common.PluginRegistry.Registrar;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/** KeyboardListenPlugin */
public class KeyboardListenPlugin implements StreamHandler,Application.ActivityLifecycleCallbacks, ViewTreeObserver.OnGlobalLayoutListener{
private static final String STREAM_CHANNEL_NAME = "keyboard_listen_plugin";
EventSink eventsSink;
boolean isVisible;
View mainView;
Activity activity;
Context context;
Map<String,Integer> res= new HashMap<>();
KeyboardListenPlugin(Registrar registrar) {
eventsSink = null;
mainView = ((ViewGroup) registrar.activity().findViewById(android.R.id.content)).getChildAt(0);
mainView.getViewTreeObserver().addOnGlobalLayoutListener(this);
this.activity=registrar.activity();
this.context=registrar.context();
res.put("height",0);
res.put("isVisible",isVisible ? 1 : 0);
}
@Override
public void onGlobalLayout() {
Rect r = new Rect();
mainView.getWindowVisibleDisplayFrame(r);
// check if the visible part of the screen is less than 85%
// if it is then the keyboard is showing
boolean newState = ((double)r.height() / (double)mainView.getRootView().getHeight()) < 0.85;
if (newState != isVisible) {
isVisible = newState;
if (eventsSink != null) {
int height=getBottomStatusHeight(this.context);
res.put("height",height);
res.put("isVisible",isVisible ? 1 : 0);
eventsSink.success(res);
}
}
}
////////////////////////////////////////////////////////////////////////
public static int getBottomStatusHeight(Context context) {
int totalHeight = getDpi(context);
int contentHeight = getScreenHeight(context);
return totalHeight - contentHeight;
}
public static int getDpi(Context context) {
int dpi = 0;
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
DisplayMetrics displayMetrics = new DisplayMetrics();
@SuppressWarnings("rawtypes")
Class c;
try {
c = Class.forName("android.view.Display");
@SuppressWarnings("unchecked")
Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
method.invoke(display, displayMetrics);
dpi = displayMetrics.heightPixels;
} catch (Exception e) {
e.printStackTrace();
}
return dpi;
}
public static int getScreenHeight(Context context) {
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.heightPixels;
}
////////////////////////////////////////////////////////////////////
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override
public void onActivityDestroyed(Activity activity) {
mainView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
public static void registerWith(Registrar registrar) {
final EventChannel eventChannel = new EventChannel(registrar.messenger(), STREAM_CHANNEL_NAME);
KeyboardListenPlugin instance = new KeyboardListenPlugin(registrar);
eventChannel.setStreamHandler(instance);
}
@Override
public void onListen(Object arguments, final EventSink eventsSink) {
// register listener
this.eventsSink = eventsSink;
// is keyboard is visible at startup, let our subscriber know
if (isVisible) {
eventsSink.success(res);
}
}
@Override
public void onCancel(Object arguments) {
eventsSink = null;
}
}
| [
"[email protected]"
]
| |
532e3513a31833856ca8c9d687becee33edfb9c6 | bd73d3450aeb07a092e4f50a72845947cf1648ea | /Test-ZK/src/main/java/com/zad/DistributedLock/zkClientApi/MaterSelector.java | 3d7b7dbd543eeec83225d44d01e29ab8a808528f | []
| no_license | ProgramRun/Test-Java | 8d2bbc33f0af59d03a82d01b3702ebe7d7cf6670 | bc73532b6dc370465d3f92eb135578ce42e001b3 | refs/heads/master | 2022-12-22T07:01:29.590479 | 2020-11-30T09:17:52 | 2020-11-30T09:17:52 | 144,426,584 | 0 | 0 | null | 2022-12-16T05:00:22 | 2018-08-12T00:19:42 | Java | UTF-8 | Java | false | false | 3,452 | java | package com.zad.DistributedLock.zkClientApi;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.exception.ZkNodeExistsException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
* 描述:
* 选主的服务
*
* @author zad
* @create 2018-09-10 20:54
*/
public class MaterSelector {
/**
* ZK ip端口号
*/
private ZkClient zkClient;
/**
* 需要争抢的节点
*/
private final static String MASTER = "/master";
/**
* 监听器
*/
private IZkDataListener dataListener;
/**
* 其他服务器
*/
private UserCenter server;
/**
* 主服务器
*/
private UserCenter master;
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
private static boolean isRun = false;
public MaterSelector(UserCenter server, ZkClient zkClient) {
System.out.println("[" + server + "]去争抢权限了");
this.server = server;
this.zkClient = zkClient;
this.dataListener = new IZkDataListener() {
@Override
public void handleDataChange(String dataPath, Object data) throws Exception {
}
@Override
public void handleDataDeleted(String dataPath) throws Exception {
System.out.println("节点删除开始" + dataPath);
// 如果被删除,发起选主操作
chooseMater();
}
};
}
public void start() {
// 开始选主
if (!isRun) {
isRun = true;
// 注册节点事件
zkClient.subscribeDataChanges(MASTER, dataListener);
chooseMater();
}
}
public void stop() {
// 停止
if (isRun) {
isRun = false;
scheduledExecutorService.shutdown();
zkClient.unsubscribeDataChanges(MASTER, dataListener);
releaseMaster();
}
}
private void chooseMater() {
if (!isRun) {
System.out.println("当前服务没有启动");
return;
}
try {
zkClient.createEphemeral(MASTER, server);
master = server;
System.out.println("客户端[" + server.getMc_id() + "] -> 我现在已经是master了");
// 通过定时器释放锁,模拟出现故障
scheduledExecutorService.schedule(() -> {
releaseMaster();
}, 5, TimeUnit.SECONDS);
} catch (ZkNodeExistsException e) {
// master已经存在
UserCenter center = zkClient.readData(MASTER, true);
if (center == null) {
chooseMater();// 再次获取master
} else {
master = center;
}
}
}
private void releaseMaster() {
// 判断是否为master,只有master才需要释放锁
if (isMaster()) {
System.out.println("释放master");
zkClient.deleteRecursive(MASTER);
}
}
private boolean isMaster() {
UserCenter userCenter = zkClient.readData(MASTER);
if (userCenter.getMc_name().equals(server.getMc_name())) {
master = userCenter;
return true;
}
return false;
}
}
| [
"[email protected]"
]
| |
ffce2c0a2adb8ce21281bbaec966993a6d2b129c | 335e5b4b5b3e3a8e1cb471eb62fff143adda9ebb | /CMP 342/Macrosoft Paint/WritingsAndDrawings.java | 2f46a78976b5278b55c84c733e93630f47605f0c | []
| no_license | cvargas9717/Projects | b309132f7e929ab548ded73611feb827e6bc3974 | 89306a3f17eb051b1903ffff6bc24a7f5367a9e9 | refs/heads/master | 2021-01-11T22:29:15.090668 | 2017-10-06T19:00:24 | 2017-10-06T19:00:24 | 78,971,138 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,302 | java | package paint_project;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class WritingsAndDrawings extends Drawings implements KeyListener{
private Font font;
private FontMetrics fm;
protected static boolean typeOn;
public WritingsAndDrawings(){
super();//call parent constructor
setBackground(Color.WHITE);
font = new Font("Serif", Font.ITALIC, 50);//default size;
fm = getFontMetrics(font);//want to be able to measure my String to draw
addKeyListener(this);
typeOn = false;
}
@Override
public void keyTyped(KeyEvent e) {
if(typeOn){
String a = String.valueOf(e.getKeyChar());
if(mouseIsPressed){
Graphics g = getGraphics();
g.setColor(lineColor);
lastX += fm.stringWidth(a); //increase x by width to move next char over
g.drawString(a, lastX, lastY);
//going to write all the chars we type on top of each other
g.dispose();
}
System.out.println("In key typed "+ a);
}
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
} | [
"[email protected]"
]
| |
3d20e730155ec22fd07c1f1e64a69efcd102fc54 | 120d90d15ce730e44b94d0d01dfa0f583ab7f3f3 | /app/src/main/java/com/test/myfirst/pokemonrecyclerview/Pokemon.java | f2539c9377bb68ed0603829b1a2cb6906c440d2f | []
| no_license | mchittimelli/PokemonRecyclerView | ce8a303444f90fa50b5d184f24473ef8cff8c086 | 6a0edd22f90be63f9251fa357dad8d36dae62111 | refs/heads/master | 2020-07-03T18:19:53.279148 | 2019-08-12T20:12:49 | 2019-08-12T20:12:49 | 202,001,909 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,571 | java | package com.test.myfirst.pokemonrecyclerview;
import android.os.Parcel;
import android.os.Parcelable;
public class Pokemon implements Parcelable {
String name,image,type,ability,height,weight,desc;
public Pokemon(String name, String image, String type, String ability, String height, String weight, String desc) {
this.name = name;
this.image = image;
this.type = type;
this.ability = ability;
this.height = height;
this.weight = weight;
this.desc = desc;
}
public Pokemon(String name, String image) {
this.name = name;
this.image = image;
}
protected Pokemon(Parcel in) {
name = in.readString();
image = in.readString();
type = in.readString();
ability = in.readString();
height = in.readString();
weight = in.readString();
desc = in.readString();
}
public static final Creator<Pokemon> CREATOR = new Creator<Pokemon>() {
@Override
public Pokemon createFromParcel(Parcel in) {
return new Pokemon(in);
}
@Override
public Pokemon[] newArray(int size) {
return new Pokemon[size];
}
};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getAbility() {
return ability;
}
public void setAbility(String ability) {
this.ability = ability;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(image);
dest.writeString(type);
dest.writeString(ability);
dest.writeString(height);
dest.writeString(weight);
dest.writeString(desc);
}
}
| [
"[email protected]"
]
| |
22d92aafbdf0f59a0c427afaeb6d7e0e5eb55738 | a2be1b5ca1e1ad61eb146247a8bbbd72aef78a76 | /mockbuster-web/src/main/java/ch/alni/mockbuster/web/controller/PostBindingController.java | 2dcbd794a3b78ea27f9ae722212241162085ee45 | []
| no_license | alexandernikiforov/mockbuster | b12c5790bc805e606a6821241cc7931c3aa71335 | 393324a6cee70bc6c77a4c3ca8f0faa53a3505b3 | refs/heads/develop | 2023-05-06T20:43:09.439998 | 2018-06-25T21:15:04 | 2018-06-25T21:15:04 | 281,759,826 | 0 | 0 | null | 2021-06-07T18:50:19 | 2020-07-22T18:58:07 | Java | UTF-8 | Java | false | false | 1,879 | java | package ch.alni.mockbuster.web.controller;
import ch.alni.mockbuster.service.MockbusterLogoutService;
import ch.alni.mockbuster.service.MockbusterSsoService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.inject.Inject;
/**
* Accepts requests from service providers. Implements SAML POST Bindng.
*/
@Controller
public class PostBindingController {
private final MockbusterSsoService mockbusterSsoService;
private final MockbusterLogoutService localLogoutService;
@Inject
public PostBindingController(MockbusterSsoService mockbusterSsoService, MockbusterLogoutService localLogoutService) {
this.mockbusterSsoService = mockbusterSsoService;
this.localLogoutService = localLogoutService;
}
@RequestMapping(path = "/saml2/sso/post", method = RequestMethod.POST)
public ResponseEntity<?> authenticate(@RequestBody MultiValueMap<String, String> formParameterMap) {
final String encodedSamlRequest = formParameterMap.getFirst("SAMLRequest");
final String relayState = formParameterMap.getFirst("RelayState");
mockbusterSsoService.authenticate(encodedSamlRequest, null);
return ResponseEntity.ok().build();
}
@RequestMapping(path = "/saml2/sso/logout", method = RequestMethod.POST)
public ResponseEntity<?> logout(@RequestBody MultiValueMap<String, String> formParameterMap) {
final String encodedSamlRequest = formParameterMap.getFirst("SAMLRequest");
final String relayState = formParameterMap.getFirst("RelayState");
return ResponseEntity.ok().build();
}
}
| [
"[email protected]"
]
| |
7e8dbfdfbecf789158346c25c04160c3ef12fd9c | ca0e9689023cc9998c7f24b9e0532261fd976e0e | /src/android/support/v4/app/n.java | a891c28fb18327253e4acfd959ca0c4993de79e4 | []
| no_license | honeyflyfish/com.tencent.mm | c7e992f51070f6ac5e9c05e9a2babd7b712cf713 | ce6e605ff98164359a7073ab9a62a3f3101b8c34 | refs/heads/master | 2020-03-28T15:42:52.284117 | 2016-07-19T16:33:30 | 2016-07-19T16:33:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 222 | java | package android.support.v4.app;
abstract interface n
{
public abstract void a(s.a parama);
}
/* Location:
* Qualified Name: android.support.v4.app.n
* Java Class Version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | [
"[email protected]"
]
| |
a7f6797df23964c95ad3319baa2a1886f94a17a7 | cb55ff71e88cfd58f525723b57e7e7cee96dbc53 | /app/controllers/Auth/Secured.java | cabd7b2cc601a30f94ed4ab2990c605493c1cad3 | [
"CC0-1.0"
]
| permissive | bhagyamoharana/BookStoreApp | 3869f9519531ddb255f9878c07d19e3c473ff469 | 94c9082391dba1177aa73a845729c2b93439250c | refs/heads/master | 2020-04-27T14:45:41.551758 | 2019-05-24T05:29:50 | 2019-05-24T05:29:50 | 174,419,748 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 786 | java | package controllers.Auth;
import controllers.routes;
import models.User;
import models.Customer;
import play.mvc.Http;
import play.mvc.Result;
import play.mvc.Security;
public class Secured extends Security.Authenticator {
@Override
public String getUsername(Http.Context ctx) {
return ctx.session().get("email");
}
@Override
public Result onUnauthorized(Http.Context ctx) {
return redirect(routes.AuthController.login());
}
public static String GET_USER(){
Http.Context ctx = Http.Context.current();
return ctx.session().get("email");
}
public static boolean CHECK(){
return (GET_USER() != null);
}
public static User USER(){
return CHECK() ? User.find.byId(GET_USER()):null;
}
} | [
"[email protected]"
]
| |
8ac6e990256d70c18a7cbdfd72d80916c2b3e36d | 300d23dc6a9395974599001b20283dc789b95c27 | /src/main/com/aequilibrium/wsecu/exception/EntityException.java | a9970b4c553e797941bccca63aa611ebf624f3c5 | []
| no_license | aeqjaymes/wsecu-demo | 76477a766951c5769a7a0c9b0b8818eeb9736be0 | f6bbb469bf741092926af2a1ed354e1c184f0e8d | refs/heads/master | 2020-03-30T20:58:43.921195 | 2018-10-04T17:50:42 | 2018-10-04T17:57:42 | 151,612,124 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 176 | java | package com.aequilibrium.wsecu.exception;
public class EntityException extends RuntimeException {
public EntityException(String message) {
super(message);
}
}
| [
"[email protected]"
]
| |
715869d7b3578a9f239676686413dfdb8ec8cb6e | 18055b5d9474682e80c579d509173747ee1eebba | /app/src/main/java/com/jugal/popularmovies/details/trailers/MovieTrailersServerConnector.java | 12fb95b6a299d2d11bf86018ba592fb06c20f285 | []
| no_license | jugalkishorerawat/Popular_Movies_Stage2 | 4792b01a09c8e668d1dc4a48882dad17b262f71a | e3864349562d0d13c69fcfd00a08fd0df111a51e | refs/heads/master | 2021-01-09T20:27:12.351967 | 2016-06-02T22:16:31 | 2016-06-02T22:16:31 | 60,301,003 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,267 | java | package com.jugal.popularmovies.details.trailers;
import android.content.Context;
import android.util.Log;
import com.jugal.popularmovies.details.MovieServerConnector;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MovieTrailersServerConnector extends MovieServerConnector {
protected static final String TAG = "TrailersServerConnector";
public MovieTrailersServerConnector(Context context, int id) {
super(context, id);
}
@Override
protected String setPath() {
return "videos";
}
@Override
protected Map<String, String> parseElements(JSONArray results) throws JSONException {
Map<String, String> trailers = new HashMap<>();
for (int i = 0; i < results.length(); i++) {
JSONObject movieJsonObject = results.getJSONObject(i);
if (movieJsonObject.getString("site").equals("YouTube")) {
trailers.put(movieJsonObject.getString("name"), movieJsonObject.getString("key"));
} else {
Log.w(TAG, "Ignored trailer for unknown website: " + movieJsonObject.getString("site"));
}
}
return trailers;
}
}
| [
"[email protected]"
]
| |
7bd64fd29e9a45c9d5be9acceb0eb333c56497de | 59aac42e38ddb4e936023f0c366d299910da6390 | /src/main/java/com/geekluxun/common/dto/RequestDto.java | 66da0581466eca2b71d9692785f189d1e4158263 | []
| no_license | geekluxun/crazy-java | 96301d43ce4677bcdab10a0c87c911691464167e | 23852d025bf7d535ac14e95c8a86c2912ddb01a6 | refs/heads/master | 2023-03-06T17:44:53.483320 | 2022-05-24T08:41:29 | 2022-05-24T08:41:29 | 138,288,079 | 1 | 0 | null | 2023-02-22T07:14:15 | 2018-06-22T10:10:36 | Java | UTF-8 | Java | false | false | 289 | java | package com.geekluxun.common.dto;
import lombok.Data;
/**
* Copyright,2018-2019,geekluxun Co.,Ltd.
*
* @Author: luxun
* @Create: 2018-07-10 9:41
* @Description:
* @Other:
*/
@Data
public class RequestDto<T> {
private String code;
private String msg;
private T data;
}
| [
"[email protected]"
]
| |
b323252834988e94d45ed5a576cda1b0aa4d6370 | 4632e6734eeccc488fc15b6c6b8debcbcefda759 | /aws-java-sdk-secretsmanager/src/main/java/com/amazonaws/services/secretsmanager/AWSSecretsManagerClient.java | d8ace7569c733529d7c08041d7cf70a2dcf775c4 | [
"Apache-2.0"
]
| permissive | XiaozheSun/aws-sdk-java | e6aad6eb6c82d0e55f19e8be7fa556d33d99fc60 | 865c8d2e1536f20fc4ec355342b54a50cdf58341 | refs/heads/master | 2020-04-06T13:59:08.782602 | 2018-11-14T01:11:03 | 2018-11-14T01:11:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 114,358 | java | /*
* Copyright 2013-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.secretsmanager;
import org.w3c.dom.*;
import java.net.*;
import java.util.*;
import javax.annotation.Generated;
import org.apache.commons.logging.*;
import com.amazonaws.*;
import com.amazonaws.annotation.SdkInternalApi;
import com.amazonaws.auth.*;
import com.amazonaws.handlers.*;
import com.amazonaws.http.*;
import com.amazonaws.internal.*;
import com.amazonaws.internal.auth.*;
import com.amazonaws.metrics.*;
import com.amazonaws.regions.*;
import com.amazonaws.transform.*;
import com.amazonaws.util.*;
import com.amazonaws.protocol.json.*;
import com.amazonaws.util.AWSRequestMetrics.Field;
import com.amazonaws.annotation.ThreadSafe;
import com.amazonaws.client.AwsSyncClientParams;
import com.amazonaws.services.secretsmanager.AWSSecretsManagerClientBuilder;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.services.secretsmanager.model.*;
import com.amazonaws.services.secretsmanager.model.transform.*;
/**
* Client for accessing AWS Secrets Manager. All service calls made using this client are blocking, and will not return
* until the service call completes.
* <p>
* <fullname>AWS Secrets Manager API Reference</fullname>
* <p>
* AWS Secrets Manager is a web service that enables you to store, manage, and retrieve, secrets.
* </p>
* <p>
* This guide provides descriptions of the Secrets Manager API. For more information about using this service, see the
* <a href="http://docs.aws.amazon.com/secretsmanager/latest/userguide/introduction.html">AWS Secrets Manager User
* Guide</a>.
* </p>
* <p>
* <b>API Version</b>
* </p>
* <p>
* This version of the Secrets Manager API Reference documents the Secrets Manager API version 2017-10-17.
* </p>
* <note>
* <p>
* As an alternative to using the API directly, you can use one of the AWS SDKs, which consist of libraries and sample
* code for various programming languages and platforms (such as Java, Ruby, .NET, iOS, and Android). The SDKs provide a
* convenient way to create programmatic access to AWS Secrets Manager. For example, the SDKs take care of
* cryptographically signing requests, managing errors, and retrying requests automatically. For more information about
* the AWS SDKs, including how to download and install them, see <a href="http://aws.amazon.com/tools/">Tools for Amazon
* Web Services</a>.
* </p>
* </note>
* <p>
* We recommend that you use the AWS SDKs to make programmatic API calls to Secrets Manager. However, you also can use
* the Secrets Manager HTTP Query API to make direct calls to the Secrets Manager web service. To learn more about the
* Secrets Manager HTTP Query API, see <a
* href="http://docs.aws.amazon.com/secretsmanager/latest/userguide/query-requests.html">Making Query Requests</a> in
* the <i>AWS Secrets Manager User Guide</i>.
* </p>
* <p>
* Secrets Manager supports GET and POST requests for all actions. That is, the API doesn't require you to use GET for
* some actions and POST for others. However, GET requests are subject to the limitation size of a URL. Therefore, for
* operations that require larger sizes, use a POST request.
* </p>
* <p>
* <b>Support and Feedback for AWS Secrets Manager</b>
* </p>
* <p>
* We welcome your feedback. Send your comments to <a
* href="mailto:[email protected]">[email protected]</a>, or post your feedback
* and questions in the <a href="http://forums.aws.amazon.com/forum.jspa?forumID=296">AWS Secrets Manager Discussion
* Forum</a>. For more information about the AWS Discussion Forums, see <a
* href="http://forums.aws.amazon.com/help.jspa">Forums Help</a>.
* </p>
* <p>
* <b>How examples are presented</b>
* </p>
* <p>
* The JSON that AWS Secrets Manager expects as your request parameters and that the service returns as a response to
* HTTP query requests are single, long strings without line breaks or white space formatting. The JSON shown in the
* examples is formatted with both line breaks and white space to improve readability. When example input parameters
* would also result in long strings that extend beyond the screen, we insert line breaks to enhance readability. You
* should always submit the input as a single JSON text string.
* </p>
* <p>
* <b>Logging API Requests</b>
* </p>
* <p>
* AWS Secrets Manager supports AWS CloudTrail, a service that records AWS API calls for your AWS account and delivers
* log files to an Amazon S3 bucket. By using information that's collected by AWS CloudTrail, you can determine which
* requests were successfully made to Secrets Manager, who made the request, when it was made, and so on. For more about
* AWS Secrets Manager and its support for AWS CloudTrail, see <a
* href="http://docs.aws.amazon.com/secretsmanager/latest/userguide/monitoring.html#monitoring_cloudtrail">Logging AWS
* Secrets Manager Events with AWS CloudTrail</a> in the <i>AWS Secrets Manager User Guide</i>. To learn more about
* CloudTrail, including how to turn it on and find your log files, see the <a
* href="http://docs.aws.amazon.com/awscloudtrail/latest/userguide/what_is_cloud_trail_top_level.html">AWS CloudTrail
* User Guide</a>.
* </p>
*/
@ThreadSafe
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AWSSecretsManagerClient extends AmazonWebServiceClient implements AWSSecretsManager {
/** Provider for AWS credentials. */
private final AWSCredentialsProvider awsCredentialsProvider;
private static final Log log = LogFactory.getLog(AWSSecretsManager.class);
/** Default signing name for the service. */
private static final String DEFAULT_SIGNING_NAME = "secretsmanager";
/** Client configuration factory providing ClientConfigurations tailored to this client */
protected static final ClientConfigurationFactory configFactory = new ClientConfigurationFactory();
private static final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory = new com.amazonaws.protocol.json.SdkJsonProtocolFactory(
new JsonClientMetadata()
.withProtocolVersion("1.1")
.withSupportsCbor(false)
.withSupportsIon(false)
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("EncryptionFailure").withModeledClass(
com.amazonaws.services.secretsmanager.model.EncryptionFailureException.class))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("InvalidParameterException").withModeledClass(
com.amazonaws.services.secretsmanager.model.InvalidParameterException.class))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("MalformedPolicyDocumentException").withModeledClass(
com.amazonaws.services.secretsmanager.model.MalformedPolicyDocumentException.class))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("DecryptionFailure").withModeledClass(
com.amazonaws.services.secretsmanager.model.DecryptionFailureException.class))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("InvalidRequestException").withModeledClass(
com.amazonaws.services.secretsmanager.model.InvalidRequestException.class))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("ResourceNotFoundException").withModeledClass(
com.amazonaws.services.secretsmanager.model.ResourceNotFoundException.class))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("InternalServiceError").withModeledClass(
com.amazonaws.services.secretsmanager.model.InternalServiceErrorException.class))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("ResourceExistsException").withModeledClass(
com.amazonaws.services.secretsmanager.model.ResourceExistsException.class))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("InvalidNextTokenException").withModeledClass(
com.amazonaws.services.secretsmanager.model.InvalidNextTokenException.class))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("LimitExceededException").withModeledClass(
com.amazonaws.services.secretsmanager.model.LimitExceededException.class))
.addErrorMetadata(
new JsonErrorShapeMetadata().withErrorCode("PreconditionNotMetException").withModeledClass(
com.amazonaws.services.secretsmanager.model.PreconditionNotMetException.class))
.withBaseServiceExceptionClass(com.amazonaws.services.secretsmanager.model.AWSSecretsManagerException.class));
public static AWSSecretsManagerClientBuilder builder() {
return AWSSecretsManagerClientBuilder.standard();
}
/**
* Constructs a new client to invoke service methods on AWS Secrets Manager using the specified parameters.
*
* <p>
* All service calls made using this new client object are blocking, and will not return until the service call
* completes.
*
* @param clientParams
* Object providing client parameters.
*/
AWSSecretsManagerClient(AwsSyncClientParams clientParams) {
super(clientParams);
this.awsCredentialsProvider = clientParams.getCredentialsProvider();
init();
}
/**
* Constructs a new client to invoke service methods on AWS Secrets Manager using the specified parameters.
*
* <p>
* All service calls made using this new client object are blocking, and will not return until the service call
* completes.
*
* @param clientParams
* Object providing client parameters.
*/
AWSSecretsManagerClient(AwsSyncClientParams clientParams, boolean endpointDiscoveryEnabled) {
super(clientParams);
this.awsCredentialsProvider = clientParams.getCredentialsProvider();
init();
}
private void init() {
setServiceNameIntern(DEFAULT_SIGNING_NAME);
setEndpointPrefix(ENDPOINT_PREFIX);
// calling this.setEndPoint(...) will also modify the signer accordingly
setEndpoint("secretsmanager.us-east-1.amazonaws.com");
HandlerChainFactory chainFactory = new HandlerChainFactory();
requestHandler2s.addAll(chainFactory.newRequestHandlerChain("/com/amazonaws/services/secretsmanager/request.handlers"));
requestHandler2s.addAll(chainFactory.newRequestHandler2Chain("/com/amazonaws/services/secretsmanager/request.handler2s"));
requestHandler2s.addAll(chainFactory.getGlobalHandlers());
}
/**
* <p>
* Disables automatic scheduled rotation and cancels the rotation of a secret if one is currently in progress.
* </p>
* <p>
* To re-enable scheduled rotation, call <a>RotateSecret</a> with <code>AutomaticallyRotateAfterDays</code> set to a
* value greater than 0. This will immediately rotate your secret and then enable the automatic schedule.
* </p>
* <note>
* <p>
* If you cancel a rotation that is in progress, it can leave the <code>VersionStage</code> labels in an unexpected
* state. Depending on what step of the rotation was in progress, you might need to remove the staging label
* <code>AWSPENDING</code> from the partially created version, specified by the <code>VersionId</code> response
* value. You should also evaluate the partially rotated new version to see if it should be deleted, which you can
* do by removing all staging labels from the new version's <code>VersionStage</code> field.
* </p>
* </note>
* <p>
* To successfully start a rotation, the staging label <code>AWSPENDING</code> must be in one of the following
* states:
* </p>
* <ul>
* <li>
* <p>
* Not be attached to any version at all
* </p>
* </li>
* <li>
* <p>
* Attached to the same version as the staging label <code>AWSCURRENT</code>
* </p>
* </li>
* </ul>
* <p>
* If the staging label <code>AWSPENDING</code> is attached to a different version than the version with
* <code>AWSCURRENT</code> then the attempt to rotate fails.
* </p>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>
* To run this command, you must have the following permissions:
* </p>
* <ul>
* <li>
* <p>
* secretsmanager:CancelRotateSecret
* </p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>
* To configure rotation for a secret or to manually trigger a rotation, use <a>RotateSecret</a>.
* </p>
* </li>
* <li>
* <p>
* To get the rotation configuration details for a secret, use <a>DescribeSecret</a>.
* </p>
* </li>
* <li>
* <p>
* To list all of the currently available secrets, use <a>ListSecrets</a>.
* </p>
* </li>
* <li>
* <p>
* To list all of the versions currently associated with a secret, use <a>ListSecretVersionIds</a>.
* </p>
* </li>
* </ul>
*
* @param cancelRotateSecretRequest
* @return Result of the CancelRotateSecret operation returned by the service.
* @throws ResourceNotFoundException
* We can't find the resource that you asked for.
* @throws InvalidParameterException
* You provided an invalid value for a parameter.
* @throws InternalServiceErrorException
* An error occurred on the server side.
* @throws InvalidRequestException
* You provided a parameter value that is not valid for the current state of the resource.</p>
* <p>
* Possible causes:
* </p>
* <ul>
* <li>
* <p>
* You tried to perform the operation on a secret that's currently marked deleted.
* </p>
* </li>
* <li>
* <p>
* You tried to enable rotation on a secret that doesn't already have a Lambda function ARN configured and
* you didn't include such an ARN as a parameter in this call.
* </p>
* </li>
* @sample AWSSecretsManager.CancelRotateSecret
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/CancelRotateSecret"
* target="_top">AWS API Documentation</a>
*/
@Override
public CancelRotateSecretResult cancelRotateSecret(CancelRotateSecretRequest request) {
request = beforeClientExecution(request);
return executeCancelRotateSecret(request);
}
@SdkInternalApi
final CancelRotateSecretResult executeCancelRotateSecret(CancelRotateSecretRequest cancelRotateSecretRequest) {
ExecutionContext executionContext = createExecutionContext(cancelRotateSecretRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<CancelRotateSecretRequest> request = null;
Response<CancelRotateSecretResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new CancelRotateSecretRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(cancelRotateSecretRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Secrets Manager");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "CancelRotateSecret");
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
URI cachedEndpoint = null;
HttpResponseHandler<AmazonWebServiceResponse<CancelRotateSecretResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new CancelRotateSecretResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Creates a new secret. A secret in Secrets Manager consists of both the protected secret data and the important
* information needed to manage the secret.
* </p>
* <p>
* Secrets Manager stores the encrypted secret data in one of a collection of "versions" associated with the secret.
* Each version contains a copy of the encrypted secret data. Each version is associated with one or more
* "staging labels" that identify where the version is in the rotation cycle. The
* <code>SecretVersionsToStages</code> field of the secret contains the mapping of staging labels to the active
* versions of the secret. Versions without a staging label are considered deprecated and are not included in the
* list.
* </p>
* <p>
* You provide the secret data to be encrypted by putting text in either the <code>SecretString</code> parameter or
* binary data in the <code>SecretBinary</code> parameter, but not both. If you include <code>SecretString</code> or
* <code>SecretBinary</code> then Secrets Manager also creates an initial secret version and automatically attaches
* the staging label <code>AWSCURRENT</code> to the new version.
* </p>
* <note>
* <ul>
* <li>
* <p>
* If you call an operation that needs to encrypt or decrypt the <code>SecretString</code> or
* <code>SecretBinary</code> for a secret in the same account as the calling user and that secret doesn't specify a
* AWS KMS encryption key, Secrets Manager uses the account's default AWS managed customer master key (CMK) with the
* alias <code>aws/secretsmanager</code>. If this key doesn't already exist in your account then Secrets Manager
* creates it for you automatically. All users and roles in the same AWS account automatically have access to use
* the default CMK. Note that if an Secrets Manager API call results in AWS having to create the account's
* AWS-managed CMK, it can result in a one-time significant delay in returning the result.
* </p>
* </li>
* <li>
* <p>
* If the secret is in a different AWS account from the credentials calling an API that requires encryption or
* decryption of the secret value then you must create and use a custom AWS KMS CMK because you can't access the
* default CMK for the account using credentials from a different AWS account. Store the ARN of the CMK in the
* secret when you create the secret or when you update it by including it in the <code>KMSKeyId</code>. If you call
* an API that must encrypt or decrypt <code>SecretString</code> or <code>SecretBinary</code> using credentials from
* a different account then the AWS KMS key policy must grant cross-account access to that other account's user or
* role for both the kms:GenerateDataKey and kms:Decrypt operations.
* </p>
* </li>
* </ul>
* </note>
* <p>
* </p>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>
* To run this command, you must have the following permissions:
* </p>
* <ul>
* <li>
* <p>
* secretsmanager:CreateSecret
* </p>
* </li>
* <li>
* <p>
* kms:GenerateDataKey - needed only if you use a customer-managed AWS KMS key to encrypt the secret. You do not
* need this permission to use the account's default AWS managed CMK for Secrets Manager.
* </p>
* </li>
* <li>
* <p>
* kms:Decrypt - needed only if you use a customer-managed AWS KMS key to encrypt the secret. You do not need this
* permission to use the account's default AWS managed CMK for Secrets Manager.
* </p>
* </li>
* <li>
* <p>
* secretsmanager:TagResource - needed only if you include the <code>Tags</code> parameter.
* </p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>
* To delete a secret, use <a>DeleteSecret</a>.
* </p>
* </li>
* <li>
* <p>
* To modify an existing secret, use <a>UpdateSecret</a>.
* </p>
* </li>
* <li>
* <p>
* To create a new version of a secret, use <a>PutSecretValue</a>.
* </p>
* </li>
* <li>
* <p>
* To retrieve the encrypted secure string and secure binary values, use <a>GetSecretValue</a>.
* </p>
* </li>
* <li>
* <p>
* To retrieve all other details for a secret, use <a>DescribeSecret</a>. This does not include the encrypted secure
* string and secure binary values.
* </p>
* </li>
* <li>
* <p>
* To retrieve the list of secret versions associated with the current secret, use <a>DescribeSecret</a> and examine
* the <code>SecretVersionsToStages</code> response value.
* </p>
* </li>
* </ul>
*
* @param createSecretRequest
* @return Result of the CreateSecret operation returned by the service.
* @throws InvalidParameterException
* You provided an invalid value for a parameter.
* @throws InvalidRequestException
* You provided a parameter value that is not valid for the current state of the resource.</p>
* <p>
* Possible causes:
* </p>
* <ul>
* <li>
* <p>
* You tried to perform the operation on a secret that's currently marked deleted.
* </p>
* </li>
* <li>
* <p>
* You tried to enable rotation on a secret that doesn't already have a Lambda function ARN configured and
* you didn't include such an ARN as a parameter in this call.
* </p>
* </li>
* @throws LimitExceededException
* The request failed because it would exceed one of the Secrets Manager internal limits.
* @throws EncryptionFailureException
* Secrets Manager can't encrypt the protected secret text using the provided KMS key. Check that the
* customer master key (CMK) is available, enabled, and not in an invalid state. For more information, see
* <a href="http://docs.aws.amazon.com/kms/latest/developerguide/key-state.html">How Key State Affects Use
* of a Customer Master Key</a>.
* @throws ResourceExistsException
* A resource with the ID you requested already exists.
* @throws ResourceNotFoundException
* We can't find the resource that you asked for.
* @throws MalformedPolicyDocumentException
* The policy document that you provided isn't valid.
* @throws InternalServiceErrorException
* An error occurred on the server side.
* @throws PreconditionNotMetException
* The request failed because you did not complete all the prerequisite steps.
* @sample AWSSecretsManager.CreateSecret
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/CreateSecret" target="_top">AWS
* API Documentation</a>
*/
@Override
public CreateSecretResult createSecret(CreateSecretRequest request) {
request = beforeClientExecution(request);
return executeCreateSecret(request);
}
@SdkInternalApi
final CreateSecretResult executeCreateSecret(CreateSecretRequest createSecretRequest) {
ExecutionContext executionContext = createExecutionContext(createSecretRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<CreateSecretRequest> request = null;
Response<CreateSecretResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new CreateSecretRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(createSecretRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Secrets Manager");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "CreateSecret");
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
URI cachedEndpoint = null;
HttpResponseHandler<AmazonWebServiceResponse<CreateSecretResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new CreateSecretResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Deletes the resource-based permission policy that's attached to the secret.
* </p>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>
* To run this command, you must have the following permissions:
* </p>
* <ul>
* <li>
* <p>
* secretsmanager:DeleteResourcePolicy
* </p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>
* To attach a resource policy to a secret, use <a>PutResourcePolicy</a>.
* </p>
* </li>
* <li>
* <p>
* To retrieve the current resource-based policy that's attached to a secret, use <a>GetResourcePolicy</a>.
* </p>
* </li>
* <li>
* <p>
* To list all of the currently available secrets, use <a>ListSecrets</a>.
* </p>
* </li>
* </ul>
*
* @param deleteResourcePolicyRequest
* @return Result of the DeleteResourcePolicy operation returned by the service.
* @throws ResourceNotFoundException
* We can't find the resource that you asked for.
* @throws InternalServiceErrorException
* An error occurred on the server side.
* @throws InvalidRequestException
* You provided a parameter value that is not valid for the current state of the resource.</p>
* <p>
* Possible causes:
* </p>
* <ul>
* <li>
* <p>
* You tried to perform the operation on a secret that's currently marked deleted.
* </p>
* </li>
* <li>
* <p>
* You tried to enable rotation on a secret that doesn't already have a Lambda function ARN configured and
* you didn't include such an ARN as a parameter in this call.
* </p>
* </li>
* @sample AWSSecretsManager.DeleteResourcePolicy
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/DeleteResourcePolicy"
* target="_top">AWS API Documentation</a>
*/
@Override
public DeleteResourcePolicyResult deleteResourcePolicy(DeleteResourcePolicyRequest request) {
request = beforeClientExecution(request);
return executeDeleteResourcePolicy(request);
}
@SdkInternalApi
final DeleteResourcePolicyResult executeDeleteResourcePolicy(DeleteResourcePolicyRequest deleteResourcePolicyRequest) {
ExecutionContext executionContext = createExecutionContext(deleteResourcePolicyRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<DeleteResourcePolicyRequest> request = null;
Response<DeleteResourcePolicyResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new DeleteResourcePolicyRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(deleteResourcePolicyRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Secrets Manager");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "DeleteResourcePolicy");
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
URI cachedEndpoint = null;
HttpResponseHandler<AmazonWebServiceResponse<DeleteResourcePolicyResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new DeleteResourcePolicyResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Deletes an entire secret and all of its versions. You can optionally include a recovery window during which you
* can restore the secret. If you don't specify a recovery window value, the operation defaults to 30 days. Secrets
* Manager attaches a <code>DeletionDate</code> stamp to the secret that specifies the end of the recovery window.
* At the end of the recovery window, Secrets Manager deletes the secret permanently.
* </p>
* <p>
* At any time before recovery window ends, you can use <a>RestoreSecret</a> to remove the <code>DeletionDate</code>
* and cancel the deletion of the secret.
* </p>
* <p>
* You cannot access the encrypted secret information in any secret that is scheduled for deletion. If you need to
* access that information, you must cancel the deletion with <a>RestoreSecret</a> and then retrieve the
* information.
* </p>
* <note>
* <ul>
* <li>
* <p>
* There is no explicit operation to delete a version of a secret. Instead, remove all staging labels from the
* <code>VersionStage</code> field of a version. That marks the version as deprecated and allows Secrets Manager to
* delete it as needed. Versions that do not have any staging labels do not show up in <a>ListSecretVersionIds</a>
* unless you specify <code>IncludeDeprecated</code>.
* </p>
* </li>
* <li>
* <p>
* The permanent secret deletion at the end of the waiting period is performed as a background task with low
* priority. There is no guarantee of a specific time after the recovery window for the actual delete operation to
* occur.
* </p>
* </li>
* </ul>
* </note>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>
* To run this command, you must have the following permissions:
* </p>
* <ul>
* <li>
* <p>
* secretsmanager:DeleteSecret
* </p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>
* To create a secret, use <a>CreateSecret</a>.
* </p>
* </li>
* <li>
* <p>
* To cancel deletion of a version of a secret before the recovery window has expired, use <a>RestoreSecret</a>.
* </p>
* </li>
* </ul>
*
* @param deleteSecretRequest
* @return Result of the DeleteSecret operation returned by the service.
* @throws ResourceNotFoundException
* We can't find the resource that you asked for.
* @throws InvalidParameterException
* You provided an invalid value for a parameter.
* @throws InvalidRequestException
* You provided a parameter value that is not valid for the current state of the resource.</p>
* <p>
* Possible causes:
* </p>
* <ul>
* <li>
* <p>
* You tried to perform the operation on a secret that's currently marked deleted.
* </p>
* </li>
* <li>
* <p>
* You tried to enable rotation on a secret that doesn't already have a Lambda function ARN configured and
* you didn't include such an ARN as a parameter in this call.
* </p>
* </li>
* @throws InternalServiceErrorException
* An error occurred on the server side.
* @sample AWSSecretsManager.DeleteSecret
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/DeleteSecret" target="_top">AWS
* API Documentation</a>
*/
@Override
public DeleteSecretResult deleteSecret(DeleteSecretRequest request) {
request = beforeClientExecution(request);
return executeDeleteSecret(request);
}
@SdkInternalApi
final DeleteSecretResult executeDeleteSecret(DeleteSecretRequest deleteSecretRequest) {
ExecutionContext executionContext = createExecutionContext(deleteSecretRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<DeleteSecretRequest> request = null;
Response<DeleteSecretResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new DeleteSecretRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(deleteSecretRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Secrets Manager");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "DeleteSecret");
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
URI cachedEndpoint = null;
HttpResponseHandler<AmazonWebServiceResponse<DeleteSecretResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new DeleteSecretResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Retrieves the details of a secret. It does not include the encrypted fields. Only those fields that are populated
* with a value are returned in the response.
* </p>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>
* To run this command, you must have the following permissions:
* </p>
* <ul>
* <li>
* <p>
* secretsmanager:DescribeSecret
* </p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>
* To create a secret, use <a>CreateSecret</a>.
* </p>
* </li>
* <li>
* <p>
* To modify a secret, use <a>UpdateSecret</a>.
* </p>
* </li>
* <li>
* <p>
* To retrieve the encrypted secret information in a version of the secret, use <a>GetSecretValue</a>.
* </p>
* </li>
* <li>
* <p>
* To list all of the secrets in the AWS account, use <a>ListSecrets</a>.
* </p>
* </li>
* </ul>
*
* @param describeSecretRequest
* @return Result of the DescribeSecret operation returned by the service.
* @throws ResourceNotFoundException
* We can't find the resource that you asked for.
* @throws InternalServiceErrorException
* An error occurred on the server side.
* @sample AWSSecretsManager.DescribeSecret
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/DescribeSecret" target="_top">AWS
* API Documentation</a>
*/
@Override
public DescribeSecretResult describeSecret(DescribeSecretRequest request) {
request = beforeClientExecution(request);
return executeDescribeSecret(request);
}
@SdkInternalApi
final DescribeSecretResult executeDescribeSecret(DescribeSecretRequest describeSecretRequest) {
ExecutionContext executionContext = createExecutionContext(describeSecretRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<DescribeSecretRequest> request = null;
Response<DescribeSecretResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new DescribeSecretRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(describeSecretRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Secrets Manager");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "DescribeSecret");
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
URI cachedEndpoint = null;
HttpResponseHandler<AmazonWebServiceResponse<DescribeSecretResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new DescribeSecretResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Generates a random password of the specified complexity. This operation is intended for use in the Lambda
* rotation function. Per best practice, we recommend that you specify the maximum length and include every
* character type that the system you are generating a password for can support.
* </p>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>
* To run this command, you must have the following permissions:
* </p>
* <ul>
* <li>
* <p>
* secretsmanager:GetRandomPassword
* </p>
* </li>
* </ul>
*
* @param getRandomPasswordRequest
* @return Result of the GetRandomPassword operation returned by the service.
* @throws InvalidParameterException
* You provided an invalid value for a parameter.
* @throws InvalidRequestException
* You provided a parameter value that is not valid for the current state of the resource.</p>
* <p>
* Possible causes:
* </p>
* <ul>
* <li>
* <p>
* You tried to perform the operation on a secret that's currently marked deleted.
* </p>
* </li>
* <li>
* <p>
* You tried to enable rotation on a secret that doesn't already have a Lambda function ARN configured and
* you didn't include such an ARN as a parameter in this call.
* </p>
* </li>
* @throws InternalServiceErrorException
* An error occurred on the server side.
* @sample AWSSecretsManager.GetRandomPassword
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/GetRandomPassword"
* target="_top">AWS API Documentation</a>
*/
@Override
public GetRandomPasswordResult getRandomPassword(GetRandomPasswordRequest request) {
request = beforeClientExecution(request);
return executeGetRandomPassword(request);
}
@SdkInternalApi
final GetRandomPasswordResult executeGetRandomPassword(GetRandomPasswordRequest getRandomPasswordRequest) {
ExecutionContext executionContext = createExecutionContext(getRandomPasswordRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<GetRandomPasswordRequest> request = null;
Response<GetRandomPasswordResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new GetRandomPasswordRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(getRandomPasswordRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Secrets Manager");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "GetRandomPassword");
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
URI cachedEndpoint = null;
HttpResponseHandler<AmazonWebServiceResponse<GetRandomPasswordResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new GetRandomPasswordResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Retrieves the JSON text of the resource-based policy document that's attached to the specified secret. The JSON
* request string input and response output are shown formatted with white space and line breaks for better
* readability. Submit your input as a single line JSON string.
* </p>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>
* To run this command, you must have the following permissions:
* </p>
* <ul>
* <li>
* <p>
* secretsmanager:GetResourcePolicy
* </p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>
* To attach a resource policy to a secret, use <a>PutResourcePolicy</a>.
* </p>
* </li>
* <li>
* <p>
* To delete the resource-based policy that's attached to a secret, use <a>DeleteResourcePolicy</a>.
* </p>
* </li>
* <li>
* <p>
* To list all of the currently available secrets, use <a>ListSecrets</a>.
* </p>
* </li>
* </ul>
*
* @param getResourcePolicyRequest
* @return Result of the GetResourcePolicy operation returned by the service.
* @throws ResourceNotFoundException
* We can't find the resource that you asked for.
* @throws InternalServiceErrorException
* An error occurred on the server side.
* @throws InvalidRequestException
* You provided a parameter value that is not valid for the current state of the resource.</p>
* <p>
* Possible causes:
* </p>
* <ul>
* <li>
* <p>
* You tried to perform the operation on a secret that's currently marked deleted.
* </p>
* </li>
* <li>
* <p>
* You tried to enable rotation on a secret that doesn't already have a Lambda function ARN configured and
* you didn't include such an ARN as a parameter in this call.
* </p>
* </li>
* @sample AWSSecretsManager.GetResourcePolicy
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/GetResourcePolicy"
* target="_top">AWS API Documentation</a>
*/
@Override
public GetResourcePolicyResult getResourcePolicy(GetResourcePolicyRequest request) {
request = beforeClientExecution(request);
return executeGetResourcePolicy(request);
}
@SdkInternalApi
final GetResourcePolicyResult executeGetResourcePolicy(GetResourcePolicyRequest getResourcePolicyRequest) {
ExecutionContext executionContext = createExecutionContext(getResourcePolicyRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<GetResourcePolicyRequest> request = null;
Response<GetResourcePolicyResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new GetResourcePolicyRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(getResourcePolicyRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Secrets Manager");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "GetResourcePolicy");
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
URI cachedEndpoint = null;
HttpResponseHandler<AmazonWebServiceResponse<GetResourcePolicyResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new GetResourcePolicyResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Retrieves the contents of the encrypted fields <code>SecretString</code> or <code>SecretBinary</code> from the
* specified version of a secret, whichever contains content.
* </p>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>
* To run this command, you must have the following permissions:
* </p>
* <ul>
* <li>
* <p>
* secretsmanager:GetSecretValue
* </p>
* </li>
* <li>
* <p>
* kms:Decrypt - required only if you use a customer-managed AWS KMS key to encrypt the secret. You do not need this
* permission to use the account's default AWS managed CMK for Secrets Manager.
* </p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>
* To create a new version of the secret with different encrypted information, use <a>PutSecretValue</a>.
* </p>
* </li>
* <li>
* <p>
* To retrieve the non-encrypted details for the secret, use <a>DescribeSecret</a>.
* </p>
* </li>
* </ul>
*
* @param getSecretValueRequest
* @return Result of the GetSecretValue operation returned by the service.
* @throws ResourceNotFoundException
* We can't find the resource that you asked for.
* @throws InvalidParameterException
* You provided an invalid value for a parameter.
* @throws InvalidRequestException
* You provided a parameter value that is not valid for the current state of the resource.</p>
* <p>
* Possible causes:
* </p>
* <ul>
* <li>
* <p>
* You tried to perform the operation on a secret that's currently marked deleted.
* </p>
* </li>
* <li>
* <p>
* You tried to enable rotation on a secret that doesn't already have a Lambda function ARN configured and
* you didn't include such an ARN as a parameter in this call.
* </p>
* </li>
* @throws DecryptionFailureException
* Secrets Manager can't decrypt the protected secret text using the provided KMS key.
* @throws InternalServiceErrorException
* An error occurred on the server side.
* @sample AWSSecretsManager.GetSecretValue
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/GetSecretValue" target="_top">AWS
* API Documentation</a>
*/
@Override
public GetSecretValueResult getSecretValue(GetSecretValueRequest request) {
request = beforeClientExecution(request);
return executeGetSecretValue(request);
}
@SdkInternalApi
final GetSecretValueResult executeGetSecretValue(GetSecretValueRequest getSecretValueRequest) {
ExecutionContext executionContext = createExecutionContext(getSecretValueRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<GetSecretValueRequest> request = null;
Response<GetSecretValueResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new GetSecretValueRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(getSecretValueRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Secrets Manager");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "GetSecretValue");
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
URI cachedEndpoint = null;
HttpResponseHandler<AmazonWebServiceResponse<GetSecretValueResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new GetSecretValueResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Lists all of the versions attached to the specified secret. The output does not include the
* <code>SecretString</code> or <code>SecretBinary</code> fields. By default, the list includes only versions that
* have at least one staging label in <code>VersionStage</code> attached.
* </p>
* <note>
* <p>
* Always check the <code>NextToken</code> response parameter when calling any of the <code>List*</code> operations.
* These operations can occasionally return an empty or shorter than expected list of results even when there are
* more results available. When this happens, the <code>NextToken</code> response parameter contains a value to pass
* to the next call to the same API to request the next part of the list.
* </p>
* </note>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>
* To run this command, you must have the following permissions:
* </p>
* <ul>
* <li>
* <p>
* secretsmanager:ListSecretVersionIds
* </p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>
* To list the secrets in an account, use <a>ListSecrets</a>.
* </p>
* </li>
* </ul>
*
* @param listSecretVersionIdsRequest
* @return Result of the ListSecretVersionIds operation returned by the service.
* @throws InvalidNextTokenException
* You provided an invalid <code>NextToken</code> value.
* @throws ResourceNotFoundException
* We can't find the resource that you asked for.
* @throws InternalServiceErrorException
* An error occurred on the server side.
* @sample AWSSecretsManager.ListSecretVersionIds
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/ListSecretVersionIds"
* target="_top">AWS API Documentation</a>
*/
@Override
public ListSecretVersionIdsResult listSecretVersionIds(ListSecretVersionIdsRequest request) {
request = beforeClientExecution(request);
return executeListSecretVersionIds(request);
}
@SdkInternalApi
final ListSecretVersionIdsResult executeListSecretVersionIds(ListSecretVersionIdsRequest listSecretVersionIdsRequest) {
ExecutionContext executionContext = createExecutionContext(listSecretVersionIdsRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<ListSecretVersionIdsRequest> request = null;
Response<ListSecretVersionIdsResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new ListSecretVersionIdsRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(listSecretVersionIdsRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Secrets Manager");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "ListSecretVersionIds");
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
URI cachedEndpoint = null;
HttpResponseHandler<AmazonWebServiceResponse<ListSecretVersionIdsResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new ListSecretVersionIdsResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Lists all of the secrets that are stored by Secrets Manager in the AWS account. To list the versions currently
* stored for a specific secret, use <a>ListSecretVersionIds</a>. The encrypted fields <code>SecretString</code> and
* <code>SecretBinary</code> are not included in the output. To get that information, call the <a>GetSecretValue</a>
* operation.
* </p>
* <note>
* <p>
* Always check the <code>NextToken</code> response parameter when calling any of the <code>List*</code> operations.
* These operations can occasionally return an empty or shorter than expected list of results even when there are
* more results available. When this happens, the <code>NextToken</code> response parameter contains a value to pass
* to the next call to the same API to request the next part of the list.
* </p>
* </note>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>
* To run this command, you must have the following permissions:
* </p>
* <ul>
* <li>
* <p>
* secretsmanager:ListSecrets
* </p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>
* To list the versions attached to a secret, use <a>ListSecretVersionIds</a>.
* </p>
* </li>
* </ul>
*
* @param listSecretsRequest
* @return Result of the ListSecrets operation returned by the service.
* @throws InvalidParameterException
* You provided an invalid value for a parameter.
* @throws InvalidNextTokenException
* You provided an invalid <code>NextToken</code> value.
* @throws InternalServiceErrorException
* An error occurred on the server side.
* @sample AWSSecretsManager.ListSecrets
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/ListSecrets" target="_top">AWS API
* Documentation</a>
*/
@Override
public ListSecretsResult listSecrets(ListSecretsRequest request) {
request = beforeClientExecution(request);
return executeListSecrets(request);
}
@SdkInternalApi
final ListSecretsResult executeListSecrets(ListSecretsRequest listSecretsRequest) {
ExecutionContext executionContext = createExecutionContext(listSecretsRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<ListSecretsRequest> request = null;
Response<ListSecretsResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new ListSecretsRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(listSecretsRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Secrets Manager");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "ListSecrets");
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
URI cachedEndpoint = null;
HttpResponseHandler<AmazonWebServiceResponse<ListSecretsResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new ListSecretsResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Attaches the contents of the specified resource-based permission policy to a secret. A resource-based policy is
* optional. Alternatively, you can use IAM identity-based policies that specify the secret's Amazon Resource Name
* (ARN) in the policy statement's <code>Resources</code> element. You can also use a combination of both
* identity-based and resource-based policies. The affected users and roles receive the permissions that are
* permitted by all of the relevant policies. For more information, see <a
* href="http://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access_resource-based-policies.html"
* >Using Resource-Based Policies for AWS Secrets Manager</a>. For the complete description of the AWS policy syntax
* and grammar, see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies.html">IAM JSON
* Policy Reference</a> in the <i>IAM User Guide</i>.
* </p>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>
* To run this command, you must have the following permissions:
* </p>
* <ul>
* <li>
* <p>
* secretsmanager:PutResourcePolicy
* </p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>
* To retrieve the resource policy that's attached to a secret, use <a>GetResourcePolicy</a>.
* </p>
* </li>
* <li>
* <p>
* To delete the resource-based policy that's attached to a secret, use <a>DeleteResourcePolicy</a>.
* </p>
* </li>
* <li>
* <p>
* To list all of the currently available secrets, use <a>ListSecrets</a>.
* </p>
* </li>
* </ul>
*
* @param putResourcePolicyRequest
* @return Result of the PutResourcePolicy operation returned by the service.
* @throws MalformedPolicyDocumentException
* The policy document that you provided isn't valid.
* @throws ResourceNotFoundException
* We can't find the resource that you asked for.
* @throws InvalidParameterException
* You provided an invalid value for a parameter.
* @throws InternalServiceErrorException
* An error occurred on the server side.
* @throws InvalidRequestException
* You provided a parameter value that is not valid for the current state of the resource.</p>
* <p>
* Possible causes:
* </p>
* <ul>
* <li>
* <p>
* You tried to perform the operation on a secret that's currently marked deleted.
* </p>
* </li>
* <li>
* <p>
* You tried to enable rotation on a secret that doesn't already have a Lambda function ARN configured and
* you didn't include such an ARN as a parameter in this call.
* </p>
* </li>
* @sample AWSSecretsManager.PutResourcePolicy
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/PutResourcePolicy"
* target="_top">AWS API Documentation</a>
*/
@Override
public PutResourcePolicyResult putResourcePolicy(PutResourcePolicyRequest request) {
request = beforeClientExecution(request);
return executePutResourcePolicy(request);
}
@SdkInternalApi
final PutResourcePolicyResult executePutResourcePolicy(PutResourcePolicyRequest putResourcePolicyRequest) {
ExecutionContext executionContext = createExecutionContext(putResourcePolicyRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<PutResourcePolicyRequest> request = null;
Response<PutResourcePolicyResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new PutResourcePolicyRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(putResourcePolicyRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Secrets Manager");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "PutResourcePolicy");
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
URI cachedEndpoint = null;
HttpResponseHandler<AmazonWebServiceResponse<PutResourcePolicyResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new PutResourcePolicyResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Stores a new encrypted secret value in the specified secret. To do this, the operation creates a new version and
* attaches it to the secret. The version can contain a new <code>SecretString</code> value or a new
* <code>SecretBinary</code> value. You can also specify the staging labels that are initially attached to the new
* version.
* </p>
* <note>
* <p>
* The Secrets Manager console uses only the <code>SecretString</code> field. To add binary data to a secret with
* the <code>SecretBinary</code> field you must use the AWS CLI or one of the AWS SDKs.
* </p>
* </note>
* <ul>
* <li>
* <p>
* If this operation creates the first version for the secret then Secrets Manager automatically attaches the
* staging label <code>AWSCURRENT</code> to the new version.
* </p>
* </li>
* <li>
* <p>
* If another version of this secret already exists, then this operation does not automatically move any staging
* labels other than those that you explicitly specify in the <code>VersionStages</code> parameter.
* </p>
* </li>
* <li>
* <p>
* If this operation moves the staging label <code>AWSCURRENT</code> from another version to this version (because
* you included it in the <code>StagingLabels</code> parameter) then Secrets Manager also automatically moves the
* staging label <code>AWSPREVIOUS</code> to the version that <code>AWSCURRENT</code> was removed from.
* </p>
* </li>
* <li>
* <p>
* This operation is idempotent. If a version with a <code>VersionId</code> with the same value as the
* <code>ClientRequestToken</code> parameter already exists and you specify the same secret data, the operation
* succeeds but does nothing. However, if the secret data is different, then the operation fails because you cannot
* modify an existing version; you can only create new ones.
* </p>
* </li>
* </ul>
* <note>
* <ul>
* <li>
* <p>
* If you call an operation that needs to encrypt or decrypt the <code>SecretString</code> or
* <code>SecretBinary</code> for a secret in the same account as the calling user and that secret doesn't specify a
* AWS KMS encryption key, Secrets Manager uses the account's default AWS managed customer master key (CMK) with the
* alias <code>aws/secretsmanager</code>. If this key doesn't already exist in your account then Secrets Manager
* creates it for you automatically. All users and roles in the same AWS account automatically have access to use
* the default CMK. Note that if an Secrets Manager API call results in AWS having to create the account's
* AWS-managed CMK, it can result in a one-time significant delay in returning the result.
* </p>
* </li>
* <li>
* <p>
* If the secret is in a different AWS account from the credentials calling an API that requires encryption or
* decryption of the secret value then you must create and use a custom AWS KMS CMK because you can't access the
* default CMK for the account using credentials from a different AWS account. Store the ARN of the CMK in the
* secret when you create the secret or when you update it by including it in the <code>KMSKeyId</code>. If you call
* an API that must encrypt or decrypt <code>SecretString</code> or <code>SecretBinary</code> using credentials from
* a different account then the AWS KMS key policy must grant cross-account access to that other account's user or
* role for both the kms:GenerateDataKey and kms:Decrypt operations.
* </p>
* </li>
* </ul>
* </note>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>
* To run this command, you must have the following permissions:
* </p>
* <ul>
* <li>
* <p>
* secretsmanager:PutSecretValue
* </p>
* </li>
* <li>
* <p>
* kms:GenerateDataKey - needed only if you use a customer-managed AWS KMS key to encrypt the secret. You do not
* need this permission to use the account's default AWS managed CMK for Secrets Manager.
* </p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>
* To retrieve the encrypted value you store in the version of a secret, use <a>GetSecretValue</a>.
* </p>
* </li>
* <li>
* <p>
* To create a secret, use <a>CreateSecret</a>.
* </p>
* </li>
* <li>
* <p>
* To get the details for a secret, use <a>DescribeSecret</a>.
* </p>
* </li>
* <li>
* <p>
* To list the versions attached to a secret, use <a>ListSecretVersionIds</a>.
* </p>
* </li>
* </ul>
*
* @param putSecretValueRequest
* @return Result of the PutSecretValue operation returned by the service.
* @throws InvalidParameterException
* You provided an invalid value for a parameter.
* @throws InvalidRequestException
* You provided a parameter value that is not valid for the current state of the resource.</p>
* <p>
* Possible causes:
* </p>
* <ul>
* <li>
* <p>
* You tried to perform the operation on a secret that's currently marked deleted.
* </p>
* </li>
* <li>
* <p>
* You tried to enable rotation on a secret that doesn't already have a Lambda function ARN configured and
* you didn't include such an ARN as a parameter in this call.
* </p>
* </li>
* @throws LimitExceededException
* The request failed because it would exceed one of the Secrets Manager internal limits.
* @throws EncryptionFailureException
* Secrets Manager can't encrypt the protected secret text using the provided KMS key. Check that the
* customer master key (CMK) is available, enabled, and not in an invalid state. For more information, see
* <a href="http://docs.aws.amazon.com/kms/latest/developerguide/key-state.html">How Key State Affects Use
* of a Customer Master Key</a>.
* @throws ResourceExistsException
* A resource with the ID you requested already exists.
* @throws ResourceNotFoundException
* We can't find the resource that you asked for.
* @throws InternalServiceErrorException
* An error occurred on the server side.
* @sample AWSSecretsManager.PutSecretValue
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/PutSecretValue" target="_top">AWS
* API Documentation</a>
*/
@Override
public PutSecretValueResult putSecretValue(PutSecretValueRequest request) {
request = beforeClientExecution(request);
return executePutSecretValue(request);
}
@SdkInternalApi
final PutSecretValueResult executePutSecretValue(PutSecretValueRequest putSecretValueRequest) {
ExecutionContext executionContext = createExecutionContext(putSecretValueRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<PutSecretValueRequest> request = null;
Response<PutSecretValueResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new PutSecretValueRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(putSecretValueRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Secrets Manager");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "PutSecretValue");
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
URI cachedEndpoint = null;
HttpResponseHandler<AmazonWebServiceResponse<PutSecretValueResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new PutSecretValueResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Cancels the scheduled deletion of a secret by removing the <code>DeletedDate</code> time stamp. This makes the
* secret accessible to query once again.
* </p>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>
* To run this command, you must have the following permissions:
* </p>
* <ul>
* <li>
* <p>
* secretsmanager:RestoreSecret
* </p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>
* To delete a secret, use <a>DeleteSecret</a>.
* </p>
* </li>
* </ul>
*
* @param restoreSecretRequest
* @return Result of the RestoreSecret operation returned by the service.
* @throws ResourceNotFoundException
* We can't find the resource that you asked for.
* @throws InvalidParameterException
* You provided an invalid value for a parameter.
* @throws InvalidRequestException
* You provided a parameter value that is not valid for the current state of the resource.</p>
* <p>
* Possible causes:
* </p>
* <ul>
* <li>
* <p>
* You tried to perform the operation on a secret that's currently marked deleted.
* </p>
* </li>
* <li>
* <p>
* You tried to enable rotation on a secret that doesn't already have a Lambda function ARN configured and
* you didn't include such an ARN as a parameter in this call.
* </p>
* </li>
* @throws InternalServiceErrorException
* An error occurred on the server side.
* @sample AWSSecretsManager.RestoreSecret
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/RestoreSecret" target="_top">AWS
* API Documentation</a>
*/
@Override
public RestoreSecretResult restoreSecret(RestoreSecretRequest request) {
request = beforeClientExecution(request);
return executeRestoreSecret(request);
}
@SdkInternalApi
final RestoreSecretResult executeRestoreSecret(RestoreSecretRequest restoreSecretRequest) {
ExecutionContext executionContext = createExecutionContext(restoreSecretRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<RestoreSecretRequest> request = null;
Response<RestoreSecretResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new RestoreSecretRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(restoreSecretRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Secrets Manager");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "RestoreSecret");
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
URI cachedEndpoint = null;
HttpResponseHandler<AmazonWebServiceResponse<RestoreSecretResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new RestoreSecretResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Configures and starts the asynchronous process of rotating this secret. If you include the configuration
* parameters, the operation sets those values for the secret and then immediately starts a rotation. If you do not
* include the configuration parameters, the operation starts a rotation with the values already stored in the
* secret. After the rotation completes, the protected service and its clients all use the new version of the
* secret.
* </p>
* <p>
* This required configuration information includes the ARN of an AWS Lambda function and the time between scheduled
* rotations. The Lambda rotation function creates a new version of the secret and creates or updates the
* credentials on the protected service to match. After testing the new credentials, the function marks the new
* secret with the staging label <code>AWSCURRENT</code> so that your clients all immediately begin to use the new
* version. For more information about rotating secrets and how to configure a Lambda function to rotate the secrets
* for your protected service, see <a
* href="http://docs.aws.amazon.com/secretsmanager/latest/userguide/rotating-secrets.html">Rotating Secrets in AWS
* Secrets Manager</a> in the <i>AWS Secrets Manager User Guide</i>.
* </p>
* <p>
* Secrets Manager schedules the next rotation when the previous one is complete. Secrets Manager schedules the date
* by adding the rotation interval (number of days) to the actual date of the last rotation. The service chooses the
* hour within that 24-hour date window randomly. The minute is also chosen somewhat randomly, but weighted towards
* the top of the hour and influenced by a variety of factors that help distribute load.
* </p>
* <p>
* The rotation function must end with the versions of the secret in one of two states:
* </p>
* <ul>
* <li>
* <p>
* The <code>AWSPENDING</code> and <code>AWSCURRENT</code> staging labels are attached to the same version of the
* secret, or
* </p>
* </li>
* <li>
* <p>
* The <code>AWSPENDING</code> staging label is not attached to any version of the secret.
* </p>
* </li>
* </ul>
* <p>
* If instead the <code>AWSPENDING</code> staging label is present but is not attached to the same version as
* <code>AWSCURRENT</code> then any later invocation of <code>RotateSecret</code> assumes that a previous rotation
* request is still in progress and returns an error.
* </p>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>
* To run this command, you must have the following permissions:
* </p>
* <ul>
* <li>
* <p>
* secretsmanager:RotateSecret
* </p>
* </li>
* <li>
* <p>
* lambda:InvokeFunction (on the function specified in the secret's metadata)
* </p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>
* To list the secrets in your account, use <a>ListSecrets</a>.
* </p>
* </li>
* <li>
* <p>
* To get the details for a version of a secret, use <a>DescribeSecret</a>.
* </p>
* </li>
* <li>
* <p>
* To create a new version of a secret, use <a>CreateSecret</a>.
* </p>
* </li>
* <li>
* <p>
* To attach staging labels to or remove staging labels from a version of a secret, use
* <a>UpdateSecretVersionStage</a>.
* </p>
* </li>
* </ul>
*
* @param rotateSecretRequest
* @return Result of the RotateSecret operation returned by the service.
* @throws ResourceNotFoundException
* We can't find the resource that you asked for.
* @throws InvalidParameterException
* You provided an invalid value for a parameter.
* @throws InternalServiceErrorException
* An error occurred on the server side.
* @throws InvalidRequestException
* You provided a parameter value that is not valid for the current state of the resource.</p>
* <p>
* Possible causes:
* </p>
* <ul>
* <li>
* <p>
* You tried to perform the operation on a secret that's currently marked deleted.
* </p>
* </li>
* <li>
* <p>
* You tried to enable rotation on a secret that doesn't already have a Lambda function ARN configured and
* you didn't include such an ARN as a parameter in this call.
* </p>
* </li>
* @sample AWSSecretsManager.RotateSecret
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/RotateSecret" target="_top">AWS
* API Documentation</a>
*/
@Override
public RotateSecretResult rotateSecret(RotateSecretRequest request) {
request = beforeClientExecution(request);
return executeRotateSecret(request);
}
@SdkInternalApi
final RotateSecretResult executeRotateSecret(RotateSecretRequest rotateSecretRequest) {
ExecutionContext executionContext = createExecutionContext(rotateSecretRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<RotateSecretRequest> request = null;
Response<RotateSecretResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new RotateSecretRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(rotateSecretRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Secrets Manager");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "RotateSecret");
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
URI cachedEndpoint = null;
HttpResponseHandler<AmazonWebServiceResponse<RotateSecretResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new RotateSecretResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Attaches one or more tags, each consisting of a key name and a value, to the specified secret. Tags are part of
* the secret's overall metadata, and are not associated with any specific version of the secret. This operation
* only appends tags to the existing list of tags. To remove tags, you must use <a>UntagResource</a>.
* </p>
* <p>
* The following basic restrictions apply to tags:
* </p>
* <ul>
* <li>
* <p>
* Maximum number of tags per secret—50
* </p>
* </li>
* <li>
* <p>
* Maximum key length—127 Unicode characters in UTF-8
* </p>
* </li>
* <li>
* <p>
* Maximum value length—255 Unicode characters in UTF-8
* </p>
* </li>
* <li>
* <p>
* Tag keys and values are case sensitive.
* </p>
* </li>
* <li>
* <p>
* Do not use the <code>aws:</code> prefix in your tag names or values because it is reserved for AWS use. You can't
* edit or delete tag names or values with this prefix. Tags with this prefix do not count against your tags per
* secret limit.
* </p>
* </li>
* <li>
* <p>
* If your tagging schema will be used across multiple services and resources, remember that other services might
* have restrictions on allowed characters. Generally allowed characters are: letters, spaces, and numbers
* representable in UTF-8, plus the following special characters: + - = . _ : / @.
* </p>
* </li>
* </ul>
* <important>
* <p>
* If you use tags as part of your security strategy, then adding or removing a tag can change permissions. If
* successfully completing this operation would result in you losing your permissions for this secret, then the
* operation is blocked and returns an Access Denied error.
* </p>
* </important>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>
* To run this command, you must have the following permissions:
* </p>
* <ul>
* <li>
* <p>
* secretsmanager:TagResource
* </p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>
* To remove one or more tags from the collection attached to a secret, use <a>UntagResource</a>.
* </p>
* </li>
* <li>
* <p>
* To view the list of tags attached to a secret, use <a>DescribeSecret</a>.
* </p>
* </li>
* </ul>
*
* @param tagResourceRequest
* @return Result of the TagResource operation returned by the service.
* @throws ResourceNotFoundException
* We can't find the resource that you asked for.
* @throws InvalidRequestException
* You provided a parameter value that is not valid for the current state of the resource.</p>
* <p>
* Possible causes:
* </p>
* <ul>
* <li>
* <p>
* You tried to perform the operation on a secret that's currently marked deleted.
* </p>
* </li>
* <li>
* <p>
* You tried to enable rotation on a secret that doesn't already have a Lambda function ARN configured and
* you didn't include such an ARN as a parameter in this call.
* </p>
* </li>
* @throws InvalidParameterException
* You provided an invalid value for a parameter.
* @throws InternalServiceErrorException
* An error occurred on the server side.
* @sample AWSSecretsManager.TagResource
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/TagResource" target="_top">AWS API
* Documentation</a>
*/
@Override
public TagResourceResult tagResource(TagResourceRequest request) {
request = beforeClientExecution(request);
return executeTagResource(request);
}
@SdkInternalApi
final TagResourceResult executeTagResource(TagResourceRequest tagResourceRequest) {
ExecutionContext executionContext = createExecutionContext(tagResourceRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<TagResourceRequest> request = null;
Response<TagResourceResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new TagResourceRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(tagResourceRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Secrets Manager");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "TagResource");
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
URI cachedEndpoint = null;
HttpResponseHandler<AmazonWebServiceResponse<TagResourceResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new TagResourceResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Removes one or more tags from the specified secret.
* </p>
* <p>
* This operation is idempotent. If a requested tag is not attached to the secret, no error is returned and the
* secret metadata is unchanged.
* </p>
* <important>
* <p>
* If you use tags as part of your security strategy, then removing a tag can change permissions. If successfully
* completing this operation would result in you losing your permissions for this secret, then the operation is
* blocked and returns an Access Denied error.
* </p>
* </important>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>
* To run this command, you must have the following permissions:
* </p>
* <ul>
* <li>
* <p>
* secretsmanager:UntagResource
* </p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>
* To add one or more tags to the collection attached to a secret, use <a>TagResource</a>.
* </p>
* </li>
* <li>
* <p>
* To view the list of tags attached to a secret, use <a>DescribeSecret</a>.
* </p>
* </li>
* </ul>
*
* @param untagResourceRequest
* @return Result of the UntagResource operation returned by the service.
* @throws ResourceNotFoundException
* We can't find the resource that you asked for.
* @throws InvalidRequestException
* You provided a parameter value that is not valid for the current state of the resource.</p>
* <p>
* Possible causes:
* </p>
* <ul>
* <li>
* <p>
* You tried to perform the operation on a secret that's currently marked deleted.
* </p>
* </li>
* <li>
* <p>
* You tried to enable rotation on a secret that doesn't already have a Lambda function ARN configured and
* you didn't include such an ARN as a parameter in this call.
* </p>
* </li>
* @throws InvalidParameterException
* You provided an invalid value for a parameter.
* @throws InternalServiceErrorException
* An error occurred on the server side.
* @sample AWSSecretsManager.UntagResource
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/UntagResource" target="_top">AWS
* API Documentation</a>
*/
@Override
public UntagResourceResult untagResource(UntagResourceRequest request) {
request = beforeClientExecution(request);
return executeUntagResource(request);
}
@SdkInternalApi
final UntagResourceResult executeUntagResource(UntagResourceRequest untagResourceRequest) {
ExecutionContext executionContext = createExecutionContext(untagResourceRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<UntagResourceRequest> request = null;
Response<UntagResourceResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new UntagResourceRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(untagResourceRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Secrets Manager");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "UntagResource");
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
URI cachedEndpoint = null;
HttpResponseHandler<AmazonWebServiceResponse<UntagResourceResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new UntagResourceResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Modifies many of the details of the specified secret. If you include a <code>ClientRequestToken</code> and
* <i>either</i> <code>SecretString</code> or <code>SecretBinary</code> then it also creates a new version attached
* to the secret.
* </p>
* <p>
* To modify the rotation configuration of a secret, use <a>RotateSecret</a> instead.
* </p>
* <note>
* <p>
* The Secrets Manager console uses only the <code>SecretString</code> parameter and therefore limits you to
* encrypting and storing only a text string. To encrypt and store binary data as part of the version of a secret,
* you must use either the AWS CLI or one of the AWS SDKs.
* </p>
* </note>
* <ul>
* <li>
* <p>
* If a version with a <code>VersionId</code> with the same value as the <code>ClientRequestToken</code> parameter
* already exists, the operation results in an error. You cannot modify an existing version, you can only create a
* new version.
* </p>
* </li>
* <li>
* <p>
* If you include <code>SecretString</code> or <code>SecretBinary</code> to create a new secret version, Secrets
* Manager automatically attaches the staging label <code>AWSCURRENT</code> to the new version.
* </p>
* </li>
* </ul>
* <note>
* <ul>
* <li>
* <p>
* If you call an operation that needs to encrypt or decrypt the <code>SecretString</code> or
* <code>SecretBinary</code> for a secret in the same account as the calling user and that secret doesn't specify a
* AWS KMS encryption key, Secrets Manager uses the account's default AWS managed customer master key (CMK) with the
* alias <code>aws/secretsmanager</code>. If this key doesn't already exist in your account then Secrets Manager
* creates it for you automatically. All users and roles in the same AWS account automatically have access to use
* the default CMK. Note that if an Secrets Manager API call results in AWS having to create the account's
* AWS-managed CMK, it can result in a one-time significant delay in returning the result.
* </p>
* </li>
* <li>
* <p>
* If the secret is in a different AWS account from the credentials calling an API that requires encryption or
* decryption of the secret value then you must create and use a custom AWS KMS CMK because you can't access the
* default CMK for the account using credentials from a different AWS account. Store the ARN of the CMK in the
* secret when you create the secret or when you update it by including it in the <code>KMSKeyId</code>. If you call
* an API that must encrypt or decrypt <code>SecretString</code> or <code>SecretBinary</code> using credentials from
* a different account then the AWS KMS key policy must grant cross-account access to that other account's user or
* role for both the kms:GenerateDataKey and kms:Decrypt operations.
* </p>
* </li>
* </ul>
* </note>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>
* To run this command, you must have the following permissions:
* </p>
* <ul>
* <li>
* <p>
* secretsmanager:UpdateSecret
* </p>
* </li>
* <li>
* <p>
* kms:GenerateDataKey - needed only if you use a custom AWS KMS key to encrypt the secret. You do not need this
* permission to use the account's AWS managed CMK for Secrets Manager.
* </p>
* </li>
* <li>
* <p>
* kms:Decrypt - needed only if you use a custom AWS KMS key to encrypt the secret. You do not need this permission
* to use the account's AWS managed CMK for Secrets Manager.
* </p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>
* To create a new secret, use <a>CreateSecret</a>.
* </p>
* </li>
* <li>
* <p>
* To add only a new version to an existing secret, use <a>PutSecretValue</a>.
* </p>
* </li>
* <li>
* <p>
* To get the details for a secret, use <a>DescribeSecret</a>.
* </p>
* </li>
* <li>
* <p>
* To list the versions contained in a secret, use <a>ListSecretVersionIds</a>.
* </p>
* </li>
* </ul>
*
* @param updateSecretRequest
* @return Result of the UpdateSecret operation returned by the service.
* @throws InvalidParameterException
* You provided an invalid value for a parameter.
* @throws InvalidRequestException
* You provided a parameter value that is not valid for the current state of the resource.</p>
* <p>
* Possible causes:
* </p>
* <ul>
* <li>
* <p>
* You tried to perform the operation on a secret that's currently marked deleted.
* </p>
* </li>
* <li>
* <p>
* You tried to enable rotation on a secret that doesn't already have a Lambda function ARN configured and
* you didn't include such an ARN as a parameter in this call.
* </p>
* </li>
* @throws LimitExceededException
* The request failed because it would exceed one of the Secrets Manager internal limits.
* @throws EncryptionFailureException
* Secrets Manager can't encrypt the protected secret text using the provided KMS key. Check that the
* customer master key (CMK) is available, enabled, and not in an invalid state. For more information, see
* <a href="http://docs.aws.amazon.com/kms/latest/developerguide/key-state.html">How Key State Affects Use
* of a Customer Master Key</a>.
* @throws ResourceExistsException
* A resource with the ID you requested already exists.
* @throws ResourceNotFoundException
* We can't find the resource that you asked for.
* @throws MalformedPolicyDocumentException
* The policy document that you provided isn't valid.
* @throws InternalServiceErrorException
* An error occurred on the server side.
* @throws PreconditionNotMetException
* The request failed because you did not complete all the prerequisite steps.
* @sample AWSSecretsManager.UpdateSecret
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/UpdateSecret" target="_top">AWS
* API Documentation</a>
*/
@Override
public UpdateSecretResult updateSecret(UpdateSecretRequest request) {
request = beforeClientExecution(request);
return executeUpdateSecret(request);
}
@SdkInternalApi
final UpdateSecretResult executeUpdateSecret(UpdateSecretRequest updateSecretRequest) {
ExecutionContext executionContext = createExecutionContext(updateSecretRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<UpdateSecretRequest> request = null;
Response<UpdateSecretResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new UpdateSecretRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(updateSecretRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Secrets Manager");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "UpdateSecret");
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
URI cachedEndpoint = null;
HttpResponseHandler<AmazonWebServiceResponse<UpdateSecretResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new UpdateSecretResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* <p>
* Modifies the staging labels attached to a version of a secret. Staging labels are used to track a version as it
* progresses through the secret rotation process. You can attach a staging label to only one version of a secret at
* a time. If a staging label to be added is already attached to another version, then it is moved--removed from the
* other version first and then attached to this one. For more information about staging labels, see <a
* href="http://docs.aws.amazon.com/secretsmanager/latest/userguide/terms-concepts.html#term_staging-label">Staging
* Labels</a> in the <i>AWS Secrets Manager User Guide</i>.
* </p>
* <p>
* The staging labels that you specify in the <code>VersionStage</code> parameter are added to the existing list of
* staging labels--they don't replace it.
* </p>
* <p>
* You can move the <code>AWSCURRENT</code> staging label to this version by including it in this call.
* </p>
* <note>
* <p>
* Whenever you move <code>AWSCURRENT</code>, Secrets Manager automatically moves the label <code>AWSPREVIOUS</code>
* to the version that <code>AWSCURRENT</code> was removed from.
* </p>
* </note>
* <p>
* If this action results in the last label being removed from a version, then the version is considered to be
* 'deprecated' and can be deleted by Secrets Manager.
* </p>
* <p>
* <b>Minimum permissions</b>
* </p>
* <p>
* To run this command, you must have the following permissions:
* </p>
* <ul>
* <li>
* <p>
* secretsmanager:UpdateSecretVersionStage
* </p>
* </li>
* </ul>
* <p>
* <b>Related operations</b>
* </p>
* <ul>
* <li>
* <p>
* To get the list of staging labels that are currently associated with a version of a secret, use
* <code> <a>DescribeSecret</a> </code> and examine the <code>SecretVersionsToStages</code> response value.
* </p>
* </li>
* </ul>
*
* @param updateSecretVersionStageRequest
* @return Result of the UpdateSecretVersionStage operation returned by the service.
* @throws ResourceNotFoundException
* We can't find the resource that you asked for.
* @throws InvalidParameterException
* You provided an invalid value for a parameter.
* @throws InvalidRequestException
* You provided a parameter value that is not valid for the current state of the resource.</p>
* <p>
* Possible causes:
* </p>
* <ul>
* <li>
* <p>
* You tried to perform the operation on a secret that's currently marked deleted.
* </p>
* </li>
* <li>
* <p>
* You tried to enable rotation on a secret that doesn't already have a Lambda function ARN configured and
* you didn't include such an ARN as a parameter in this call.
* </p>
* </li>
* @throws LimitExceededException
* The request failed because it would exceed one of the Secrets Manager internal limits.
* @throws InternalServiceErrorException
* An error occurred on the server side.
* @sample AWSSecretsManager.UpdateSecretVersionStage
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/secretsmanager-2017-10-17/UpdateSecretVersionStage"
* target="_top">AWS API Documentation</a>
*/
@Override
public UpdateSecretVersionStageResult updateSecretVersionStage(UpdateSecretVersionStageRequest request) {
request = beforeClientExecution(request);
return executeUpdateSecretVersionStage(request);
}
@SdkInternalApi
final UpdateSecretVersionStageResult executeUpdateSecretVersionStage(UpdateSecretVersionStageRequest updateSecretVersionStageRequest) {
ExecutionContext executionContext = createExecutionContext(updateSecretVersionStageRequest);
AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();
awsRequestMetrics.startEvent(Field.ClientExecuteTime);
Request<UpdateSecretVersionStageRequest> request = null;
Response<UpdateSecretVersionStageResult> response = null;
try {
awsRequestMetrics.startEvent(Field.RequestMarshallTime);
try {
request = new UpdateSecretVersionStageRequestProtocolMarshaller(protocolFactory).marshall(super
.beforeMarshalling(updateSecretVersionStageRequest));
// Binds the request metrics to the current request.
request.setAWSRequestMetrics(awsRequestMetrics);
request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());
request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Secrets Manager");
request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "UpdateSecretVersionStage");
} finally {
awsRequestMetrics.endEvent(Field.RequestMarshallTime);
}
URI cachedEndpoint = null;
HttpResponseHandler<AmazonWebServiceResponse<UpdateSecretVersionStageResult>> responseHandler = protocolFactory.createResponseHandler(
new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false),
new UpdateSecretVersionStageResultJsonUnmarshaller());
response = invoke(request, responseHandler, executionContext);
return response.getAwsResponse();
} finally {
endClientExecution(awsRequestMetrics, request, response);
}
}
/**
* Returns additional metadata for a previously executed successful, request, typically used for debugging issues
* where a service isn't acting as expected. This data isn't considered part of the result data returned by an
* operation, so it's available through this separate, diagnostic interface.
* <p>
* Response metadata is only cached for a limited period of time, so if you need to access this extra diagnostic
* information for an executed request, you should use this method to retrieve it as soon as possible after
* executing the request.
*
* @param request
* The originally executed request
*
* @return The response metadata for the specified request, or null if none is available.
*/
public ResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest request) {
return client.getResponseMetadataForRequest(request);
}
/**
* Normal invoke with authentication. Credentials are required and may be overriden at the request level.
**/
private <X, Y extends AmazonWebServiceRequest> Response<X> invoke(Request<Y> request, HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler,
ExecutionContext executionContext) {
return invoke(request, responseHandler, executionContext, null);
}
/**
* Normal invoke with authentication. Credentials are required and may be overriden at the request level.
**/
private <X, Y extends AmazonWebServiceRequest> Response<X> invoke(Request<Y> request, HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler,
ExecutionContext executionContext, URI cachedEndpoint) {
executionContext.setCredentialsProvider(CredentialUtils.getCredentialsProvider(request.getOriginalRequest(), awsCredentialsProvider));
return doInvoke(request, responseHandler, executionContext, cachedEndpoint);
}
/**
* Invoke with no authentication. Credentials are not required and any credentials set on the client or request will
* be ignored for this operation.
**/
private <X, Y extends AmazonWebServiceRequest> Response<X> anonymousInvoke(Request<Y> request,
HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler, ExecutionContext executionContext) {
return doInvoke(request, responseHandler, executionContext, null);
}
/**
* Invoke the request using the http client. Assumes credentials (or lack thereof) have been configured in the
* ExecutionContext beforehand.
**/
private <X, Y extends AmazonWebServiceRequest> Response<X> doInvoke(Request<Y> request, HttpResponseHandler<AmazonWebServiceResponse<X>> responseHandler,
ExecutionContext executionContext, URI discoveredEndpoint) {
if (discoveredEndpoint != null) {
request.setEndpoint(discoveredEndpoint);
request.getOriginalRequest().getRequestClientOptions().appendUserAgent("endpoint-discovery");
} else {
request.setEndpoint(endpoint);
}
request.setTimeOffset(timeOffset);
HttpResponseHandler<AmazonServiceException> errorResponseHandler = protocolFactory.createErrorResponseHandler(new JsonErrorResponseMetadata());
return client.execute(request, responseHandler, errorResponseHandler, executionContext);
}
@com.amazonaws.annotation.SdkInternalApi
static com.amazonaws.protocol.json.SdkJsonProtocolFactory getProtocolFactory() {
return protocolFactory;
}
}
| [
""
]
| |
ffca59fc76fd87e74fd86917cd71b7ce23b819f0 | 5b62981e0a3b016c6e32aef3a5d829f3b5ca5c88 | /src/test_Suite/tests/rptFunctions/RF_PopProfileEForm.java | 6cc0d6ff94979cb9657468ffab387fcd0f7a9c0d | []
| no_license | kamaltechnocrat/JMeter | c1f61416fb832d97ad4f09e022a80a2a74c2f01b | cd36cf4185949e8516c446f6705f4144eb6bfb19 | refs/heads/master | 2020-03-15T13:40:43.682421 | 2018-05-04T18:03:34 | 2018-05-04T18:03:34 | 132,172,591 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,547 | java | /**
*
*/
package test_Suite.tests.rptFunctions;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.fest.swing.annotation.GUITest;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import test_Suite.constants.eForms.IEFormsConst;
import test_Suite.constants.ui.IClicksConst;
import test_Suite.constants.ui.ITablesConst;
import test_Suite.lib.eForms.EForm;
import test_Suite.lib.eForms.EFormField;
import test_Suite.lib.eForms.Formlet;
import test_Suite.lib.workflow.Project;
import test_Suite.utils.cases.GeneralUtil;
import test_Suite.utils.reporting_Functions.RptFuncUtil;
import test_Suite.utils.ui.ClicksUtil;
import test_Suite.utils.ui.IEUtil;
import test_Suite.utils.ui.TablesUtil;
/**
* @author mshakshouki
*
*/
@GUITest
@Test(singleThreaded = true)
public class RF_PopProfileEForm {
/*********** Variables Declaration Section ********************/
Class<?> ownClass = this.getClass();
private Log log = LogFactory.getLog(ownClass);
EForm form;
Formlet formlet;
EFormField eFormField;
Project proj;
String preFix = "";
String postFix = "";
boolean isItNewOrg = true;
String orgName = "-Applicant-eForm-Reporting-Function";
/*********** End ofVariables Declaration Section ********************/
@BeforeClass(groups = { "SetupReportingFunctionsNG" })
public void setUp() {
try {
log.warn("Starting: " + this.getClass().getSimpleName());
IEUtil.openNewBrowser();
GeneralUtil.navigateToPO();
GeneralUtil.logInSuper();
form = new EForm();
form.setEFormType(IEFormsConst.applicantWorkspace_FormTypeName);
form.setEFormSubType(IEFormsConst.applicantWorkspace_FormTypeName);
form.setEFormTitle("Applicant Profile Reporting Function");
form.setEFormId("Test-Applicant-Reporting-Function");
GeneralUtil.setApplicantWorkspace(form.getEFormId());
proj = new Project();
proj.setOrgName(orgName);
proj.setProgPreFix("-Applicant-");
proj.setPostfix(postFix);
proj.createOrgFullName(isItNewOrg);
} catch (Exception e) {
log.error("Unexpected Exception", e);
throw new RuntimeException("Unexpected Exception", e);
}
}
@AfterClass(groups = { "SetupReportingFunctionsNG" }, alwaysRun=true)
public void tearDown() throws Exception {
ClicksUtil.clickLinks("Submission Summary");
ClicksUtil.clickButtons(IClicksConst.completeBtn);
form = null;
proj = null;
formlet = null;
eFormField = null;
GeneralUtil.Logoff();
IEUtil.closeBrowser();
log.warn("Ending: " + this.getClass().getSimpleName());
}
@Test(groups = { "SetupReportingFunctionsNG" })
public void testApplicantEFormReportingFunctionNG() throws Exception {
Assert.assertTrue(TablesUtil.openInTableByImage(
ITablesConst.applicantsTableId, proj.getOrgFullName(), 3),
"Fail: could not Open Applicant Profile");
fill_EForm();
}
private void fill_EForm() throws Exception {
try {
RptFuncUtil.fill_NoProperties_FieldsData();
RptFuncUtil.fill_eList_FormletData();
RptFuncUtil.fill_Dropdown_FieldsData();
RptFuncUtil.fill_LookupDropdwon_FieldsData();
RptFuncUtil.fill_TypesProperties_FieldsData();
RptFuncUtil.fill_MinAndMaxProperties_FieldsData();
RptFuncUtil.fill_eListDropdown_FormletData();
RptFuncUtil.fill_eListDataGrid_FormletData();
} catch (Exception e) {
log.error("Unexpected Exception", e);
throw new RuntimeException("Unexpected Exception", e);
}
}
}
| [
"[email protected]"
]
| |
5c11888a642ae58ddd6f0932f640f069e4cc1892 | 71fbb52ec83c09e7a709d3c7789cb8914a6acce6 | /src/com/bridgeit/algorithm/InsertionSortString.java | 9897c637df2b0eb7c4499115eec24577494a0fa3 | []
| no_license | Nilesh1296/Program | bb870ad431a94e2c94d2e4d47f8ac625705d4c24 | 3822e70c06ac5436ca965330e63731e2eeaf4f94 | refs/heads/master | 2021-04-15T04:30:12.849018 | 2018-05-02T11:15:10 | 2018-05-02T11:15:10 | 126,833,839 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 804 | java | /******************************************************************************
* Purpose:Sort the String using insertionsort
*
* @author Nilesh singh
* @version 1.0
* @since 28-02-2018
*
******************************************************************************/
package com.bridgeit.algorithm;
import com.bridgeit.utility.Utility;
public class InsertionSortString {
public static void main(String args[]) {
Utility utility = new Utility();
System.out.println("Enter the size of the array");
int size = utility.inputInteger();
String arr[] = new String[size];
for (int i = 0; i < size; i++) {
arr[i] = utility.inputString();
}
String arr1[] = Utility.insertionSortString1(arr);
for (int i = 0; i < arr1.length; i++) {
System.out.println(arr1[i]);
}
}
}
| [
"[email protected]"
]
| |
1fdfc052a02e8a116899c503880fccdd6560285c | eb02d279218bc071466a20dcb2bbcf5e9d83c976 | /src/main/java/com/qf/service/UserTbMapperService.java | d822f9b042ae80e302440090b2d9fd062bde87a2 | []
| no_license | li62zz/pushtest2 | 3463dab5134697c7aeaebe73703ad9316c2d8b49 | b2122050a513cd1db2170947a7464fba40601e05 | refs/heads/master | 2022-12-21T16:02:23.791315 | 2019-07-23T13:22:54 | 2019-07-23T13:22:54 | 198,424,271 | 0 | 0 | null | 2022-12-10T05:19:35 | 2019-07-23T12:16:54 | HTML | UTF-8 | Java | false | false | 638 | java | package com.qf.service;
import com.github.pagehelper.PageInfo;
import com.qf.bean.UserTb;
import java.util.List;
public interface UserTbMapperService {
UserTb login(String username, String password);
boolean checkname(String name);
UserTb updateusers(UserTb userTb);
//查询全部用户和角色信息
PageInfo<UserTb> findall(int index,int size);
int deleteByPrimaryKey(Integer userId);
int insert(UserTb record);
int insertSelective(UserTb record);
UserTb selectByPrimaryKey(Integer userId);
int updateByPrimaryKeySelective(UserTb record);
int updateByPrimaryKey(UserTb record);
} | [
"[email protected]"
]
| |
5f0bd56879337a9967b7f928c2affc2a541d244e | 1e2d4e444bd1af40d69c60c333dca58a3a3e8c2b | /app/src/main/java/travel/iknow/android/LoginActivity.java | cc1bf7497f75366fe176beff9c719b452c8c07cf | []
| no_license | pristalovpavel/IKnowTravel | c978a722b4b1e50f96d0da5ddbd0d2578c94372a | db997a3823830b83e183cf5e1b56531fb4d9c449 | refs/heads/master | 2020-04-12T08:29:02.420578 | 2015-02-16T14:30:51 | 2015-02-16T14:30:51 | 30,704,406 | 0 | 0 | null | 2015-02-16T14:24:05 | 2015-02-12T13:46:48 | Java | UTF-8 | Java | false | false | 13,718 | java | package travel.iknow.android;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import travel.iknow.android.data.DataSource;
import travel.iknow.android.data.model.Local;
import travel.iknow.android.data.model.Token;
/**
* A login screen that offers login via email/password.
*/
public class LoginActivity extends ActionBarActivity implements LoaderCallbacks<Cursor>
{
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
//private UserLoginTask mAuthTask = null;
// UI references.
private EditText mNameView;
private EditText mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
private String name;
private String email;
private String password;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if(isRegistered()) startMainActivity();
Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar);
setSupportActionBar(toolbar);
// Set up the login form.
mNameView = (EditText) findViewById((R.id.name));
mEmailView = (EditText) findViewById(R.id.email);
populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener()
{
@Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent)
{
if (id == R.id.login || id == EditorInfo.IME_NULL)
{
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View view)
{
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
}
void startMainActivity()
{
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
private void populateAutoComplete()
{
getLoaderManager().initLoader(0, null, this);
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
public void attemptLogin()
{
// Reset errors.
mNameView.setError(null);
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
name = mNameView.getText().toString();
email = mEmailView.getText().toString();
password = mPasswordView.getText().toString();
if (TextUtils.isEmpty(name) || !isNameValid(name))
{
mNameView.setError(getString(R.string.error_invalid_name));
mNameView.requestFocus();
return;
}
// Check for a valid email address.
if (TextUtils.isEmpty(email) || !isEmailValid(email))
{
mEmailView.setError(getString(R.string.error_invalid_email));
mEmailView.requestFocus();
return;
}
// Check for a valid password, if the user entered one.
if (TextUtils.isEmpty(password) || !isPasswordValid(password))
{
mPasswordView.setError(getString(R.string.error_invalid_password));
mPasswordView.requestFocus();
return;
}
saveProfile(name, email, password);
showProgress(true);
performAuth();
}
private void performAuth()
{
final IKnowTravelApplication application = ((IKnowTravelApplication) getApplication());
Callback<Token> cb = new Callback<Token>()
{
/**
* Successful HTTP response.
*
* @param newToken
* @param response
*/
@Override
public void success(Token newToken, Response response)
{
Toast.makeText(LoginActivity.this, "token: " + newToken, Toast.LENGTH_SHORT)
.show();
DataSource.currentToken = newToken.getToken();
application.updateHeaders(newToken.getToken());
registration();
}
/**
* Unsuccessful HTTP response due to network failure, non-2XX status code, or unexpected
* exception.
*
* @param error
*/
@Override
public void failure(RetrofitError error)
{
Toast.makeText(LoginActivity.this, "cannot get token", Toast.LENGTH_SHORT).show();
}
};
application.apiHelper.requestToken(cb);
}
private void registration()
{
Callback<Object> cb = new Callback<Object>()
{
/**
* Successful HTTP response.
*
* @param o
* @param response
*/
@Override
public void success(Object o, Response response)
{
showProgress(false);
Toast.makeText(LoginActivity.this, "Successfully registered!", Toast.LENGTH_SHORT)
.show();
startMainActivity();
}
/**
* Unsuccessful HTTP response due to network failure, non-2XX status code, or unexpected
* exception.
*
* @param error
*/
@Override
public void failure(RetrofitError error)
{
showProgress(false);
Toast.makeText(LoginActivity.this, "cannot load", Toast.LENGTH_SHORT).show();
}
};
((IKnowTravelApplication)getApplication()).apiHelper.registration(new Local(name, email, password, true), cb);
}
private void saveProfile(String name, String email, String pass)
{
SharedPreferences.Editor editor = getSharedPreferences(DataSource.PREFERENCES_NAME, 0).edit();
editor.putString(DataSource.NAME_PREFERENCES_NAME, name);
editor.putString(DataSource.EMAIL_PREFERENCES_NAME, email);
editor.putString(DataSource.PASSWORD_PREFERENCES_NAME, pass);
editor.commit();
}
private boolean isRegistered()
{
SharedPreferences prefs = getSharedPreferences(DataSource.PREFERENCES_NAME, 0);
String name = prefs.getString(DataSource.NAME_PREFERENCES_NAME, "");
String email = prefs.getString(DataSource.EMAIL_PREFERENCES_NAME, "");
String password = prefs.getString(DataSource.PASSWORD_PREFERENCES_NAME, "");
return (!name.isEmpty() && !email.isEmpty() && !password.isEmpty());
}
private boolean isNameValid(String name)
{
//TODO: Replace this with your own logic
return !TextUtils.isEmpty(name);
}
private boolean isEmailValid(String email)
{
//TODO: Replace this with your own logic
return email.contains("@");
}
private boolean isPasswordValid(String password)
{
//TODO: Replace this with your own logic
return password.length() > 2;
}
/**
* Shows the progress UI and hides the login form.
*/
public void showProgress(final boolean show)
{
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2)
{
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter()
{
@Override
public void onAnimationEnd(Animator animation)
{
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter()
{
@Override
public void onAnimationEnd(Animator animation)
{
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else
{
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle)
{
return new CursorLoader(this,
// Retrieve data rows for the device user's 'profile' contact.
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
// Select only email addresses.
ContactsContract.Contacts.Data.MIMETYPE + " = ?",
new String[]{ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE},
// Show primary email addresses first. Note that there won't be
// a primary email address if the user hasn't specified one.
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC"
);
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor)
{
if(cursor == null) return;
List<String> emails = new ArrayList<String>();
cursor.moveToFirst();
while (!cursor.isAfterLast())
{
emails.add(cursor.getString(ProfileQuery.ADDRESS));
cursor.moveToNext();
}
//addEmailsToAutoComplete(emails);
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader)
{
}
private interface ProfileQuery
{
String[] PROJECTION = {ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,};
int ADDRESS = 0;
int IS_PRIMARY = 1;
}
/*private void addEmailsToAutoComplete(List<String> emailAddressCollection)
{
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(LoginActivity.this, android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
mEmailView.setAdapter(adapter);
}*/
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
// public class UserLoginTask extends AsyncTask<Void, Void, Boolean>
// {
// private final Local local;
//
// UserLoginTask(Local local)
// {
// this.local = local;
// }
//
// @Override
// protected Boolean doInBackground(Void... params)
// {
// RestAdapter restAdapter = new RestAdapter.Builder()
// .setEndpoint("http://api.iknow.travel")
// .setRequestInterceptor(ApiHelper.requestInterceptor)
// .build();
//
//
// ApiHelper apiHelper = restAdapter.create(ApiHelper.class);
// //Response response = apiHelper.registration(local);
//
// return true;//response.getStatus() == HttpStatus.SC_OK;
// }
//
// @Override
// protected void onPostExecute(final Boolean success)
// {
// mAuthTask = null;
// showProgress(false);
//
// if (success)
// {
// //finish();
// }
// else
// {
// mPasswordView.setError(getString(R.string.error_incorrect_password));
// mPasswordView.requestFocus();
// }
// }
//
// @Override
// protected void onCancelled()
// {
// mAuthTask = null;
// showProgress(false);
// }
// }
}
| [
"[email protected]"
]
| |
4b1f1c5c8c9b9f386205f449b0fba3c17c82562c | df2bd60d667b4e5701d4f5137079981ed62378a3 | /src/inventorysystem/Sales.java | c5c813a2992e602bc51966238b6b7a6d81b7a29b | []
| no_license | mohamedatef78/InventorySystem-java | c112a06aa92a5f2133fb783f13ecaeaabea62491 | 242c1654a65064806b3deb9910bb9736265aa08a | refs/heads/main | 2023-05-26T03:22:20.616801 | 2021-06-07T17:53:55 | 2021-06-07T17:53:55 | 374,754,488 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,545 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package inventorysystem;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Mohamed atef
*/
public class Sales {
private int sales_ID;
private int product_ID;
private String product_Code ;
private int invoice_id;
private int quantity;
private float itemdiscount ;
private int total ;
private DatabaseConnection con = new DatabaseConnection();
public ArrayList<Product> productList = new ArrayList<Product>();
public void setquantity(int quantity){
this.quantity = quantity ;
}
public void setitemdiscount(int itemdiscount){
this.itemdiscount = itemdiscount ;
}
public int getproduct_ID() {
return product_ID;
}
public int getsales_ID() {
return sales_ID;
}
public int getinvoice_id() {
return invoice_id;
}
public int getquantity() {
return quantity;
}
public float getitemdiscount() {
return itemdiscount;
}
public int gettotal() {
return total;
}
public ArrayList<Product> fetchproduct(String productCode){
String query = "SELECT * FROM inventorymanagmentsystem.product where product_code= '"+productCode +"'";
ResultSet rs= null;
Product product = null;
try {
rs =(ResultSet) this.con.executeSQLQuery(query, "SELECT");
while(rs.next()){
product = new Product();
this.product_ID = rs.getInt("product_id");
this.product_Code =rs.getString("product_code");
product.setproductID(rs.getInt("product_id"));
product.setproductName(rs.getString("product_name"));
product.setproductCode(rs.getString("product_code"));
product.setprice(rs.getInt("product_price"));
product.setproductquantity(rs.getInt("product_quantity"));
product.setweight(rs.getInt("product_weight"));
product.setproductionDate(rs.getString("produtcion_date"));
this.productList.add(product);
}
} catch (SQLException ex) {
Logger.getLogger(Product.class.getName()).log(Level.SEVERE, null, ex);
return null ;
} catch (ParseException ex) {
Logger.getLogger(Product.class.getName()).log(Level.SEVERE, null, ex);
return null ;
}
return this.productList;
}
public boolean checkQuantityAvailability(){
return this.productList.get(0).getquantity() >= this.quantity;
}
public int calcu(){
if(this.itemdiscount!=0){
float itemdiscount = this.itemdiscount / 100 ;
int total = this.quantity *this.productList.get(0).getweight()*this.productList.get(0).getprice();
this.total =(int) (total- (total * itemdiscount));
} else {
this.total =this.quantity *this.productList.get(0).getweight()*this.productList.get(0).getprice();
}
this.productList.clear();
return this.total ;
}
}
| [
"[email protected]"
]
| |
dd9c587bf5c21ecd7cd50d838cf073e3320b0f44 | 784ac837434cfbb53173fe8e85792ca6842f3463 | /app/src/main/java/com/maulanakurnia/movieroom/data/AppDatabase.java | f23c16a55c2c4f0bbc14c75dcec58d8104422656 | []
| no_license | maulanakurnia/movie-room | 01c5508d70cad8116710f1295a60cf2ddb2c9dd8 | 72f93ea1def65df0660159c38b6e0cb171b1ad2a | refs/heads/master | 2023-06-12T04:49:51.018921 | 2021-06-29T08:45:17 | 2021-06-29T08:48:44 | 375,734,623 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,309 | java | package com.maulanakurnia.movieroom.data;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;
import com.maulanakurnia.movieroom.data.dao.FavoriteDao;
import com.maulanakurnia.movieroom.data.dao.UserDao;
import com.maulanakurnia.movieroom.data.model.Favorite;
import com.maulanakurnia.movieroom.data.model.User;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by Maulana Kurnia on 6/1/2021
* Keep Coding & Stay Awesome!
**/
@Database(entities = {User.class, Favorite.class}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
public abstract FavoriteDao favoriteDao();
public static final int NUMBER_OF_THREADS = 4;
private static volatile AppDatabase INSTANCE;
public static final ExecutorService databaseWriteExecutor = Executors.newFixedThreadPool(NUMBER_OF_THREADS);
public static AppDatabase getDatabase(final Context context) {
if(INSTANCE == null) {
synchronized (AppDatabase.class) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, "roommovie.db")
.fallbackToDestructiveMigration()
.addCallback(sRoomDatabaseCallback)
.build();
}
}
return INSTANCE;
}
private static final RoomDatabase.Callback sRoomDatabaseCallback = new RoomDatabase.Callback() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
databaseWriteExecutor.execute(() -> {
UserDao userDao = INSTANCE.userDao();
userDao.deleteAll();
User user = new User();
user.setFullname("Maulana Kurnia Fiqih Ainul Yaqin");
user.setNickname("Maulana Kurnia");
user.setUsername("maulanakurnia");
user.setPassword("1221");
user.setImage_path(null);
userDao.insert(user);
});
}
};
}
| [
"[email protected]"
]
| |
ed1d8c75603773ebcbe1bf3daea7fe4743e14840 | 9f945767e47c443e51830b0aedf3482f71dbbd39 | /RecyclerViewApp/app/src/main/java/com/example/recyclerviewapp/MainActivity.java | df90889a512c31e7178d175c270d86fe2e7efb96 | []
| no_license | Israel74/TP_UIT | 553b7959a0066f21d2f1a87293c1db8ef95f1bba | 1db525275509d9d466a74618e7ed49eb25319567 | refs/heads/master | 2020-04-30T19:23:18.421041 | 2019-04-05T00:13:37 | 2019-04-05T00:13:37 | 177,034,025 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 340 | java | package com.example.recyclerviewapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
| [
"[email protected]"
]
| |
9e8119dc7c56d2e83f7670c5398e5f46edaa6bae | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/12/12_a058ed0cd11e27d53515a2618c715eef0e2d88a0/ExtendedJavaObject/12_a058ed0cd11e27d53515a2618c715eef0e2d88a0_ExtendedJavaObject_t.java | f9df27e788a751e11124eac6efe7d766d9378a5a | []
| no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 7,154 | java | /*
* Scriptographer
*
* This file is part of Scriptographer, a Plugin for Adobe Illustrator.
*
* Copyright (c) 2002-2008 Juerg Lehni, http://www.scratchdisk.com.
* All rights reserved.
*
* Please visit http://scriptographer.com/ for updates and contact.
*
* -- GPL LICENSE NOTICE --
* 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 2
* 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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
* -- GPL LICENSE NOTICE --
*
* File created on 02.01.2005.
*
* $Id$
*/
package com.scratchdisk.script.rhino;
import java.util.HashMap;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.EcmaError;
import org.mozilla.javascript.EvaluatorException;
import org.mozilla.javascript.NativeJavaObject;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import com.scratchdisk.script.ChangeNotifier;
import com.scratchdisk.script.ChangeListener;
/**
* @author lehni
*/
public class ExtendedJavaObject extends NativeJavaObject {
HashMap<String, Object> properties;
ExtendedJavaClass classWrapper = null;
/**
* @param scope
* @param javaObject
* @param staticType
*/
public ExtendedJavaObject(Scriptable scope, Object javaObject,
Class staticType, boolean unsealed) {
super(scope, javaObject, staticType);
properties = unsealed ? new HashMap<String, Object>() : null;
classWrapper = ExtendedJavaClass.getClassWrapper(scope, staticType);
}
public Scriptable getPrototype() {
Scriptable prototype = super.getPrototype();
return prototype == null
? classWrapper.getInstancePrototype()
: prototype;
}
protected ExtendedJavaObject changeListener = null;
protected String changeName = null;
protected int currentChangeVersion = -1;
public static int changeVersion = -1;
public Object get(String name, Scriptable start) {
// Properties need to come first, as they might override something
// defined in the underlying Java object
if (properties != null && properties.containsKey(name)) {
// See whether this object defines the property.
return properties.get(name);
} else {
// If there is a modification listener, fetch the new value of this object
// from it before calling anything on it. We are doing this by replacing
// the underlying native object each time.
if (changeListener != null && currentChangeVersion != changeVersion) {
Object result = changeListener.get(changeName, this);
if (result != this && result instanceof ExtendedJavaObject) {
ExtendedJavaObject update = (ExtendedJavaObject) result;
javaObject = update.javaObject;
// Help the garbage collector
update.javaObject = null;
}
currentChangeVersion = changeVersion;
}
Scriptable prototype = getPrototype();
Object result = prototype.get(name, this);
if (result != Scriptable.NOT_FOUND)
return result;
result = members.get(this, name, javaObject, false);
if (result != Scriptable.NOT_FOUND) {
// Now see if the result is a modification dispatcher for this listener.
// If so, create the links between the two.
if (javaObject instanceof ChangeListener
&& result instanceof ExtendedJavaObject) {
ExtendedJavaObject other = (ExtendedJavaObject) result;
if (other.javaObject instanceof ChangeNotifier) {
other.changeListener = this;
other.changeName = name;
}
}
return result;
}
if (name.equals("prototype"))
return prototype;
return Scriptable.NOT_FOUND;
}
}
public void put(String name, Scriptable start, Object value) {
EvaluatorException error = null;
if (members.has(name, false)) {
try {
// Try setting the value on member first
members.put(this, name, javaObject, value, false);
// If there is a modification listener, update this field in it right away now.
if (changeListener != null)
changeListener.put(changeName, changeListener, this);
return; // done
} catch (EvaluatorException e) {
// Rethrow errors that have another cause (a real Java exception from the
// called getter / setter) or that are about conversion problems.
if (e.getCause() != null || e.getMessage().indexOf("Cannot convert") != -1)
throw e;
error = e;
}
}
// Still here? An exception has happened. Let's try other things
if (name.equals("prototype")) {
if (value instanceof Scriptable)
setPrototype((Scriptable) value);
} else if (properties != null) {
// Ignore EvaluatorException exceptions that might have happened in
// members.put above. These would happen if the user tries to
// override a Java method or field. We allow this on the level of
// the wrapper though, if the wrapper was created unsealed (meaning
// properties exist).
properties.put(name, value);
} else if (error != null) {
// If nothing of the above worked, throw the error again.
throw error;
}
}
public boolean has(String name, Scriptable start) {
return members.has(name, false) ||
properties != null && properties.containsKey(name);
}
public void delete(String name) {
if (properties != null)
properties.remove(name);
}
public Object[] getIds() {
// Concatenate the super classes ids array with the keySet from
// properties HashMap:
Object[] javaIds = super.getIds();
if (properties != null) {
int numProps = properties.size();
if (numProps == 0)
return javaIds;
Object[] ids = new Object[javaIds.length + numProps];
properties.keySet().toArray(ids);
System.arraycopy(javaIds, 0, ids, numProps, javaIds.length);
return ids;
} else {
return javaIds;
}
}
protected Object toObject(Object obj, Scriptable scope) {
// Use this instead of Context.toObject, since that one
// seems to handle Booleans wrongly (wrapping it in objects).
// TODO: Is this a Rhino bug? If so, fix it.
scope = ScriptableObject.getTopLevelScope(scope);
Context cx = Context.getCurrentContext();
return cx.getWrapFactory().wrap(cx, scope, obj, null);
}
public Object getDefaultValue(Class<?> hint) {
// Try the ScriptableObject version first that tries to call toString / valueOf,
// and fallback on the Java toString only if that does not work out.
try {
return ScriptableObject.getDefaultValue(this, hint);
} catch (EcmaError e) {
return super.getDefaultValue(hint);
}
}
}
| [
"[email protected]"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.