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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
31d0370e6c7b5e8efc4d18241003826fef479806 | 5e8cb54cbb7c6cf588aa63212550b14b27048df2 | /app/src/main/java/com/example/mylibrary/data/model/BookOfAuthor.java | 9d3214faf6368c89698477bec2455e6f979b2763 | [] | no_license | xuanphuoc129/my_library | 8e28433142b587cc0ad2ffe44aa7c53d24177c33 | 9540ebd508715c7f2149a57d6658caaa0efeaa12 | refs/heads/master | 2020-05-17T11:09:55.863961 | 2019-04-28T00:59:51 | 2019-04-28T00:59:51 | 183,678,713 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,083 | java | package com.example.mylibrary.data.model;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.Relation;
import java.util.List;
@Entity(tableName = "book_of_author")
public class BookOfAuthor {
@ColumnInfo(name = "AuthorID")
private String AuthorID; // mã tác giả
@ColumnInfo(name = "AuthorName")
private String AuthorName; // tên tác giả
@Relation(parentColumn = "AuthorID", entityColumn = "AuthorID", entity = Book.class)
private List<Book> books; // sách cùng tác giả
public BookOfAuthor() {
}
public String getAuthorID() {
return AuthorID;
}
public void setAuthorID(String authorID) {
AuthorID = authorID;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
public String getAuthorName() {
return AuthorName;
}
public void setAuthorName(String authorName) {
AuthorName = authorName;
}
}
| [
"admin@ADMINs-MacBook-Pro.local"
] | admin@ADMINs-MacBook-Pro.local |
4c29bd406bd34bc14505d8559ee78aac4c4dc995 | 56bdb7e73caf57591c52e7d30fc8d100e8f72f0a | /src/main/java/br/com/marmitaria/rest/login/TokenFilter.java | 0cf90bb65102eca99f5ab44b82ea8024738d2905 | [] | no_license | abelantunes98/fulano_de_sal | 13b0b55b7a9509e3582c8104202897199f570149 | 4eb5cde8e2a00749147d28aaf2d3e5f414eb8d89 | refs/heads/master | 2023-01-22T20:14:08.561244 | 2019-11-16T12:52:42 | 2019-11-16T12:52:42 | 315,416,778 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,294 | java | package br.com.marmitaria.rest.login;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.GenericFilter;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import br.com.marmitaria.rest.exception.TokenException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
@Component
public class TokenFilter extends GenericFilter {
/**
*
*/
private static final long serialVersionUID = -5607986703246617499L;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
String header = req.getHeader("Authorization");
if (header == null || !header.startsWith("Bearer ")) {
throw new TokenException("Token inexistente ou mal formatado!");
}
String token = header.substring(7);
try {
Jwts.parser().setSigningKey(TokenKey.TOKEN_KEY.getValue()).parseClaimsJws(token).getBody();
} catch (SignatureException e) {
throw new TokenException("Token invalido ou expirado!");
}
chain.doFilter(request, response);
}
}
| [
"samuel25101998@gmail.com"
] | samuel25101998@gmail.com |
35d1168425d8bd6efa2bcc8c8c11a5cf7cab7bb5 | 7f3d442ee252aac7b1425239857018beac68a3ca | /5/StringSort.java | 84cf81f6dce9dcdfba7ab8648cf439425860aa89 | [] | no_license | takasyou-main/pro_b | e08ed1385aced08e7709e301b3675a9daca2f382 | 99c62b42bab0e4c86e0050e6244c70fa4a6d0387 | refs/heads/master | 2021-01-10T19:55:40.033354 | 2014-12-22T13:41:12 | 2014-12-22T13:41:12 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,171 | java | import java.io.*;
public class StringSort {
final static int MAXLINE=1000;
static int test=0;
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
String line;
int linenum = 0;
String[] tmp_text= new String[MAXLINE];
while ((line = reader.readLine()) != null) {
tmp_text[linenum]=line;
linenum++;
}
String[] text = new String[linenum];
for(int i=0;i<linenum;i++)text[i]=tmp_text[i];
quickSort(text,0,text.length-1);
for(String data : text)System.out.println(data);
} catch (IOException e) {
System.out.println(e);
}
}
public static void quickSort(String[] a,int l,int r){
int pivotPos = l;
int pre_r=r;
int pre_l=l;
if(l!=r){
while(l<=r){
if(a[l].compareTo(a[pivotPos])<=0)l++;
else if(a[r].compareTo(a[pivotPos])>0)r--;
else swap(a,l,r);
}
swap(a,pivotPos,r);
quickSort(a,pivotPos,r);
quickSort(a,r+1,pre_r);
}
}
public static void swap(String[] a,int x,int y){
String tmp=a[x];
a[x]=a[y];
a[y]=tmp;
}
}
| [
"takasyou.kuri@gmail.com"
] | takasyou.kuri@gmail.com |
a1c5da75c68c605c2025135d9a1e57851a944d13 | 968df8bba0bf8798e27e51c02fc1723f051ff2b6 | /src/Lecteur/ModeleMultipleReponse.java | 76b50c975e6ef36f239ce127cebf68b84566b9e8 | [] | no_license | champymarty/ProjetCreateurQuestionnaire | c62c427adfea0ca96c53f3a1940d245949740179 | 85ece1eb63404559e2f562bd36e168e9fb59536f | refs/heads/master | 2022-11-26T10:56:29.929737 | 2020-07-15T23:51:46 | 2020-07-15T23:51:46 | 274,820,298 | 0 | 0 | null | null | null | null | ISO-8859-2 | Java | false | false | 2,727 | java | package Lecteur;
import java.io.Serializable;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import Editeur.Reponse;
public class ModeleMultipleReponse extends ModeleQuestion implements Serializable {
/**
*
*/
private static final long serialVersionUID = 5982108056365527000L;
private ArrayList<Reponse> choix = new ArrayList<>();
private ArrayList<Integer> indexSelectionnes = new ArrayList<>();
private ArrayList<Integer> indexReponses;
private boolean estImage;
public ModeleMultipleReponse(int ordrePassage, String question, String messageReussite, String messageFail,
int nbEssait, ArrayList<Reponse> choix,ArrayList<Integer> indexReponse, boolean estImage) {
super(ordrePassage, question, messageReussite, messageFail, nbEssait);
this.choix = choix;
this.indexReponses = indexReponse;
this.estImage = estImage;
}
public void updateSelectionne(ArrayList<Integer> selectionne) {
indexSelectionnes = selectionne;
}
public ArrayList<Integer> getIndexReponses() {
return indexReponses;
}
public boolean estImage() {
return estImage;
}
public int getNbChoix() {
return choix.size();
}
public void setChoix(ArrayList<Reponse> choix) {
this.choix = choix;
}
public void setEstImage(boolean estImage) {
this.estImage = estImage;
}
public void setIndexReponses(ArrayList<Integer> indexReponses) {
this.indexReponses = indexReponses;
}
public void setIndexSelectionnes(ArrayList<Integer> indexSelectionnes) {
this.indexSelectionnes = indexSelectionnes;
}
public ArrayList<Reponse> getChoix(){
return choix;
}
public String getChoix(int index) {
if( index < choix.size()) {
return choix.get(index).getAffichage();
}
return null;
}
@Override
public void afficherValidation() {
if(reponseValide()) {
JOptionPane.showMessageDialog(null, messageReussite, "Résultat réponse", JOptionPane.INFORMATION_MESSAGE);
}else {
JOptionPane.showMessageDialog(null, messageFail, "Résultat réponse", JOptionPane.INFORMATION_MESSAGE);
}
}
@Override
public boolean reponseValide() {
if(indexSelectionnes.size() != indexReponses.size()) {
return false;
}
for(int i = 0; i < indexSelectionnes.size(); i++) {
System.out.print(indexSelectionnes.get(i) + " =? " + indexReponses.get(i));
if(indexSelectionnes.get(i).intValue() != indexReponses.get(i).intValue() ) {
return false;
}
}
return true;
}
@Override
public String getQuestionType() {
return "Question avec plusieurs réponses";
}
@Override
public boolean isReponseImage() {
return estImage;
}
@Override
public JPanel generateAffichage() {
return new PaneauMultipleReponse(this);
}
}
| [
"raphaelstjean@yahoo.ca"
] | raphaelstjean@yahoo.ca |
36410ad5240a47512d437e79fb81351f1daacebe | e4344654e23d9d2d13588f951432a0e0747ecdf2 | /networks/prog5/chatclient.java | 0384bf595e66a6e4c2d9fb967126aa869a3de971 | [] | no_license | JKtheSlacker/classwork | 802130d7279498725bad62e6e252c5a229b7d49a | a8a1cc5c22174d442298e84def4db8adfae3c7cf | refs/heads/master | 2021-01-01T20:10:41.848966 | 2011-06-10T16:05:14 | 2011-06-10T16:05:14 | 1,400,135 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,285 | java | /* chatclient.java
* Written by Joshua K. Wood
* May 2011 */
import java.io.*;
import java.net.*;
class chatclient {
static Socket clientSocket;
static String userName;
static DataOutputStream outToServer;
static BufferedReader inFromUser;
public static void main (String argv[]) throws Exception
{
// Set up the connection
clientSocket = new Socket ("localhost", 42134);
System.out.println("To exit chat at any time, type EOF and press enter.");
outToServer = new DataOutputStream(clientSocket.getOutputStream());
inFromUser = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter a username to continue:");
userName = inFromUser.readLine();
outToServer.writeBytes(userName + "\n");
keyboardListener keyboard = new keyboardListener(clientSocket, outToServer, inFromUser);
serverListener server = new serverListener(clientSocket);
keyboard.start();
server.start();
keyboard.join();
server.join();
}
}
// Not exactly Ray Charles
class keyboardListener extends Thread {
String userInput;
BufferedReader inFromUser;
DataOutputStream outToServer;
Socket clientSocket;
boolean stillChatting = true;
public keyboardListener (Socket clientSocket, DataOutputStream outToServer, BufferedReader inFromUser){
this.clientSocket = clientSocket;
this.outToServer = outToServer;
this.inFromUser = inFromUser;
}
public synchronized void run() {
try {
while (stillChatting) {
userInput = inFromUser.readLine();
if (userInput.endsWith("EOF")) {
stillChatting = false;
}
outToServer.writeBytes(userInput + "\n");
}
clientSocket.close();
} catch (Exception e) {
}
}
}
// Not the server whisperer, lest ye be confused.
class serverListener extends Thread {
String serverResponse;
BufferedReader inFromServer;
boolean stillChatting = true;
Socket clientSocket;
public serverListener (Socket clientSocket){
this.clientSocket = clientSocket;
}
// Handles reading from the server
public synchronized void run() {
try {
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while (stillChatting){
serverResponse = inFromServer.readLine();
System.out.println(serverResponse);
}
} catch (Exception e){
}
}
}
| [
"joshuakwood@gmail.com"
] | joshuakwood@gmail.com |
f83da7d18fd7397a6b180a08d9c8c9a9645e96aa | 53b8e2d532469f00805a75ecc4265510c4701948 | /Everis Quality Assurance QA Bootcamp/Codigos de Automacao/bootcamp-bdd-everis-dio-main/src/test/java/com/everis/steps/ResultadoPesquisaSteps.java | 5fd329a3cb239e2ebea1543c11eddd9482b26003 | [] | no_license | Alexandre-Paulo-Silva/Cursos-Digital-Innvation-One | 0f7d9d69219bac6e5f2c8fce18393bba15f7e25c | cd4d1d2b145522820a19f15b8e5338761c15bf7c | refs/heads/main | 2023-08-25T10:17:48.478836 | 2021-10-24T21:13:54 | 2021-10-24T21:13:54 | 419,943,084 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 667 | java |
package com.everis.steps;
import com.everis.pages.ResultadoPesquisaPage;
import io.cucumber.java.pt.E;
import io.cucumber.java.pt.Quando;
public class ResultadoPesquisaSteps {
@Quando("^adiciona o produto \"(.*)\" ao carrinho$")
public void adicionarProdutoAoCarrinho(String nomeProduto) {
ResultadoPesquisaPage resultadoPesquisaPage = new ResultadoPesquisaPage();
resultadoPesquisaPage.adicionarProdutoAoCarrinho(nomeProduto);
}
@E("^acessa o produto \"(.*)\"$")
public void acessarProduto(String nomeProduto) {
ResultadoPesquisaPage resultadoPesquisaPage = new ResultadoPesquisaPage();
resultadoPesquisaPage.acessarProduto(nomeProduto);
}
} | [
"alexandre.paulo.silva@hotmail.com"
] | alexandre.paulo.silva@hotmail.com |
abe6eacb872e1219d7324ac5ff61d756ae6c4971 | 6cbb0f31e9db4d039d01db8ba958b048a9daaea0 | /src/main/java/be/hubau/sane/parser/Rule_literal_char.java | 6b93e10e3f61ffa685135364e0885867f6443900 | [] | no_license | Turbots/sane-java | fe620ce89a0aedda69a112eb023447d35439a7ef | 7096f3ec4a0325cb4deea68422bcb10d3ce1daf3 | refs/heads/master | 2020-05-10T00:03:18.848210 | 2019-04-25T21:16:01 | 2019-04-25T21:16:01 | 181,519,595 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,508 | java | package be.hubau.sane.parser;/* -----------------------------------------------------------------------------
* Rule_literal_char.java
* -----------------------------------------------------------------------------
*
* Producer : com.parse2.aparse.Parser 2.5
* Produced : Mon Apr 15 15:26:09 CEST 2019
*
* -----------------------------------------------------------------------------
*/
import java.util.ArrayList;
final public class Rule_literal_char extends Rule {
public Rule_literal_char(String spelling, ArrayList<Rule> rules) {
super(spelling, rules);
}
public static Rule_literal_char parse(ParserContext context) {
context.push("literal-char");
boolean parsed = true;
int s0 = context.index;
ParserAlternative a0 = new ParserAlternative(s0);
ArrayList<ParserAlternative> as1 = new ArrayList<ParserAlternative>();
parsed = false;
{
int s1 = context.index;
ParserAlternative a1 = new ParserAlternative(s1);
parsed = true;
if (parsed) {
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++) {
Rule rule = Terminal_NumericValue.parse(context, "%x09", "[\\x09]", 1);
if ((f1 = rule != null)) {
a1.add(rule, context.index);
c1++;
}
}
parsed = c1 == 1;
}
if (parsed) {
as1.add(a1);
}
context.index = s1;
}
{
int s1 = context.index;
ParserAlternative a1 = new ParserAlternative(s1);
parsed = true;
if (parsed) {
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++) {
Rule rule = Terminal_NumericValue.parse(context, "%x20-26", "[\\x20-\\x26]", 1);
if ((f1 = rule != null)) {
a1.add(rule, context.index);
c1++;
}
}
parsed = c1 == 1;
}
if (parsed) {
as1.add(a1);
}
context.index = s1;
}
{
int s1 = context.index;
ParserAlternative a1 = new ParserAlternative(s1);
parsed = true;
if (parsed) {
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++) {
Rule rule = Terminal_NumericValue.parse(context, "%x28-7E", "[\\x28-\\x7E]", 1);
if ((f1 = rule != null)) {
a1.add(rule, context.index);
c1++;
}
}
parsed = c1 == 1;
}
if (parsed) {
as1.add(a1);
}
context.index = s1;
}
{
int s1 = context.index;
ParserAlternative a1 = new ParserAlternative(s1);
parsed = true;
if (parsed) {
boolean f1 = true;
int c1 = 0;
for (int i1 = 0; i1 < 1 && f1; i1++) {
Rule rule = Terminal_NumericValue.parse(context, "%x80-10FFFF", "[\\x80-\\u10FFFF]", 1);
if ((f1 = rule != null)) {
a1.add(rule, context.index);
c1++;
}
}
parsed = c1 == 1;
}
if (parsed) {
as1.add(a1);
}
context.index = s1;
}
ParserAlternative b = ParserAlternative.getBest(as1);
parsed = b != null;
if (parsed) {
a0.add(b.rules, b.end);
context.index = b.end;
}
Rule rule = null;
if (parsed) {
rule = new Rule_literal_char(context.text.substring(a0.start, a0.end), a0.rules);
} else {
context.index = s0;
}
context.pop("literal-char", parsed);
return (Rule_literal_char) rule;
}
public Object accept(Visitor visitor) {
return visitor.visit(this);
}
}
/* -----------------------------------------------------------------------------
* eof
* -----------------------------------------------------------------------------
*/
| [
"dhubau@gmail.com"
] | dhubau@gmail.com |
5a820841f6f025b4d898ca72c1c4fb8ba73db9c5 | 71f9711d53d1ab39fa101083057a0b7bcdfdca21 | /Projects/Client/src/com/feedbactory/client/ui/browser/feedback/personal/YouPicHandler.java | c9acc941cd458f2a5a06ba0f8903054f5ffb94d7 | [
"MIT"
] | permissive | Russell-W/Feedbactory | fcb0fd6b6e84ac2d10f7dbc69a7af5d25346c32e | b4bb056f5b6b9e7b1826626551f49837df6f7ebe | refs/heads/master | 2021-01-13T04:44:38.329973 | 2017-01-15T04:37:38 | 2017-01-15T04:37:38 | 78,909,306 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,655 | java |
package com.feedbactory.client.ui.browser.feedback.personal;
import com.feedbactory.client.core.feedback.personal.PersonalFeedbackUtilities;
import com.feedbactory.client.ui.UIUtilities;
import com.feedbactory.client.ui.browser.BrowserService;
import com.feedbactory.client.ui.browser.feedback.personal.js.YouPicJavaScriptString;
import com.feedbactory.shared.feedback.personal.PersonalFeedbackConstants;
import com.feedbactory.shared.feedback.personal.PersonalFeedbackCriteriaType;
import com.feedbactory.shared.feedback.personal.PersonalFeedbackPerson;
import com.feedbactory.shared.feedback.personal.PersonalFeedbackPersonProfile;
import com.feedbactory.shared.feedback.personal.PersonalFeedbackWebsite;
import com.feedbactory.shared.feedback.personal.service.YouPic;
import java.util.Set;
final class YouPicHandler extends PersonalFeedbackWebsiteBrowserHandler
{
final private PersonalFeedbackBrowserEventManager browserEventManager;
YouPicHandler(final PersonalFeedbackBrowserEventManager browserEventManager)
{
this.browserEventManager = browserEventManager;
}
/****************************************************************************
*
***************************************************************************/
private PersonalFeedbackBrowsedPageResult handleBrowserPageLocationChanged(final BrowserService browserService)
{
final Object[] rawBrowsedData = (Object[]) browserService.evaluateJavascript(YouPicJavaScriptString.getLiveExecutor());
if (((Boolean) rawBrowsedData[0]).booleanValue())
{
if (rawBrowsedData[1] != null)
return getBrowsedPhotoProfile((Object[]) rawBrowsedData[1]);
else
return PersonalFeedbackBrowsedPageResult.NoPersonProfile;
}
else
return PersonalFeedbackBrowsedPageResult.BrowserPageNotReady;
}
private PersonalFeedbackBrowsedPageResult getBrowsedPhotoProfile(final Object[] browsedPhotoData)
{
final String photoID = (String) browsedPhotoData[0];
final String photoUserID = (String) browsedPhotoData[1];
final String photoDisplayName = getCompoundDisplayName((Object[]) browsedPhotoData[2]);
final String photoThumbnailURLID = (String) browsedPhotoData[3];
final Set<String> photoTags = PersonalFeedbackUtilities.getProcessedTags((Object[]) browsedPhotoData[4]);
if ((photoID.length() <= PersonalFeedbackConstants.MaximumPersonIDLength) &&
(photoUserID.length() <= PersonalFeedbackConstants.MaximumPersonProfileUserIDLength) &&
(photoDisplayName.length() <= PersonalFeedbackConstants.MaximumPersonProfileDisplayNameLength) &&
(photoThumbnailURLID.length() <= PersonalFeedbackConstants.MaximumPersonProfilePhotoURLLength))
{
final PersonalFeedbackPerson browsedPhoto = new PersonalFeedbackPerson(YouPic.instance, photoID, PersonalFeedbackCriteriaType.Photography);
return new PersonalFeedbackBrowsedPageResult(new PersonalFeedbackPersonProfile(browsedPhoto, photoUserID, photoDisplayName, photoThumbnailURLID, null, photoTags));
}
return PersonalFeedbackBrowsedPageResult.NoPersonProfile;
}
/****************************************************************************
*
***************************************************************************/
@Override
final PersonalFeedbackWebsite getServiceIdentifier()
{
return YouPic.instance;
}
@Override
final PersonalFeedbackBrowsedPageResult browserPageLocationChanged(final BrowserService browserService)
{
return handleBrowserPageLocationChanged(browserService);
}
} | [
"Russell-W@users.noreply.github.com"
] | Russell-W@users.noreply.github.com |
d5daf29c28d11b9692bcd308bd98b96ddae50df8 | 2a49f7ba7ca4eab577e9686af84ffadcd1a671be | /code/src/RandomNum.java | 74dd6a13b2d9dd1b6fad34fb55ec3515f9da0425 | [] | no_license | whram/java-basic | a93d6fa115df592b0d1d2d8c41153a1b1aa788d7 | bb039e1e56da28e23d910625e95e66ba8a108e23 | refs/heads/master | 2022-11-14T18:46:30.344755 | 2020-07-09T02:16:23 | 2020-07-09T02:16:23 | 266,078,970 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 491 | java | import java.util.Scanner;
import java.util.TreeSet;
public class RandomNum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()){
TreeSet<Integer> ts = new TreeSet();
int count = sc.nextInt();
for (int i = 0; i < count; i++) {
ts.add(sc.nextInt());
}
for (Integer t : ts) {
System.out.println(t);
}
}
}
}
| [
"793663370@qq.com"
] | 793663370@qq.com |
7e358ff0009fdd2fb7503a9e186fe599b3ca4910 | 4fed9530c70398d1989cf669587800b68ae7eb17 | /SpringTool/APIPeriferia/src/main/java/com/api/rest/contollers/StudentUpdateController.java | cf40a81056ded38f9d756889b8160b22b4a5c645 | [] | no_license | johansparra/PeriferiaPropuestaAPI | a3c1854c20e1970520dc2dc3c97edafdbf472151 | fede46f0f82de1ac4049a02172c4c20007bbf047 | refs/heads/master | 2022-04-13T13:16:30.142192 | 2020-03-28T20:09:34 | 2020-03-28T20:09:34 | 248,304,898 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 748 | java | package com.api.rest.contollers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.api.rest.beans.Student;
import com.api.rest.beans.StudentRegistration;
@Controller
public class StudentUpdateController {
@RequestMapping(method = RequestMethod.PUT, value="/update/student")
@ResponseBody
public String updateStudentRecord(@RequestBody Student stdn) {
System.out.println("In updateStudentRecord");
return StudentRegistration.getInstance().upDateStudent(stdn);
}
}
| [
"ing.sebasparra@gmail.com"
] | ing.sebasparra@gmail.com |
100d0ac2fd26cccafc462f927de79084f44916f9 | 87a777f848c15de02db1c8808f5caae599165413 | /app/src/main/java/me/jouin/lionel/tarkigates/MainActivity.java | ded77482112d682168abaa7e413746e0f009f1bf | [
"MIT"
] | permissive | LionelJouin/TarkiGates | e63fc261577841b9ea821483b2acf62dd15c9262 | dd5c44cecb852436508f0fe67be89a5ac5194710 | refs/heads/master | 2021-01-12T12:22:54.658327 | 2018-09-17T17:18:17 | 2018-09-17T17:18:17 | 72,476,212 | 5 | 2 | null | null | null | null | UTF-8 | Java | false | false | 5,091 | java | package me.jouin.lionel.tarkigates;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import java.util.HashMap;
import java.util.Map;
import me.jouin.lionel.tarkigates.levels.LevelList;
import me.jouin.lionel.tarkigates.pages.Game;
import me.jouin.lionel.tarkigates.pages.Home;
import me.jouin.lionel.tarkigates.pages.Informations;
import me.jouin.lionel.tarkigates.pages.Page;
import me.jouin.lionel.tarkigates.pages.PageListener;
import me.jouin.lionel.tarkigates.pages.PageName;
import me.jouin.lionel.tarkigates.pages.Settings;
public class MainActivity extends AppCompatActivity {
private FragmentTransaction tx;
private Home home;
private Game game;
private Settings settings;
private Informations informations;
private Map<PageName, Page> pages;
private PageName pageActuel;
private PageName previousPage;
private boolean doubleBackToExitPressedOnce = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
home = new Home();
game = new Game();
settings = new Settings();
informations = new Informations();
pages = new HashMap<>();
pages.put(PageName.HOME, home);
pages.put(PageName.GAME, game);
pages.put(PageName.SETTINGS, settings);
pages.put(PageName.INFORMATIONS, informations);
for(Map.Entry<PageName, Page> p : pages.entrySet()) {
p.getValue().addPageListeners(new PageListener() {
@Override
public void pageChange(PageName pageName) {
changePage(pageName);
}
@Override
public void selectLevel(LevelList levelList) {
game.setLevel(levelList);
}
});
}
pageActuel = PageName.HOME;
changePage(pageActuel);
Resources.getInstance(this);
Resources.getInstance().playBackgroundMusic(true);
super.onStart();
SharedPreferences sharedPref = getSharedPreferences(getString(R.string.pref_settings), Context.MODE_PRIVATE);
boolean prefSoundEffects = sharedPref.getBoolean(getString(R.string.pref_soundEffects), true);
int prefOrientation = sharedPref.getInt(getString(R.string.pref_orientation), ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Resources.getInstance().soundEffect = prefSoundEffects;
if (prefOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
else
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
@Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPref = getSharedPreferences(getString(R.string.pref_settings), Context.MODE_PRIVATE);
boolean prefMusic = sharedPref.getBoolean(getString(R.string.pref_music), true);
Resources.getInstance().playBackgroundMusic(prefMusic);
Resources.getInstance().setVolume();
}
@Override
protected void onPause() {
super.onPause();
Resources.getInstance().playBackgroundMusic(false);
}
public void changePage(PageName pageName) {
if (pages.containsKey(pageName)) {
if (pageActuel != PageName.SETTINGS) {
previousPage = pageActuel;
pageActuel = pageName;
tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.fragment, pages.get(pageName));
tx.commit();
} else {
pageActuel = previousPage;
previousPage = PageName.SETTINGS;
tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.fragment, pages.get(pageActuel));
tx.commit();
}
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
Positions.getInstance(this);
}
@Override
public void onBackPressed() {
if (pageActuel == PageName.HOME) {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, getString(R.string.doubleBackToExit), Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
} else {
changePage(PageName.HOME);
}
}
}
| [
"lionel.jouin@outlook.com"
] | lionel.jouin@outlook.com |
63f81c32cc24e608e93c6f47e9e9d4e44d283a79 | de61aaf5ee99ba4ea05b5bf6e461d037cb313813 | /src/blackjack/Card.java | 250ac25e6e73d2eb774f35d59f831a33613be084 | [] | no_license | Yvanne/Blackjack-Game | a2c739386e79fc04c30c0ca97f72a714701e4067 | 7a4f0d9bd046364054a5590d7da604d6b26bbbea | refs/heads/master | 2022-11-25T05:52:35.580416 | 2020-08-07T01:54:55 | 2020-08-07T01:54:55 | 285,709,817 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,023 | java | package blackjack;
/**
* Card - A Card object representing one playing card from the standard deck
* Copyright (C) 2005 University of Maryland
*/
public class Card {
private CardValue value;
private CardSuit suit;
private boolean faceUp;
public Card(CardValue value, CardSuit suit) {
this.value = value;
this.suit = suit;
this.faceUp = true; // By default cards are face up
}
public CardValue getValue() {
return value;
}
public CardSuit getSuit() {
return suit;
}
public boolean isFacedUp() {
return faceUp;
}
public void setFaceUp() {
faceUp = true;
}
public void setFaceDown() {
faceUp = false;
}
public boolean equals(Object o){
if (value == ((Card)o).value && suit == ((Card)o).suit)
return true;
return false;
}
public int hashCode() {
return value.getIntValue() * 4 + suit.ordinal();
}
public String toString() {
String result = "";
result += value + " of " + suit + " ";
result += (faceUp ? "(FaceUp)": "(FaceDown)");
return result;
}
} | [
"yseuhou@umd.edu"
] | yseuhou@umd.edu |
8833c2560b8cabbc05b5a3d4e900db3b53f1584d | 8f53022b806447bba69ad9526a248336aa648c80 | /app/src/main/java/com/welson/reader/presenter/BookReviewPresenter.java | 7958a1b31df1cd60b1bf4ba765ed6308fa27388e | [] | no_license | dddjjq/Reader | 76538612d4f09489a181f163bbed73ce4d4bbf9f | 6678833329d2878fb628c3d3c49d61b024367cba | refs/heads/master | 2020-04-07T02:08:52.002855 | 2019-02-02T09:14:54 | 2019-02-02T09:14:54 | 157,965,479 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,878 | java | package com.welson.reader.presenter;
import com.welson.reader.base.BaseView;
import com.welson.reader.contract.BookReviewContract;
import com.welson.reader.entity.BookReviewList;
import com.welson.reader.retrofit.RetrofitHelper;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
public class BookReviewPresenter extends AbstractPresenter implements BookReviewContract.Presenter {
private BookReviewContract.View view;
@Override
public void requestData(String duration, String sort, String type, int start, int limit, String distillate) {
if (view == null) return;
RetrofitHelper.getInstance().getBookReviewList(duration, sort, type, start, limit, distillate)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<BookReviewList>() {
@Override
public void onSubscribe(Disposable d) {
addDisposable(d);
}
@Override
public void onNext(BookReviewList bookReviewList) {
view.showSucceed(bookReviewList);
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
view.showError();
}
@Override
public void onComplete() {
}
});
}
@Override
public void attachView(BaseView baseView) {
view = (BookReviewContract.View) baseView;
}
@Override
public void detachView() {
if (view != null) {
view = null;
}
}
}
| [
"dingyunlong1996@hotmail.com"
] | dingyunlong1996@hotmail.com |
afd6ccf5271b8db3a2b2f7004cf232bb2f4f4a2b | 875eb715b63c764eaa95b5715eeeabf342255fa0 | /LASTVERSION/src/os/OS.java | 8915f7ee37c805977fc6b6bc3040a67cbc4c2c18 | [] | no_license | mohamedriad/comebassilandrostom | d7d33323f0279cbb52508c3983752382efffec1d | 703837d540134170bf927d953e23f79c07434df4 | refs/heads/master | 2020-04-08T21:08:53.821054 | 2018-12-13T01:50:41 | 2018-12-13T01:50:41 | 159,731,251 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,292 | java | package os;
import java.util.Random;
public class OS {
public static void main(String[] args) {
int q=1;
Banker b = new Banker();
b.input();
int[] Request=new int[b.DataTypes];
Random rand=new Random();
b.getNeed();
int[] order=new int[b.NoOfProcesses];
boolean[] isFinished=new boolean[b.NoOfProcesses];
int Count=0;// for ordering
int n=0;// counting requests
do
{
// fill requests
for(int i=0;i<b.DataTypes;i++)
{
Request[i]=rand.nextInt(q+5);
}
//====================
System.out.println("Request:"+n);
n++;
int Pwr=rand.nextInt(b.NoOfProcesses);
b.banker(Pwr,Request);
System.out.println("===============");
for(int t=0;t<b.NoOfProcesses;t++)
{
if(b.NeedEqualsZero(t) && !isFinished[t])
{
isFinished[t]=true;
order[Count] =t;
Count++;
}
}
} while(b.NeedNotEqualZero());
// OrderOfProcesses
System.out.println("The Order of Processes");
for(int h=0;h<b.NoOfProcesses;h++)
System.out.println("P"+order[h]);
//================================
}
}
| [
"noreply@github.com"
] | noreply@github.com |
25cda1f701be235bd2d399eae93e205e1178d273 | ee8f4bd0b5db983f3eecccd07d565e6a8c135e6b | /tsfile/src/main/java/org/apache/iotdb/tsfile/v2/read/reader/page/PageReaderV2.java | 639c829a4c918d4d422e0642866685d9d43ba6c3 | [
"Apache-2.0",
"BSD-3-Clause",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"EPL-1.0",
"CDDL-1.1"
] | permissive | phoenix-elite1050/iotdb | 3c38ef9eea73f3f973743adf167ad37d21831749 | 98984d51080e00d641c4bc2e244a7a161eafb0aa | refs/heads/master | 2023-03-15T18:59:35.541610 | 2021-03-05T07:26:25 | 2021-03-05T07:26:25 | 339,314,311 | 0 | 1 | Apache-2.0 | 2021-03-05T16:58:51 | 2021-02-16T07:13:03 | Java | UTF-8 | Java | false | false | 3,451 | 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 org.apache.iotdb.tsfile.v2.read.reader.page;
import java.io.IOException;
import java.nio.ByteBuffer;
import org.apache.iotdb.tsfile.encoding.decoder.Decoder;
import org.apache.iotdb.tsfile.encoding.decoder.PlainDecoder;
import org.apache.iotdb.tsfile.exception.write.UnSupportedDataTypeException;
import org.apache.iotdb.tsfile.file.header.PageHeader;
import org.apache.iotdb.tsfile.file.metadata.enums.TSDataType;
import org.apache.iotdb.tsfile.read.common.BatchData;
import org.apache.iotdb.tsfile.read.common.BatchDataFactory;
import org.apache.iotdb.tsfile.read.filter.basic.Filter;
import org.apache.iotdb.tsfile.read.reader.page.PageReader;
import org.apache.iotdb.tsfile.utils.Binary;
public class PageReaderV2 extends PageReader {
public PageReaderV2(ByteBuffer pageData, TSDataType dataType, Decoder valueDecoder,
Decoder timeDecoder, Filter filter) {
this(null, pageData, dataType, valueDecoder, timeDecoder, filter);
}
public PageReaderV2(PageHeader pageHeader, ByteBuffer pageData, TSDataType dataType,
Decoder valueDecoder, Decoder timeDecoder, Filter filter) {
super(pageHeader, pageData, dataType, valueDecoder, timeDecoder, filter);
}
/**
* @return the returned BatchData may be empty, but never be null
*/
@SuppressWarnings("squid:S3776") // Suppress high Cognitive Complexity warning
@Override
public BatchData getAllSatisfiedPageData(boolean ascending) throws IOException {
if (dataType != TSDataType.INT32 && dataType != TSDataType.TEXT) {
return super.getAllSatisfiedPageData(ascending);
}
BatchData pageData = BatchDataFactory.createBatchData(dataType, ascending, false);
while (timeDecoder.hasNext(timeBuffer)) {
long timestamp = timeDecoder.readLong(timeBuffer);
switch (dataType) {
case INT32:
int anInt = (valueDecoder instanceof PlainDecoder) ?
valueBuffer.getInt() : valueDecoder.readInt(valueBuffer);
if (!isDeleted(timestamp) && (filter == null || filter.satisfy(timestamp, anInt))) {
pageData.putInt(timestamp, anInt);
}
break;
case TEXT:
int length = valueBuffer.getInt();
byte[] buf = new byte[length];
valueBuffer.get(buf, 0, buf.length);
Binary aBinary = new Binary(buf);
if (!isDeleted(timestamp) && (filter == null || filter.satisfy(timestamp, aBinary))) {
pageData.putBinary(timestamp, aBinary);
}
break;
default:
throw new UnSupportedDataTypeException(String.valueOf(dataType));
}
}
return pageData.flip();
}
}
| [
"noreply@github.com"
] | noreply@github.com |
505e06d345c69405ca1726f435d05cdaa2fee660 | d04d85982fbe9e89a1db222403aaec042c83b8b3 | /Web_Admin/src/main/java/com/osp/model/Customer.java | 925c6edc65f9b91f4885efb5f3a478cbbc98b8db | [] | no_license | quanglinh53/Admin-Web | 5daf4c11b4009a4c5e682afbe8700deed4157f4c | 8a28f3af38f611e6bbbd9bfdebc9b78cbd27df77 | refs/heads/master | 2023-06-30T10:34:16.714559 | 2021-07-24T02:40:00 | 2021-07-24T02:40:00 | 388,482,649 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,123 | java | package com.osp.model;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.naming.Name;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.List;
/**
* Created by Admin on 12/14/2017.
*/
@Entity
@Data
@Table(name = "tqc_customer")
public class Customer implements Serializable {
private static final long serialVersionUID = -3552661732973732446L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID", unique = true, nullable = false)
private Integer id;
@Column(name = "USER_NAME", nullable = false, unique = true)
private String username;
@Column(name = "FULL_NAME", nullable = false, unique = true)
private String fullName;
@Column(name = "SEX", nullable = false, unique = true)
private Integer sex;
@Column(name = "BIRTHDAY", nullable = false, unique = true)
private Date birthday;
@Column(name = "PASSWORD", nullable = false, length = 100)
private String password;
@Column(name = "EMAIL", length = 100)
private String email;
@Column(name = "GEN_DATE")
private Date gendate;
@Column(name = "LAST_UPDATE")
private Date lastUpdate;
@Column(name = "STATUS", length = 100)
private Long status;
@Column(name = "SCAN")
private Long scan;
@Column(name = "RESET_DATE")
private Date resetDate;
@Column(name="CODE_RESET")
private String code;
@Column(name="IMAGE")
private String image;
@Column(name="FILE_NAME")
private String fileName;
@Column(name="LINK_FILE")
private String linkFile;
public static long getSerialVersionUID() {
return serialVersionUID;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getGendate() {
return gendate;
}
public void setGendate(Date gendate) {
this.gendate = gendate;
}
public Date getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
public Long getStatus() {
return status;
}
public void setStatus(Long status) {
this.status = status;
}
public Long getScan() {
return scan;
}
public void setScan(Long scan) {
this.scan = scan;
}
public Date getResetDate() {
return resetDate;
}
public void setResetDate(Date resetDate) {
this.resetDate = resetDate;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getLinkFile() {
return linkFile;
}
public void setLinkFile(String linkFile) {
this.linkFile = linkFile;
}
}
| [
"thiennv4895outsource@gmail.com"
] | thiennv4895outsource@gmail.com |
a9a34353b96fb0197aa76fae2afe147356714491 | 7b0967b1edabea42fd63824b59d13481abff59d8 | /Desktop/Sprint 3/proiect/src/main/java/com/amihaeseisergiu/proiect/Bathroom.java | cbb807c824fa4547cbe4c21bc5cb7b8f9030bf76 | [
"MIT"
] | permissive | octavianiacob/VA-AR-FII | 70e72a44fa2eb5a5013af74f1203b6aa00fe353f | cc4600d99ab97d27f25575f4e3e5be747a821b3f | refs/heads/master | 2022-07-03T04:29:53.498369 | 2020-05-18T10:54:50 | 2020-05-18T10:54:50 | 266,740,643 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 421 | 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 com.amihaeseisergiu.proiect;
import java.io.Serializable;
/**
*
* @author Alex
*/
public class Bathroom extends ExtendedRectangle implements Serializable {
public Bathroom(Point p) {
super(p);
}
}
| [
"61450080+Amihaeseisergiu@users.noreply.github.com"
] | 61450080+Amihaeseisergiu@users.noreply.github.com |
dfe5043a5f398a249510b2b6829fb5de284732ba | f115ded1eca19c44d23d9c7a407c44e360602da4 | /JavaExamples/src/main/java/com/mblinn/mbfpp/oo/fi/PersonNaturalSort.java | 869e6c0e2ba7b76b12d449b6cddcd8f6ecff796f | [] | no_license | slideclick/Functional-Programming-Patterns-in-Scala-and-Clojure | 435147ab25766db264145504e2519318f4427253 | 0aeb52e307e51122546e2c5146f72aef6014a9f2 | refs/heads/master | 2020-12-24T13:36:20.154575 | 2015-08-27T07:55:28 | 2015-08-27T07:55:28 | 41,473,057 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 949 | java | /***
* Excerpted from "Functional Programming Patterns",
* published by The Pragmatic Bookshelf.
* Copyrights apply to this code. It may not be used to create training material,
* courses, books, articles, and the like. Contact us if you are in doubt.
* We make no guarantees that this code is fit for any purpose.
* Visit http://www.pragmaticprogrammer.com/titles/mbfpp for more book information.
***/
package com.mblinn.mbfpp.oo.fi;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class PersonNaturalSort {
public static void main(String[] args) {
Person p1 = new Person("Mike", "Bevilacqua");
Person p2 = new Person("Pedro", "Vasquez");
Person p3 = new Person("Robert", "Aarons");
List<Person> people = new ArrayList<Person>();
people.add(p1);
people.add(p2);
people.add(p3);
Collections.sort(people);
for (Person person : people) {
System.out.println(person);
}
}
}
| [
"lius@CPEKW-Q1100534.is.ad.igt.com"
] | lius@CPEKW-Q1100534.is.ad.igt.com |
74e4693090fe4afe4cd7337cc18b10edbf812f54 | 1f1824e4126cda026ac0eb8429a57779c1da6484 | /app/src/main/java/com/example/aws/blogapp/Models/Comment.java | bb53ecf438cfcd5d98f947efc5646586e02dbb8d | [] | no_license | osam2019/APP_REALTIMEVACATION_Team | 45f6abb34cc23513fddaefb85b3dc29e47abfdda | 3dbafd66874ed0709fa7bd623cc5d9b376da3610 | refs/heads/master | 2020-08-27T07:05:07.081438 | 2019-10-24T18:29:14 | 2019-10-24T18:29:14 | 217,278,583 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,195 | java | package com.example.aws.blogapp.Models;
import com.google.firebase.database.ServerValue;
public class Comment {
private String content,uid,uname;
private Object timestamp;
public Comment() {
}
public Comment(String content, String uid, String uname) {
this.content = content;
this.uid = uid;
this.uname = uname;
this.timestamp = ServerValue.TIMESTAMP;
}
public Comment(String content, String uid, String uname, Object timestamp) {
this.content = content;
this.uid = uid;
this.uname = uname;
this.timestamp = timestamp;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public Object getTimestamp() {
return timestamp;
}
public void setTimestamp(Object timestamp) {
this.timestamp = timestamp;
}
}
| [
"56851999+kg2224@users.noreply.github.com"
] | 56851999+kg2224@users.noreply.github.com |
fc2b67ee1401364eed4055cf3dedce7f92c6de1a | ea60d1a2a7cef14ee1bbb3b64c7a72ebaf7099b5 | /Medical Store/healthAssist/src/main/java/com/cg/healthAssist/dao/OrderDao.java | cc84c356132e52432791ed3d20f6fff6d5940807 | [] | no_license | Hemalatha-Sivasubramaniyan/MyRepoHemalatha | ce9ab81eaccb92c93ed8b223e5afef651733e581 | e383e3fba198fe89678f361cc9ac63d60845a5b8 | refs/heads/master | 2023-01-27T23:01:07.549174 | 2020-11-20T13:00:23 | 2020-11-20T13:00:23 | 314,550,842 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 888 | java | package com.cg.healthAssist.dao;
/**
* OrderDao interface consist of methods to be implemented in the Dao implementation class
* @author Hemalatha S
*/
import java.util.List;
import com.cg.healthAssist.exception.OrderIdNotFoundException;
import com.cg.healthAssist.model.Order;
public interface OrderDao {
/*
* This method will return the list of orders
*/
public List<Order> viewOrders();
/*
* This method will remove the order from Order database if the delivery is
* done. Also if the order is not available then results in exception
*/
public void deliverOrder(long orderId) throws OrderIdNotFoundException;
/*
* This method will show the order details of a particular orderId
*/
public Order viewOrderHistory(long orderId);
/*
* This two methods will perform begin and commit transaction
*/
void beginTransaction();
void commitTransaction();
}
| [
"hemalathasivasubramaniyan@gmail.com"
] | hemalathasivasubramaniyan@gmail.com |
1fdb4288e5fe2c4a9fa34a91113ae0493fd30c72 | 503d12c3ae666f7899ac41cdee5270c8a6c2df19 | /app/src/main/java/com/project/MyApplication/TestDialog.java | 51c3adb947c53ee8972c1dd2746a1e79d1a32c63 | [] | no_license | byz1014/baseLib | a1a034719d475db791ed4a158db9e54b999b1817 | 0a62c931340f69e8726757327df79c4b7c456f91 | refs/heads/master | 2022-08-30T20:26:39.181116 | 2020-05-21T09:02:33 | 2020-05-21T09:02:33 | 264,843,790 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,037 | java | package com.project.MyApplication;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.TextView;
import com.example.baselib.BaseDialog;
import com.example.baselib.FindviewbyId;
public class TestDialog extends BaseDialog {
@FindviewbyId(value = R.id.tv_true,click = true)
TextView tv_true;
@FindviewbyId(value = R.id.tv_cancle,click = true)
TextView tv_cancle;
public TestDialog(@NonNull Context context) {
super(context, R.style.customDialog);
}
@Override
protected int onLayout() {
return R.layout.dialog_message;
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.tv_true:
if(mDialogCallBackListener!=null){
mDialogCallBackListener.onSuccess(null);
}
dismiss();
break;
case R.id.tv_cancle:
dismiss();
break;
}
}
}
| [
"byz1014@163.com"
] | byz1014@163.com |
e06f3cc66ed9ca44f7df99c632afbf0ce9d11cbd | cd1b9f3b4d5abe93f2d2c8fdcc2a3af815f420e0 | /ExerciciosAula10Agosto/src/exercicio4/Util.java | d1203cf22929aeaf07366520073143d8c51d4fb6 | [] | no_license | FernandoGiuseppeSalvetti/LaboratorioProgramacao | ceed6433b76c22eabeea3e4cc80d4f994f6378bf | bb086a37cde33fc1fdaac8eeb30483b36d7f4ff4 | refs/heads/main | 2023-07-15T20:27:37.954932 | 2021-09-01T02:43:07 | 2021-09-01T02:43:07 | 399,328,300 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 2,517 | java | package exercicio4;
public class Util {
public boolean validaTempoContribuicao(String sexo, int anosDeContribuicao) {
if(sexo == "masculino") {
if(anosDeContribuicao >= 35) {
return true;
}
return false;
}else {
if(anosDeContribuicao >= 30) {
return true;
}
return false;
}
}
public boolean validaIdade(String sexo, int idade, int anosDeContribuicao) {
if(sexo.toLowerCase() == "masculino") {
if(idade >= 65) {
return true;
}
return false;
}else {
if(anosDeContribuicao >= 60) {
return true;
}
return false;
}
}
public int calculaTempoRestanteContribuicao(String sexo, int idade, int anosDeContribuicao) {
if(sexo.toLowerCase() == "masculino") {
return 30 - anosDeContribuicao;
}else {
return 35 - anosDeContribuicao;
}
}
public String calculaTempoRestanteAposentadoria(String sexo, int idade, int anosDeContribuicao) {
if(sexo.toLowerCase() == "masculino") {
if(validaTempoContribuicao(sexo, anosDeContribuicao)) {
if(validaIdade(sexo, idade, anosDeContribuicao) == false) {
return "Você precisa trabalhar até os 65 anos para se aposentar.";
}
}else {
if(validaIdade(sexo, idade, anosDeContribuicao) == false) {
return "Você precisa trabalhar até os 65 anos para se aposentar, e contribuir mais " + calculaTempoRestanteContribuicao(sexo, idade, anosDeContribuicao) + " anos";
}
return "Você precisa contribuir mais " + calculaTempoRestanteContribuicao(sexo, idade, anosDeContribuicao) + " anos para se aposentar.";
}
} else {
if(validaTempoContribuicao(sexo, anosDeContribuicao)) {
if(validaIdade(sexo, idade, anosDeContribuicao) == false) {
return "Você precisa trabalhar até os 65 anos para se aposentar.";
}
}else {
if(validaIdade(sexo, idade, anosDeContribuicao) == false) {
return "Você precisa trabalhar até os 65 anos para se aposentar, e contribuir mais " + calculaTempoRestanteContribuicao(sexo, idade, anosDeContribuicao) + " anos";
}
return "Você precisa contribuir mais " + calculaTempoRestanteContribuicao(sexo, idade, anosDeContribuicao) + " anos para se aposentar.";
}
}
return "Sexo inválido";
}
public boolean podeAposentar(String sexo, int idade, int anosDeContribuicao) {
if(validaIdade(sexo, idade, anosDeContribuicao) && validaTempoContribuicao(sexo, anosDeContribuicao)) {
return true;
}else{
return false;
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
4f58b304e3bc4accb3a906e036b39cda463147b2 | 6beeb3a9fa13c94e5899cb2f02aaf0cc2f3ca581 | /gestion de personnel/src/gestion/de/personnel/Info_employe.java | 4ddac3f614cc07d889e8f45379319dbdc07b9d46 | [] | no_license | AARABAabdallah/employee-RH-management-app | 057d57046a60426980aa0c71b952ec9d8d8ad97b | dc6f47833f5cc212a4609364801e10679433e34a | refs/heads/master | 2020-04-24T17:31:10.032724 | 2019-02-23T00:01:42 | 2019-02-23T00:01:42 | 172,150,234 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 34,471 | 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 gestion.de.personnel;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.imageio.ImageIO;
import javax.swing.*;
/**
*
* @author aarab
*/
public class Info_employe extends javax.swing.JFrame {
Connection conn=null;
ResultSet rs=null;
PreparedStatement pst=null;
ResultSet rs1=null;
PreparedStatement pst1=null;
/**
* Creates new form addEmployee
*/
public Info_employe() {
conn=db.java_db();
initComponents();
Toolkit toolkit = getToolkit();
Dimension size = toolkit.getScreenSize();
setLocation(size.width/2 - getWidth()/2,
size.height/2 - getHeight()/2);
getInfos();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
txt_id = new javax.swing.JTextField();
txt_firstname = new javax.swing.JTextField();
txt_surname = new javax.swing.JTextField();
txt_dob = new javax.swing.JTextField();
txt_email = new javax.swing.JTextField();
txt_tel = new javax.swing.JTextField();
txt_add1 = new javax.swing.JTextField();
txt_add2 = new javax.swing.JTextField();
txt_job = new javax.swing.JTextField();
txt_apt = new javax.swing.JTextField();
txt_status = new javax.swing.JTextField();
txt_pc = new javax.swing.JTextField();
txt_dep = new javax.swing.JTextField();
txt_doj = new javax.swing.JTextField();
txt_salary = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jLabel17 = new javax.swing.JLabel();
r_male = new javax.swing.JRadioButton();
r_female = new javax.swing.JRadioButton();
jDesktopPane1 = new javax.swing.JDesktopPane();
img = new javax.swing.JLabel();
jButton3 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
txt_id.setEditable(false);
txt_dob.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txt_dobActionPerformed(evt);
}
});
txt_add2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txt_add2ActionPerformed(evt);
}
});
txt_status.setEditable(false);
txt_dep.setEditable(false);
txt_dep.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txt_depActionPerformed(evt);
}
});
txt_salary.setEditable(false);
jLabel1.setText("Matricule :");
jLabel2.setText("Nom :");
jLabel3.setText("Date de naissance :");
jLabel4.setText("Prénom :");
jLabel5.setText("Tél :");
jLabel6.setText("Adresse 2:");
jLabel7.setText("Adresse 1:");
jLabel8.setText("Email :");
jLabel9.setText("App./Maison No :");
jLabel10.setText("Code Postale :");
jLabel12.setText("Departement :");
jLabel13.setText("Salaire de base :");
jLabel14.setText("Etat :");
jLabel15.setText("Profession :");
jLabel16.setText("Date d'embauche :");
jLabel17.setText("Sex");
r_male.setText("Homme");
r_male.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
r_maleActionPerformed(evt);
}
});
r_female.setText("Femme");
r_female.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
r_femaleActionPerformed(evt);
}
});
jDesktopPane1.setLayer(img, javax.swing.JLayeredPane.DEFAULT_LAYER);
javax.swing.GroupLayout jDesktopPane1Layout = new javax.swing.GroupLayout(jDesktopPane1);
jDesktopPane1.setLayout(jDesktopPane1Layout);
jDesktopPane1Layout.setHorizontalGroup(
jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jDesktopPane1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(img, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jDesktopPane1Layout.setVerticalGroup(
jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jDesktopPane1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(img, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jButton3.setText("Modifier photo");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton5.setText("Modifier");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jButton3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jDesktopPane1, javax.swing.GroupLayout.Alignment.LEADING))
.addGap(40, 40, 40)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txt_id, javax.swing.GroupLayout.PREFERRED_SIZE, 359, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 561, Short.MAX_VALUE)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel17, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(48, 48, 48)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(r_male, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(r_female))
.addComponent(txt_surname, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txt_firstname, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txt_add1, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_add2, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(149, 149, 149)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txt_email, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_tel, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_dob, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel9)
.addComponent(jLabel16, javax.swing.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE)
.addComponent(jLabel12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel13, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txt_apt, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_pc, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_dep, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_doj, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txt_salary, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txt_job, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel14, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txt_status, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGap(40, 40, 40))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(34, 34, 34)
.addComponent(jDesktopPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(95, 95, 95)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_id, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))))
.addGap(27, 27, 27)
.addComponent(jButton3)
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(txt_firstname, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(11, 11, 11)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txt_surname, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(r_male)
.addComponent(r_female)
.addComponent(jLabel17))
.addGap(17, 17, 17)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_dob, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_email, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5)
.addComponent(txt_tel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7)
.addComponent(txt_add1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addComponent(txt_add2, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_apt, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel9))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_pc, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel12)
.addComponent(txt_dep, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(50, 50, 50)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel16)
.addComponent(txt_doj, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_salary, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel13))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_job, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txt_status, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel14))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void txt_add2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_add2ActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_add2ActionPerformed
private void txt_dobActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_dobActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_dobActionPerformed
private void txt_depActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_depActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_depActionPerformed
/* }
*/
/**/
private void r_femaleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_r_femaleActionPerformed
// TODO add your handling code here:
gender="Female";
r_female.setSelected(true);
r_male.setSelected(false);
}//GEN-LAST:event_r_femaleActionPerformed
private void r_maleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_r_maleActionPerformed
// TODO add your handling code here:
gender="Male";
r_male.setSelected(true);
r_female.setSelected(false);
}//GEN-LAST:event_r_maleActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
JFileChooser choser =new JFileChooser();
choser.showOpenDialog(null);
File f=choser.getSelectedFile();
filename=f.getAbsolutePath();
ImageIcon imageIcon=new ImageIcon(new ImageIcon(filename).getImage().getScaledInstance(img.getWidth(),img.getHeight(),Image.SCALE_DEFAULT));
img.setIcon(imageIcon);
try{
File image=new File(filename);
FileInputStream fix=new FileInputStream(image);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
byte[] buf=new byte[1024];
for(int n;(n=fix.read(buf))!=-1;){
bos.write(buf,0,n);
}
person_image=bos.toByteArray();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}//GEN-LAST:event_jButton3ActionPerformed
/**/
private void getInfos() {
// TODO add your handling code here:
try{
String sql ="select * from Staff_information where id=? ";
String sql2 ="select emp_id from users where id=? ";
String iid=String.valueOf(Emp.empId);
pst1=conn.prepareStatement(sql2);
pst1.setString(1,iid);
rs1=pst1.executeQuery();
String iiid =rs1.getString("emp_id");
pst=conn.prepareStatement(sql);
pst.setString(1,iiid);
rs=pst.executeQuery();
String add1 =rs.getString("id");
txt_id.setText(add1);
String add2 =rs.getString("first_name");
txt_firstname.setText(add2);
String add3 =rs.getString("surname");
txt_surname.setText(add3);
String add4 =rs.getString("Dob");
txt_dob.setText(add4);
String add5 =rs.getString("Email");
txt_email.setText(add5);
String add6 =rs.getString("Telephone");
txt_tel.setText(add6);
String add7 =rs.getString("Address");
txt_add1.setText(add7);
String add8 =rs.getString("Department");
txt_dep.setText(add8);
String add10 =rs.getString("Salary");
txt_salary.setText(add10);
String add11 =rs.getString("Address2");
txt_add2.setText(add11);
String add12 =rs.getString("Apartment");
txt_apt.setText(add12);
String add13 =rs.getString("Post_code");
txt_pc.setText(add13);
String add14 =rs.getString("Status");
txt_status.setText(add14);
String add15 =rs.getString("Date_hired");
txt_doj.setText(add15);
String add16 =rs.getString("job_title");
txt_job.setText(add16);
String add17 =rs.getString("Designation");
if(gender=="Male"){
r_male.setSelected(true);
r_female.setSelected(false);
}else if(gender=="Female"){
r_male.setSelected(false);
r_female.setSelected(true);
}
byte[] image = rs.getBytes("Image");
if(image!=null){
ImageIcon imageIcon = new ImageIcon(new ImageIcon(image).getImage().getScaledInstance(img.getWidth(), img.getHeight(), Image.SCALE_SMOOTH));
img.setIcon(imageIcon);
}
else{
img.setIcon(null);
}
}catch(Exception e){
}
finally {
try{
rs.close();
pst.close();
rs1.close();
pst1.close();
}
catch(Exception e){
}
}
}
/* }
*/
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
// TODO add your handling code here:
int x = JOptionPane.showConfirmDialog(null, "Voulez-vous vraiment mettre à jour les données?","Update Record",JOptionPane.YES_NO_OPTION);
if(x==0){
String value4 = txt_id.getText();
try{
String value1 = txt_firstname.getText();
String value2 = txt_surname.getText();
String value3 = txt_dob.getText();
String value5 = txt_email.getText();
String value6 = txt_tel.getText();
String value7 = txt_add1.getText();
String value8 = txt_dep.getText();
String value9 = txt_add2.getText();
String value10 = txt_apt.getText();
String value11 = txt_pc.getText();
String value12 = null;
String value13 = txt_status.getText();
String value14 = txt_salary.getText();
String value15 = txt_job.getText();
String value16 = txt_doj.getText();
String value17=gender;
String sql= "update Staff_information set id='"+value4+"',first_name='"+value1+"', surname='"+value2+"', "
+ "Dob='"+value3+"',Email='"+value5+"',Telephone='"+value6+"',"
+ "Address='"+value7+"',Department='"+value8+"', Address2 = '"+value9+"', "
+ "Apartment = '"+value10+"', Post_code ='"+value11+"', "
+ "Designation ='"+value12+"', Status ='"+value13+"',Gender='"+value17+"', Salary ='"+value14+"', job_title ='"+value15+"', Date_Hired ='"+value16+"' "
+ " where id='"+value4+"' ";
pst=conn.prepareStatement(sql);
pst.execute();
JOptionPane.showMessageDialog(null, "Les données sont mis à jour");
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
try {
File file = new File(filename);
FileInputStream fis = new FileInputStream(file);
byte[] image = new byte[(int) file.length()];
fis.read(image);
String sql = "update Staff_information SET Image =? where id ='"+value4+"'";
pst = conn.prepareStatement(sql);
pst.setBytes(1, image);
pst.executeUpdate();
pst.close();
}catch(Exception ee){
JOptionPane.showMessageDialog(null, ee);
}
}finally {
try{
rs.close();
pst.close();
}
catch(Exception e){
}
}
}//GEN-LAST:event_jButton5ActionPerformed
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Info_employe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Info_employe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Info_employe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Info_employe.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Info_employe().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel img;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton5;
private javax.swing.JDesktopPane jDesktopPane1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JRadioButton r_female;
private javax.swing.JRadioButton r_male;
private javax.swing.JTextField txt_add1;
private javax.swing.JTextField txt_add2;
private javax.swing.JTextField txt_apt;
private javax.swing.JTextField txt_dep;
private javax.swing.JTextField txt_dob;
private javax.swing.JTextField txt_doj;
private javax.swing.JTextField txt_email;
private javax.swing.JTextField txt_firstname;
private javax.swing.JTextField txt_id;
private javax.swing.JTextField txt_job;
private javax.swing.JTextField txt_pc;
private javax.swing.JTextField txt_salary;
private javax.swing.JTextField txt_status;
private javax.swing.JTextField txt_surname;
private javax.swing.JTextField txt_tel;
// End of variables declaration//GEN-END:variables
private String gender;
private ImageIcon format=null;
String filename=null;
byte[] person_image=null;
}
| [
"aaraba10abdallah@gmail.com"
] | aaraba10abdallah@gmail.com |
ea4fdf0b088edd8bea7ae4200207334cedfee00e | bfc3bcccc1315b445168ad2ccaaf6262f448c8e9 | /TorrentzFilmes/src/br/com/torrentz/util/UtilData.java | b5a7b4234eb2b8dc8f34a438f8bc1e3200933bc7 | [
"MIT"
] | permissive | Viniciusalopes/torrentz-filmes | c99ced5b89186a975f9b6e171e3bea5f950cb074 | e0270731e6ac68a4d81bc2af75b0e5213efb5f9c | refs/heads/main | 2023-01-07T13:17:41.211408 | 2020-11-12T09:59:00 | 2020-11-12T09:59:00 | 307,871,287 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 920 | 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 br.com.torrentz.util;
/**
*
* @author vovolinux
*/
public class UtilData {
public static void validateFormatDate(String date) throws Exception {
String[] split = date.split("/");
String pattern = "Formato aceito: dd/mm/yyyy";
if (split.length != 3) {
throw new Exception("Data inválida!\n" + pattern);
}
if (split[0].trim().length() < 2) {
throw new Exception("Dia inválido!\n" + pattern);
}
if (split[1].trim().length() < 2) {
throw new Exception("Mês inválido!\n" + pattern);
}
if (split[2].trim().length() < 4) {
throw new Exception("Ano inválido!\n" + pattern);
}
}
}
| [
"suporte@viniciusalopes.com.br"
] | suporte@viniciusalopes.com.br |
b87efe9f0b7bfdaa4305674c7ca759bd63c899db | a7a5ea1965def34f212d0799e5957faf198aa3a3 | /android/Streaming/magicfilter/src/main/java/com/seu/magicfilter/advanced/MagicPixarFilter.java | 24ded55cf6b4b9fd6ac17b75c2ad0daa317ec5bb | [] | no_license | 18307612949/AndroidFFmpeg | dc911355659b953c893ff4af54d304505b0c552e | a91b480e530957cfe3b3d455e8a0594bc7578c35 | refs/heads/master | 2021-08-16T06:13:14.412157 | 2017-10-16T07:42:27 | 2017-10-16T07:42:27 | 107,400,346 | 1 | 0 | null | 2017-10-18T11:44:03 | 2017-10-18T11:44:02 | null | UTF-8 | Java | false | false | 2,299 | java | package com.seu.magicfilter.advanced;
import android.opengl.GLES20;
import com.seu.magicfilter.R;
import com.seu.magicfilter.utils.MagicFilterType;
import com.seu.magicfilter.base.gpuimage.GPUImageFilter;
import com.seu.magicfilter.utils.MagicFilterFactory;
import com.seu.magicfilter.utils.OpenGLUtils;
public class MagicPixarFilter extends GPUImageFilter{
private int[] inputTextureHandles = {-1};
private int[] inputTextureUniformLocations = {-1};
private int mGLStrengthLocation;
public MagicPixarFilter(){
super(MagicFilterType.PIXAR, R.raw.pixar);
}
@Override
protected void onDestroy() {
super.onDestroy();
GLES20.glDeleteTextures(1, inputTextureHandles, 0);
for (int i = 0; i < inputTextureHandles.length; i++) {
inputTextureHandles[i] = -1;
}
}
@Override
protected void onDrawArraysAfter(){
for(int i = 0; i < inputTextureHandles.length && inputTextureHandles[i] != OpenGLUtils.NO_TEXTURE; i++){
GLES20.glActiveTexture(GLES20.GL_TEXTURE0 + (i+3));
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, 0);
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
}
}
@Override
protected void onDrawArraysPre(){
for (int i = 0; i < inputTextureHandles.length && inputTextureHandles[i] != OpenGLUtils.NO_TEXTURE; i++){
GLES20.glActiveTexture(GLES20.GL_TEXTURE0 + (i+3) );
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, inputTextureHandles[i]);
GLES20.glUniform1i(inputTextureUniformLocations[i], (i+3));
}
}
@Override
protected void onInit(){
super.onInit();
for (int i=0; i < inputTextureUniformLocations.length; i++) {
inputTextureUniformLocations[i] = GLES20.glGetUniformLocation(getProgram(), "inputImageTexture" + (2 + i));
}
mGLStrengthLocation = GLES20.glGetUniformLocation(getProgram(), "strength");
}
@Override
protected void onInitialized(){
super.onInitialized();
setFloat(mGLStrengthLocation, 1.0f);
runOnDraw(new Runnable(){
public void run(){
inputTextureHandles[0] = OpenGLUtils.loadTexture(getContext(), "filter/pixar_curves.png");
}
});
}
}
| [
"wlanjie888@gmail.com"
] | wlanjie888@gmail.com |
3db0da78afb570274d77d0c3cbe1e26cbd35259b | 192fc75e245f8834861c2a8dbe9714daa2ec6c2e | /CWE89_SQL_Injection/CWE89_SQL_Injection__console_readLine_executeUpdate_10.java | f15c115e3cc632bdc15bbbf33ebbbead5ed3f1e3 | [] | no_license | Carlosboie/Playtech | 6f8bb72efc6769612a0cb967a9130f6db78d19fc | 684ae94b9b0ff069c8561157227b5b43a7ca1320 | refs/heads/master | 2021-05-27T11:05:24.157218 | 2012-09-12T08:08:30 | 2012-09-12T08:08:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 26,946 | java | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE89_SQL_Injection__console_readLine_executeUpdate_10.java
Label Definition File: CWE89_SQL_Injection.label.xml
Template File: sources-sinks-10.tmpl.java
*/
/*
* @description
* CWE: 89 SQL Injection
* BadSource: console_readLine Read data from the console using readLine
* GoodSource: A hardcoded string
* Sinks: executeUpdate
* GoodSink: prepared sqlstatement, executeUpdate
* BadSink : raw query used in executeUpdate
* Flow Variant: 10 Control flow: if(IO.static_t) and if(IO.static_f)
*
* */
package testcases.CWE89_SQL_Injection;
import testcasesupport.*;
import java.sql.*;
import javax.servlet.http.*;
import java.util.logging.Logger;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.logging.Logger;
public class CWE89_SQL_Injection__console_readLine_executeUpdate_10 extends AbstractTestCase
{
public void bad() throws Throwable
{
String data;
/* INCIDENTAL: CWE 571 Statement is Always True */
if(IO.static_t)
{
Logger log_bad = Logger.getLogger("local-logger");
data = ""; /* init data */
/* read user input from console with readLine*/
BufferedReader buffread = null;
InputStreamReader instrread = null;
try
{
instrread = new InputStreamReader(System.in);
buffread = new BufferedReader(instrread);
data = buffread.readLine();
}
catch( IOException ioe )
{
log_bad.warning("Error with stream reading");
}
finally
{
/* clean up stream reading objects */
try {
if( buffread != null )
{
buffread.close();
}
}
catch( IOException ioe )
{
log_bad.warning("Error closing buffread");
}
finally {
try {
if( instrread != null )
{
instrread.close();
}
}
catch( IOException ioe )
{
log_bad.warning("Error closing instrread");
}
}
}
}
else {
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");
/* FIX: Use a hardcoded string */
data = "foo";
}
/* INCIDENTAL: CWE 571 Statement is Always True */
if(IO.static_t)
{
Logger log2 = Logger.getLogger("local-logger");
Connection conn_tmp2 = null;
Statement sqlstatement = null;
try
{
conn_tmp2 = IO.getDBConnection();
sqlstatement = conn_tmp2.createStatement();
/* POTENTIAL FLAW: place user input into dynamic sql query */
int iResult = sqlstatement.executeUpdate("insert into users (status) values ('updated') where name='"+data+"'");
IO.writeString("Updated " + iResult + " rows successfully.");
}
catch( SQLException se )
{
log2.warning("Error getting database connection");
}
finally
{
try {
if( sqlstatement != null )
{
sqlstatement.close();
}
}
catch( SQLException e )
{
log2.warning("Error closing sqlstatement");
}
finally {
try {
if( conn_tmp2 != null )
{
conn_tmp2.close();
}
}
catch( SQLException e )
{
log2.warning("Error closing conn_tmp2");
}
}
}
}
else {
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
Logger log2 = Logger.getLogger("local-logger");
Connection conn_tmp2 = null;
PreparedStatement sqlstatement = null;
try {
/* FIX: use prepared sqlstatement */
conn_tmp2 = IO.getDBConnection();
sqlstatement = conn_tmp2.prepareStatement("insert into users (status) values ('updated') where name=?");
sqlstatement.setString(1, data);
int iResult = sqlstatement.executeUpdate();
IO.writeString("Updated " + iResult + " rows successfully.");
}
catch( SQLException se )
{
log2.warning("Error getting database connection");
}
finally {
try {
if( sqlstatement != null )
{
sqlstatement.close();
}
}
catch( SQLException e )
{
log2.warning("Error closing sqlstatement");
}
finally {
try {
if( conn_tmp2 != null )
{
conn_tmp2.close();
}
}
catch( SQLException e )
{
log2.warning("Error closing conn_tmp2");
}
}
}
}
}
/* goodG2B1() - use goodsource and badsink by changing first IO.static_t to IO.static_f */
private void goodG2B1() throws Throwable
{
String data;
/* INCIDENTAL: CWE 570 Statement is Always False */
if(IO.static_f)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
Logger log_bad = Logger.getLogger("local-logger");
data = ""; /* init data */
/* read user input from console with readLine*/
BufferedReader buffread = null;
InputStreamReader instrread = null;
try
{
instrread = new InputStreamReader(System.in);
buffread = new BufferedReader(instrread);
data = buffread.readLine();
}
catch( IOException ioe )
{
log_bad.warning("Error with stream reading");
}
finally
{
/* clean up stream reading objects */
try {
if( buffread != null )
{
buffread.close();
}
}
catch( IOException ioe )
{
log_bad.warning("Error closing buffread");
}
finally {
try {
if( instrread != null )
{
instrread.close();
}
}
catch( IOException ioe )
{
log_bad.warning("Error closing instrread");
}
}
}
}
else {
java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");
/* FIX: Use a hardcoded string */
data = "foo";
}
/* INCIDENTAL: CWE 571 Statement is Always True */
if(IO.static_t)
{
Logger log2 = Logger.getLogger("local-logger");
Connection conn_tmp2 = null;
Statement sqlstatement = null;
try
{
conn_tmp2 = IO.getDBConnection();
sqlstatement = conn_tmp2.createStatement();
/* POTENTIAL FLAW: place user input into dynamic sql query */
int iResult = sqlstatement.executeUpdate("insert into users (status) values ('updated') where name='"+data+"'");
IO.writeString("Updated " + iResult + " rows successfully.");
}
catch( SQLException se )
{
log2.warning("Error getting database connection");
}
finally
{
try {
if( sqlstatement != null )
{
sqlstatement.close();
}
}
catch( SQLException e )
{
log2.warning("Error closing sqlstatement");
}
finally {
try {
if( conn_tmp2 != null )
{
conn_tmp2.close();
}
}
catch( SQLException e )
{
log2.warning("Error closing conn_tmp2");
}
}
}
}
else {
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
Logger log2 = Logger.getLogger("local-logger");
Connection conn_tmp2 = null;
PreparedStatement sqlstatement = null;
try {
/* FIX: use prepared sqlstatement */
conn_tmp2 = IO.getDBConnection();
sqlstatement = conn_tmp2.prepareStatement("insert into users (status) values ('updated') where name=?");
sqlstatement.setString(1, data);
int iResult = sqlstatement.executeUpdate();
IO.writeString("Updated " + iResult + " rows successfully.");
}
catch( SQLException se )
{
log2.warning("Error getting database connection");
}
finally {
try {
if( sqlstatement != null )
{
sqlstatement.close();
}
}
catch( SQLException e )
{
log2.warning("Error closing sqlstatement");
}
finally {
try {
if( conn_tmp2 != null )
{
conn_tmp2.close();
}
}
catch( SQLException e )
{
log2.warning("Error closing conn_tmp2");
}
}
}
}
}
/* goodG2B2() - use goodsource and badsink by reversing statements in first if */
private void goodG2B2() throws Throwable
{
String data;
/* INCIDENTAL: CWE 571 Statement is Always True */
if(IO.static_t)
{
java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");
/* FIX: Use a hardcoded string */
data = "foo";
}
else {
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
Logger log_bad = Logger.getLogger("local-logger");
data = ""; /* init data */
/* read user input from console with readLine*/
BufferedReader buffread = null;
InputStreamReader instrread = null;
try {
instrread = new InputStreamReader(System.in);
buffread = new BufferedReader(instrread);
data = buffread.readLine();
}
catch( IOException ioe )
{
log_bad.warning("Error with stream reading");
}
finally {
/* clean up stream reading objects */
try {
if( buffread != null )
{
buffread.close();
}
}
catch( IOException ioe )
{
log_bad.warning("Error closing buffread");
}
finally {
try {
if( instrread != null )
{
instrread.close();
}
}
catch( IOException ioe )
{
log_bad.warning("Error closing instrread");
}
}
}
}
/* INCIDENTAL: CWE 571 Statement is Always True */
if(IO.static_t)
{
Logger log2 = Logger.getLogger("local-logger");
Connection conn_tmp2 = null;
Statement sqlstatement = null;
try
{
conn_tmp2 = IO.getDBConnection();
sqlstatement = conn_tmp2.createStatement();
/* POTENTIAL FLAW: place user input into dynamic sql query */
int iResult = sqlstatement.executeUpdate("insert into users (status) values ('updated') where name='"+data+"'");
IO.writeString("Updated " + iResult + " rows successfully.");
}
catch( SQLException se )
{
log2.warning("Error getting database connection");
}
finally
{
try {
if( sqlstatement != null )
{
sqlstatement.close();
}
}
catch( SQLException e )
{
log2.warning("Error closing sqlstatement");
}
finally {
try {
if( conn_tmp2 != null )
{
conn_tmp2.close();
}
}
catch( SQLException e )
{
log2.warning("Error closing conn_tmp2");
}
}
}
}
else {
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
Logger log2 = Logger.getLogger("local-logger");
Connection conn_tmp2 = null;
PreparedStatement sqlstatement = null;
try {
/* FIX: use prepared sqlstatement */
conn_tmp2 = IO.getDBConnection();
sqlstatement = conn_tmp2.prepareStatement("insert into users (status) values ('updated') where name=?");
sqlstatement.setString(1, data);
int iResult = sqlstatement.executeUpdate();
IO.writeString("Updated " + iResult + " rows successfully.");
}
catch( SQLException se )
{
log2.warning("Error getting database connection");
}
finally {
try {
if( sqlstatement != null )
{
sqlstatement.close();
}
}
catch( SQLException e )
{
log2.warning("Error closing sqlstatement");
}
finally {
try {
if( conn_tmp2 != null )
{
conn_tmp2.close();
}
}
catch( SQLException e )
{
log2.warning("Error closing conn_tmp2");
}
}
}
}
}
/* goodB2G1() - use badsource and goodsink by changing second IO.static_t to IO.static_f */
private void goodB2G1() throws Throwable
{
String data;
/* INCIDENTAL: CWE 571 Statement is Always True */
if(IO.static_t)
{
Logger log_bad = Logger.getLogger("local-logger");
data = ""; /* init data */
/* read user input from console with readLine*/
BufferedReader buffread = null;
InputStreamReader instrread = null;
try
{
instrread = new InputStreamReader(System.in);
buffread = new BufferedReader(instrread);
data = buffread.readLine();
}
catch( IOException ioe )
{
log_bad.warning("Error with stream reading");
}
finally
{
/* clean up stream reading objects */
try {
if( buffread != null )
{
buffread.close();
}
}
catch( IOException ioe )
{
log_bad.warning("Error closing buffread");
}
finally {
try {
if( instrread != null )
{
instrread.close();
}
}
catch( IOException ioe )
{
log_bad.warning("Error closing instrread");
}
}
}
}
else {
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");
/* FIX: Use a hardcoded string */
data = "foo";
}
/* INCIDENTAL: CWE 570 Statement is Always False */
if(IO.static_f)
{
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
Logger log2 = Logger.getLogger("local-logger");
Connection conn_tmp2 = null;
Statement sqlstatement = null;
try
{
conn_tmp2 = IO.getDBConnection();
sqlstatement = conn_tmp2.createStatement();
/* POTENTIAL FLAW: place user input into dynamic sql query */
int iResult = sqlstatement.executeUpdate("insert into users (status) values ('updated') where name='"+data+"'");
IO.writeString("Updated " + iResult + " rows successfully.");
}
catch( SQLException se )
{
log2.warning("Error getting database connection");
}
finally
{
try {
if( sqlstatement != null )
{
sqlstatement.close();
}
}
catch( SQLException e )
{
log2.warning("Error closing sqlstatement");
}
finally {
try {
if( conn_tmp2 != null )
{
conn_tmp2.close();
}
}
catch( SQLException e )
{
log2.warning("Error closing conn_tmp2");
}
}
}
}
else {
Logger log2 = Logger.getLogger("local-logger");
Connection conn_tmp2 = null;
PreparedStatement sqlstatement = null;
try {
/* FIX: use prepared sqlstatement */
conn_tmp2 = IO.getDBConnection();
sqlstatement = conn_tmp2.prepareStatement("insert into users (status) values ('updated') where name=?");
sqlstatement.setString(1, data);
int iResult = sqlstatement.executeUpdate();
IO.writeString("Updated " + iResult + " rows successfully.");
}
catch( SQLException se )
{
log2.warning("Error getting database connection");
}
finally {
try {
if( sqlstatement != null )
{
sqlstatement.close();
}
}
catch( SQLException e )
{
log2.warning("Error closing sqlstatement");
}
finally {
try {
if( conn_tmp2 != null )
{
conn_tmp2.close();
}
}
catch( SQLException e )
{
log2.warning("Error closing conn_tmp2");
}
}
}
}
}
/* goodB2G2() - use badsource and goodsink by reversing statements in second if */
private void goodB2G2() throws Throwable
{
String data;
/* INCIDENTAL: CWE 571 Statement is Always True */
if(IO.static_t)
{
Logger log_bad = Logger.getLogger("local-logger");
data = ""; /* init data */
/* read user input from console with readLine*/
BufferedReader buffread = null;
InputStreamReader instrread = null;
try
{
instrread = new InputStreamReader(System.in);
buffread = new BufferedReader(instrread);
data = buffread.readLine();
}
catch( IOException ioe )
{
log_bad.warning("Error with stream reading");
}
finally
{
/* clean up stream reading objects */
try {
if( buffread != null )
{
buffread.close();
}
}
catch( IOException ioe )
{
log_bad.warning("Error closing buffread");
}
finally {
try {
if( instrread != null )
{
instrread.close();
}
}
catch( IOException ioe )
{
log_bad.warning("Error closing instrread");
}
}
}
}
else {
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
java.util.logging.Logger log_good = java.util.logging.Logger.getLogger("local-logger");
/* FIX: Use a hardcoded string */
data = "foo";
}
/* INCIDENTAL: CWE 571 Statement is Always True */
if(IO.static_t)
{
Logger log2 = Logger.getLogger("local-logger");
Connection conn_tmp2 = null;
PreparedStatement sqlstatement = null;
try
{
/* FIX: use prepared sqlstatement */
conn_tmp2 = IO.getDBConnection();
sqlstatement = conn_tmp2.prepareStatement("insert into users (status) values ('updated') where name=?");
sqlstatement.setString(1, data);
int iResult = sqlstatement.executeUpdate();
IO.writeString("Updated " + iResult + " rows successfully.");
}
catch( SQLException se )
{
log2.warning("Error getting database connection");
}
finally
{
try {
if( sqlstatement != null )
{
sqlstatement.close();
}
}
catch( SQLException e )
{
log2.warning("Error closing sqlstatement");
}
finally {
try {
if( conn_tmp2 != null )
{
conn_tmp2.close();
}
}
catch( SQLException e )
{
log2.warning("Error closing conn_tmp2");
}
}
}
}
else {
/* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
Logger log2 = Logger.getLogger("local-logger");
Connection conn_tmp2 = null;
Statement sqlstatement = null;
try {
conn_tmp2 = IO.getDBConnection();
sqlstatement = conn_tmp2.createStatement();
/* POTENTIAL FLAW: place user input into dynamic sql query */
int iResult = sqlstatement.executeUpdate("insert into users (status) values ('updated') where name='"+data+"'");
IO.writeString("Updated " + iResult + " rows successfully.");
}
catch( SQLException se )
{
log2.warning("Error getting database connection");
}
finally {
try {
if( sqlstatement != null )
{
sqlstatement.close();
}
}
catch( SQLException e )
{
log2.warning("Error closing sqlstatement");
}
finally {
try {
if( conn_tmp2 != null )
{
conn_tmp2.close();
}
}
catch( SQLException e )
{
log2.warning("Error closing conn_tmp2");
}
}
}
}
}
public void good() throws Throwable
{
goodG2B1();
goodG2B2();
goodB2G1();
goodB2G2();
}
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException, IllegalAccessException
{
mainFromParent(args);
}
}
| [
"amitf@checkmarx.com"
] | amitf@checkmarx.com |
71e4b76517094782c90cd33679f3c9b8d9aa8fa0 | eaec4795e768f4631df4fae050fd95276cd3e01b | /src/cmps252/HW4_2/UnitTesting/record_686.java | 93e5cc717a8176e6c866bb0c1829dcb4c888e6ed | [
"MIT"
] | permissive | baraabilal/cmps252_hw4.2 | debf5ae34ce6a7ff8d3bce21b0345874223093bc | c436f6ae764de35562cf103b049abd7fe8826b2b | refs/heads/main | 2023-01-04T13:02:13.126271 | 2020-11-03T16:32:35 | 2020-11-03T16:32:35 | 307,839,669 | 1 | 0 | MIT | 2020-10-27T22:07:57 | 2020-10-27T22:07:56 | null | UTF-8 | Java | false | false | 2,444 | java | package cmps252.HW4_2.UnitTesting;
import static org.junit.jupiter.api.Assertions.*;
import java.io.FileNotFoundException;
import java.util.List;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import cmps252.HW4_2.Customer;
import cmps252.HW4_2.FileParser;
@Tag("6")
class Record_686 {
private static List<Customer> customers;
@BeforeAll
public static void init() throws FileNotFoundException {
customers = FileParser.getCustomers(Configuration.CSV_File);
}
@Test
@DisplayName("Record 686: FirstName is Billie")
void FirstNameOfRecord686() {
assertEquals("Billie", customers.get(685).getFirstName());
}
@Test
@DisplayName("Record 686: LastName is Rivenberg")
void LastNameOfRecord686() {
assertEquals("Rivenberg", customers.get(685).getLastName());
}
@Test
@DisplayName("Record 686: Company is Cabbage, Elwin F Esq")
void CompanyOfRecord686() {
assertEquals("Cabbage, Elwin F Esq", customers.get(685).getCompany());
}
@Test
@DisplayName("Record 686: Address is 2095 Frank Ave")
void AddressOfRecord686() {
assertEquals("2095 Frank Ave", customers.get(685).getAddress());
}
@Test
@DisplayName("Record 686: City is Fairbanks")
void CityOfRecord686() {
assertEquals("Fairbanks", customers.get(685).getCity());
}
@Test
@DisplayName("Record 686: County is Fairbanks North Star")
void CountyOfRecord686() {
assertEquals("Fairbanks North Star", customers.get(685).getCounty());
}
@Test
@DisplayName("Record 686: State is AK")
void StateOfRecord686() {
assertEquals("AK", customers.get(685).getState());
}
@Test
@DisplayName("Record 686: ZIP is 99701")
void ZIPOfRecord686() {
assertEquals("99701", customers.get(685).getZIP());
}
@Test
@DisplayName("Record 686: Phone is 907-451-0587")
void PhoneOfRecord686() {
assertEquals("907-451-0587", customers.get(685).getPhone());
}
@Test
@DisplayName("Record 686: Fax is 907-451-3336")
void FaxOfRecord686() {
assertEquals("907-451-3336", customers.get(685).getFax());
}
@Test
@DisplayName("Record 686: Email is billie@rivenberg.com")
void EmailOfRecord686() {
assertEquals("billie@rivenberg.com", customers.get(685).getEmail());
}
@Test
@DisplayName("Record 686: Web is http://www.billierivenberg.com")
void WebOfRecord686() {
assertEquals("http://www.billierivenberg.com", customers.get(685).getWeb());
}
}
| [
"mbdeir@aub.edu.lb"
] | mbdeir@aub.edu.lb |
1af8c1a1ccc3574b0dbf3c9b998fbc223c01b564 | 9a0e39f51ae902ed329d898d200c353a7b7467e2 | /src/compiler/Compiler.java | a1c2cdc8a0df98be25459b43c49c00b6083f8fab | [] | no_license | fetouh15/cisc-compiler | 9c8c7d72261eb4319c272ff7ba1c4d7fbaf375ec | 34982974fc2c159a4c76bf179eaccc560034667c | refs/heads/master | 2020-08-27T19:05:08.114316 | 2019-10-25T06:32:36 | 2019-10-25T06:32:36 | 217,466,421 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 10,595 | 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 compiler;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
/**
*
* @author fetouh
*/
public class Compiler {
/**
* @param args the command line arguments
*/
static ArrayList<String> tokens = new ArrayList<String>();
public static int find(String X) {
int flag = 0, i = 0;
if (X.matches("[0-9]+")) {
flag = 1;
return flag;
}
int beg, end;
beg = tokens.indexOf("VAR");
end = tokens.indexOf("BEGIN");
for (i = beg + 1; i < end; i++) {
if (X.equalsIgnoreCase(tokens.get(i))) {
flag = 1;
return flag;
}
}
return flag;
}
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException, IOException {
long start = System.currentTimeMillis();
//String hlFile="";
//System.out.println(args.length);
// Scanner sc = new Scanner(System.in);
// hlFile=sc.next();
//args[0]="input.txt";
BufferedReader br = new BufferedReader(new FileReader(args[0]));
StringBuilder sb = new StringBuilder();
String linefile = br.readLine();
while (linefile != null) {
sb.append(linefile);
sb.append("\n");
linefile = br.readLine();
}
String line= sb.toString();
br.close();
int flagmaybe = 0, flag2 = 0;
// String backup = "PROGRAM|VAR|BEGIN|END|END.|FOR|READ|WRITE|TO|DO|;|=|\\+|FOR|\\(|\\)|\\*)";
/* String line = "PROGRAM BASICS VAR\n"
+ "X,A,B,C,Z BEGIN\n"
+ "READ(X,Z,B) A := X+B;\n"
+ "C := X+ Z;\n"
+ "C := C * B;\n"
+ "Z := A+B+C;\n"
+ "WRITE(A,C,Z) END.";*/
//String line = "PROGRAM STATS VAR SUM,SUMSQ,I,VALUE,MEAN,VARIANCEBEGIN SUM:=I+SUMSQ*SUM+I+MEAN*VARIANCE*SUMSQ+I+I*VALUE+I; END.";
// String line = "PROGRAM STATS VAR SUM,SUMSQ,I,VALUE,MEAN,VARIANCEBEGIN SUM:=0; SUMSQ:=0; FORI:=1 TO 100 DO BEGIN READ(VALUE) SUM:=SUM+VALUE; SUMSQ:=SUMSQ+VALUE*VALUE; END FORI:=1 TO 100 DO BEGIN READ(VALUE) SUM:=SUM+VALUE; SUMSQ:=SUMSQ+VALUE*VALUE+SUMSQ+VALUE*VALUE+SUMSQ+VALUE*VALUE; END WRITE(MEAN,VARIANCE) END.";
line = line.replaceAll("\\s", "");
TokenTable.create();
String linecopy = new String(line);
String temp = new String();
String endtoken = new String();
Regex.create();
String Validate = "(PROGRAM)(\\w+)(VAR)(.+)(\\BBEGIN)(.+)(END\\.)";
Pattern r = Pattern.compile(Regex.Validate);
Matcher m = r.matcher(line);
if (m.find()) {
if (m.matches()) {
tokens.add(m.group(1).trim());
tokens.add(m.group(2).trim());
tokens.add(m.group(3).trim());
String Variables = new String();
Variables = m.group(4).trim();
for (int i = 1; i < 4; i++) {
line = line.replaceFirst(m.group(i), "");
}
String[] parts = new String[30];
Variables = Variables.substring(0, line.indexOf("BEGIN"));
//Variables = Variables.replaceFirst("VAR", "");
parts = Variables.split(",");
for (int i = 0; i < parts.length; i++) {
if (!parts[i].isEmpty()) {
if (!parts[i].matches("\\s*")) {
if (!parts[i].matches("[0-9].*")) {
tokens.add(parts[i]);
} else {
System.out.println("Variable can not start with a digit");
return;
}
}
}
}
tokens.add(m.group(5));
endtoken = m.group(7);
line = line.replaceFirst(Variables, "");
line = line.replaceFirst(m.group(5), "");
}
}
while (!line.equalsIgnoreCase("END.")) {
// for (Map.Entry<String, String> entry : Regex.regex.entrySet()) {
if (line.startsWith("WRITE") || line.startsWith("READ")) {
Pattern r2;
if (line.startsWith("WRITE")) {
r2 = Pattern.compile(Regex.WRITE);
} else {
r2 = Pattern.compile(Regex.READ);
}
Matcher m2 = r2.matcher(line);
if (m2.find()) {
tokens.add(m2.group(1).trim());
tokens.add(m2.group(3).trim());
String[] parts = new String[30];
String Variables = new String(m2.group(2));
Variables = Variables.replaceAll("\\(", "");
Variables = Variables.replaceAll("\\)", "");
parts = Variables.split(",");
flag2 = 0;
for (int k = 0; k < parts.length; k++) {
flag2 = find(parts[k]);
if (flag2 == 0) {
System.out.println("Undefined Variable read or write" + parts[k]);
return;
}
}
for (int i = 0; i < parts.length; i++) {
if (!parts[i].isEmpty()) {
if (!parts[i].matches("\\s*")) {
tokens.add(parts[i]);
}
}
}
tokens.add(m2.group(5));
tokens.add(m2.group(6));
for (int i = 1; i < 3; i++) {
line = line.replaceFirst(m2.group(i), "");
}
line = line.replaceFirst("\\(", "");
line = line.replaceFirst("\\)", "");
line = line.replaceFirst(";", "");
}
} else if (line.startsWith("FOR")) {
Pattern r2 = Pattern.compile(Regex.FOR);
Matcher m2 = r2.matcher(line);
if (m2.find()) {
flag2 = 0;
flag2 = find(m2.group(2));
if (flag2 == 0) {
System.out.println("Undefined Variable3" + m2.group(2));
return;
}
for (int i = 1; i < 9; i++) {
tokens.add(m2.group(i));
}
for (int i = 1; i < 9; i++) {
line = line.replaceFirst(m2.group(i), "");
}
}
} else if (line.startsWith("END") && line.length() > 4) {
Pattern r2 = Pattern.compile(Regex.END);
Matcher m2 = r2.matcher(line);
if (m2.find()) {
tokens.add(m2.group(1));
line = line.replaceFirst(m2.group(1), "");
}
} else {
Pattern r2 = Pattern.compile(Regex.ASSIGN);
Matcher m2 = r2.matcher(line);
if (m2.find()) {
flag2 = 0;
flag2 = find(m2.group(1));
if (flag2 == 0) {
System.out.println("Undefined Variable1" + m2.group(1));
return;
}
tokens.add(m2.group(1).trim());
tokens.add(m2.group(2).trim());
for (int i = 1; i < 3; i++) {
line = line.replaceFirst(m2.group(i), "");
}
int i = 0;
while (line.charAt(i) != ';') {
flag2 = 0;
int j = 0;
String temp2 = new String();
temp2 = "";
if (line.charAt(0) == '(')
{temp2 += line.charAt(0);
tokens.add(temp2);
line = line.replaceFirst("\\(", "");}
temp2 = "";
while (line.charAt(j) != '+' && line.charAt(j) != '*' && line.charAt(j) != ';' && line.charAt(j) != '(' && line.charAt(j) != ')') {
temp2 += line.charAt(j);
j++;
}
if(!temp2.isEmpty()) { flag2 = find(temp2);
if (flag2 == 0) {
System.out.println("Undefined Variable2" + temp2);
return;
}
tokens.add(temp2);
line = line.replaceFirst(temp2, ""); }
j = 0;
temp2 = "";
if (line.charAt(0) == '+') {
temp2 += line.charAt(0);
tokens.add(temp2);
line = line.replaceFirst("\\+", "");
} else if (line.charAt(0) == '*') {
temp2 += line.charAt(0);
tokens.add(temp2);
line = line.replaceFirst("\\*", "");
} else if (line.charAt(0) == ')') {
temp2 += line.charAt(0);
tokens.add(temp2);
line = line.replaceFirst("\\)", "");
}
}
tokens.add(m2.group(5));
line = line.replaceFirst(m2.group(5), "");
}
}
}
//}
tokens.add(line);
CG.createLines();
CG.createFile(args[0]);
long end = System.currentTimeMillis();
System.out.println(end - start + "ms");
}
}
| [
"karimfathy@karims-MacBook-Pro.local"
] | karimfathy@karims-MacBook-Pro.local |
533c05f4e8861444c71423c9b597526f691131ec | 16ad4472361eb4737f1da8843cf8f827b9c30257 | /src/main/java/com/itp/ciecyt/domain/EntidadFinanciadora.java | 635d15b6c0388cd4c35f5cce5fea101fcaeb5e08 | [] | no_license | keliumJU/ciecytGrup | f991feade3f64e47c90188d4cda861e0ce0f8337 | 5e1caca834b4e328664b70ac217f0f97d2f8bf96 | refs/heads/master | 2022-12-27T16:53:03.458105 | 2019-07-08T00:32:12 | 2019-07-08T00:32:12 | 195,460,238 | 1 | 1 | null | 2022-12-16T04:52:56 | 2019-07-05T19:48:18 | Java | UTF-8 | Java | false | false | 3,671 | java | package com.itp.ciecyt.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.Objects;
/**
* A EntidadFinanciadora.
*/
@Entity
@Table(name = "entidad_financiadora")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class EntidadFinanciadora implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
@SequenceGenerator(name = "sequenceGenerator")
private Long id;
@Column(name = "valor")
private Double valor;
@Column(name = "estado_financiacion")
private Boolean estadoFinanciacion;
@ManyToOne
@JsonIgnoreProperties("entidadFinanciadoras")
private Proyecto proyecto;
@OneToMany(mappedBy = "entidadFinanciadora")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Empresas> empresas = new HashSet<>();
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Double getValor() {
return valor;
}
public EntidadFinanciadora valor(Double valor) {
this.valor = valor;
return this;
}
public void setValor(Double valor) {
this.valor = valor;
}
public Boolean isEstadoFinanciacion() {
return estadoFinanciacion;
}
public EntidadFinanciadora estadoFinanciacion(Boolean estadoFinanciacion) {
this.estadoFinanciacion = estadoFinanciacion;
return this;
}
public void setEstadoFinanciacion(Boolean estadoFinanciacion) {
this.estadoFinanciacion = estadoFinanciacion;
}
public Proyecto getProyecto() {
return proyecto;
}
public EntidadFinanciadora proyecto(Proyecto proyecto) {
this.proyecto = proyecto;
return this;
}
public void setProyecto(Proyecto proyecto) {
this.proyecto = proyecto;
}
public Set<Empresas> getEmpresas() {
return empresas;
}
public EntidadFinanciadora empresas(Set<Empresas> empresas) {
this.empresas = empresas;
return this;
}
public EntidadFinanciadora addEmpresas(Empresas empresas) {
this.empresas.add(empresas);
empresas.setEntidadFinanciadora(this);
return this;
}
public EntidadFinanciadora removeEmpresas(Empresas empresas) {
this.empresas.remove(empresas);
empresas.setEntidadFinanciadora(null);
return this;
}
public void setEmpresas(Set<Empresas> empresas) {
this.empresas = empresas;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof EntidadFinanciadora)) {
return false;
}
return id != null && id.equals(((EntidadFinanciadora) o).id);
}
@Override
public int hashCode() {
return 31;
}
@Override
public String toString() {
return "EntidadFinanciadora{" +
"id=" + getId() +
", valor=" + getValor() +
", estadoFinanciacion='" + isEstadoFinanciacion() + "'" +
"}";
}
}
| [
"aizquierdo@itp.edu.co"
] | aizquierdo@itp.edu.co |
95edad74a8f8799b1e0c6c23bf6b1bad2de7bf73 | c347a05e9b83924f38f8b86ca921838a6acd8a8f | /Athlete/src/com/athlete/activity/setup/ActivityLocation.java | b2ec4e804358110d1e5c8937d67cd5cf6041520e | [] | no_license | developer-triffort/Athlete | 1a0bab6114c4152f314b3fe30cb849abdb5dc02b | 911a1d5a5f7a4d04df65773dc4d7f695e1dd97f9 | refs/heads/master | 2020-12-24T15:31:30.834375 | 2014-02-25T05:44:02 | 2014-02-25T05:44:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,613 | java | package com.athlete.activity.setup;
import java.util.List;
import java.util.Locale;
import org.json.JSONObject;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.athlete.R;
import com.athlete.model.ProfileUser;
import com.athlete.model.User;
import com.athlete.util.AnalyticsUtils;
public class ActivityLocation extends BaseSetupActivity implements
LocationListener {
private double latitude, longitude;
private LocationManager mLocManager;
private String location = "";
private TextView txtDetectLocation;
private Dialog mDialog;
private EditText edTxtCustomLocation;
private final String LOCATION_NAME = "location_name";
private final String sharedKeyIsDetect = "isDetectShared";
private boolean isDetect;
@Override
protected void onResume() {
super.onResume();
AnalyticsUtils.sendPageViews(ActivityLocation.this,
AnalyticsUtils.GOOGLE_ANALYTICS.SCREEN.SELECT_LOCATION);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actv_setup_location);
isDetect = getShared().getBoolean(sharedKeyIsDetect, false);
txtDetectLocation = (TextView) findViewById(R.id.txtDetectLocation);
edTxtCustomLocation = (EditText) findViewById(R.id.edTextCustom);
edTxtCustomLocation.setImeOptions(EditorInfo.IME_ACTION_DONE);
location = profileUser.getLocationName();
if (location == null) {
location = "";
}
setText();
findViewById(R.id.layoutDetectLocation).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
AnalyticsUtils.sendPageViews(ActivityLocation.this,
AnalyticsUtils.GOOGLE_ANALYTICS.SCREEN.SELECT_LOCATION,
AnalyticsUtils.GOOGLE_ANALYTICS.CATEGORY,
AnalyticsUtils.GOOGLE_ANALYTICS.ACTION,
"detect", 0);
hideKeyboard(ActivityLocation.this);
createProgressDialog();
isDetect = true;
getShared().edit()
.putBoolean(sharedKeyIsDetect, isDetect)
.commit();
setText();
mLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0,
ActivityLocation.this);
mLocManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
ActivityLocation.this);
}
});
edTxtCustomLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isDetect) {
isDetect = false;
getShared().edit().putBoolean(sharedKeyIsDetect, isDetect)
.commit();
setText();
}
}
});
findViewById(R.id.btnBack).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
edTxtCustomLocation
.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
hideKeyboard(ActivityLocation.this);
if (!location.equalsIgnoreCase(edTxtCustomLocation
.getText().toString())) {
AnalyticsUtils
.sendPageViews(
ActivityLocation.this,
AnalyticsUtils.GOOGLE_ANALYTICS.SCREEN.SELECT_LOCATION,
AnalyticsUtils.GOOGLE_ANALYTICS.CATEGORY,
AnalyticsUtils.GOOGLE_ANALYTICS.ACTION,
"custom", 0);
createProgressDialog();
location = edTxtCustomLocation.getText()
.toString();
isDetect = false;
getShared()
.edit()
.putBoolean(sharedKeyIsDetect, isDetect)
.commit();
setText();
try {
updateLocation();
} catch (Exception e) {
}
hideProgress();
}
return true;
}
return false;
}
});
}
@Override
public void onBackPressed() {
super.onBackPressed();
hideKeyboard(ActivityLocation.this);
}
private void setText() {
if (isDetect) {
txtDetectLocation.setText(location);
edTxtCustomLocation.setText("");
} else {
edTxtCustomLocation.setText(location);
txtDetectLocation.setText("");
}
}
public void getAddress(double lat, double lng) {
Geocoder geocoder = new Geocoder(ActivityLocation.this,
Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Address obj = addresses.get(0);
location = obj.getLocality() + ", " + obj.getAdminArea();
isDetect = true;
getShared().edit().putBoolean(sharedKeyIsDetect, true).commit();
setText();
updateLocation();
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
hideProgress();
}
private void updateLocation() throws Exception {
jsonObjSend = new JSONObject();
jsonObjSend.put(LOCATION_NAME, location);
profileUser.setLocationName(location);
baseBl.createOrUpdate(ProfileUser.class, profileUser);
currentUser.setProfileUser(profileUser);
baseBl.createOrUpdate(User.class, currentUser);
updateUser(null);
}
private void hideProgress() {
if (mDialog != null) {
mDialog.dismiss();
mDialog = null;
}
}
private void createProgressDialog() {
if (mDialog == null) {
mDialog = new ProgressDialog(ActivityLocation.this);
((ProgressDialog) mDialog).setMessage(getString(R.string.updating));
mDialog.show();
}
}
@Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
getAddress(latitude, longitude);
if (location != null) {
mLocManager.removeUpdates(this);
}
}
@Override
public void onProviderDisabled(String arg0) {
Toast.makeText(ActivityLocation.this, "Gps Disabled",
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
@Override
public void onProviderEnabled(String arg0) {
}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
}
| [
"ali.ahmad@triffort.com"
] | ali.ahmad@triffort.com |
48fdbeaf9ee545602ebc7520d8e945d86b268e10 | abb3b48a568d2a33eb05133973bc42da268f8021 | /code/src/main/java/com/yuntu/sale/ifconf/vo/ThirdOrderNumVo.java | b5a544ec0b52ca1cdd06a2365aa447172381b62a | [] | no_license | barry2018118/ytsale201910 | 552271e31eede6fdc51cc4b2f48a2a67f6328709 | 4331054d538056b8d6b00c8c2a9b2bb01ff5c2a6 | refs/heads/master | 2022-12-22T13:58:28.684484 | 2019-10-07T04:08:53 | 2019-10-07T04:08:53 | 213,284,410 | 0 | 0 | null | 2022-12-16T03:32:11 | 2019-10-07T03:05:41 | TSQL | UTF-8 | Java | false | false | 1,116 | java | package com.yuntu.sale.ifconf.vo;
public class ThirdOrderNumVo {
/** 供应商订单号 **/
private String thirdno;
/** 系统订单号 **/
private String orderno;
/** 总数 **/
private Integer num=0;
/** 已使用数 **/
private Integer printnum=0;
/** 已退款数 **/
private Integer locknum=0;
/** 可使用数 **/
private Integer validnum=0;
public String getThirdno() {
return thirdno;
}
public void setThirdno(String thirdno) {
this.thirdno = thirdno;
}
public String getOrderno() {
return orderno;
}
public void setOrderno(String orderno) {
this.orderno = orderno;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
public Integer getPrintnum() {
return printnum;
}
public void setPrintnum(Integer printnum) {
this.printnum = printnum;
}
public Integer getLocknum() {
return locknum;
}
public void setLocknum(Integer locknum) {
this.locknum = locknum;
}
public Integer getValidnum() {
return validnum;
}
public void setValidnum(Integer validnum) {
this.validnum = validnum;
}
}
| [
"luckykapok918@163.com"
] | luckykapok918@163.com |
787fdf73d9c94f8dec812726eb6c32e65ddb9103 | 88ed30ae68858ad6365357d4b0a95ad07594c430 | /agent/arcus-zw-controller/src/main/java/com/iris/agent/zw/events/ZWEvent.java | 15807dc701377494cdb37ce2763d54b1c6c7b2b4 | [
"Apache-2.0"
] | permissive | Diffblue-benchmarks/arcusplatform | 686f58654d2cdf3ca3c25bc475bf8f04db0c4eb3 | b95cb4886b99548a6c67702e8ba770317df63fe2 | refs/heads/master | 2020-05-23T15:41:39.298441 | 2019-05-01T03:56:47 | 2019-05-01T03:56:47 | 186,830,996 | 0 | 0 | Apache-2.0 | 2019-05-30T11:13:52 | 2019-05-15T13:22:26 | Java | UTF-8 | Java | false | false | 1,165 | java | /*
* Copyright 2019 Arcus 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.iris.agent.zw.events;
/**
* Interface for events internal to the ZWave subsystem
*
* @author Erik Larson
*/
public interface ZWEvent {
public enum ZWEventType {
BOOTSTRAPPED,
START_PAIRING,
STOP_PAIRING,
START_UNPAIRING,
STOP_UNPAIRING,
NODE_ADDED,
NODE_REMOVED,
NODE_DISCOVERED,
NODE_ID,
NODE_MAPPED,
NODE_COMMAND,
HOME_ID_CHANGED,
PROTOCOL_VERSION,
OFFLINE_TIMEOUT,
HEARD_FROM,
GONE_OFFLINE,
GONE_ONLINE
}
ZWEventType getType();
}
| [
"b@yoyo.com"
] | b@yoyo.com |
82eda0272a249f5aa6ea155c79cce46c79326e07 | 1fdd768b197367a330add8b22ffc864a40191a0e | /SwapTest.java | 75d9092839ab7c9939df5debf9187660914bdfa8 | [] | no_license | alimz758/Java-MultiThreading | 02463c5be19eb2ddb0ca5e487626ee59a822ce79 | 40428cd773e15912086800240916a9127877920c | refs/heads/master | 2021-02-21T17:14:02.070333 | 2020-03-06T08:05:59 | 2020-03-06T08:05:59 | 245,362,085 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 965 | java | import java.util.concurrent.ThreadLocalRandom;
import java.lang.management.ThreadMXBean;
// The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.
// The class must define a method of no arguments called run.
class SwapTest implements Runnable {
private long nTransitions;
private State state;
private ThreadMXBean bean;
private long cputime;
SwapTest(long n, State s, ThreadMXBean b) {
nTransitions = n;
state = s;
bean = b;
}
//Runnable statw with Run
public void run() {
var n = state.size();
if (n <= 1)
return;
var rng = ThreadLocalRandom.current();
var id = Thread.currentThread().getId();
var start = bean.getThreadCpuTime(id);
for (var i = nTransitions; 0 < i; i--)
state.swap(rng.nextInt(0, n), rng.nextInt(0, n));
var end = bean.getThreadCpuTime(id);
cputime = end - start;
}
public long cpuTime() {
return cputime;
}
}
| [
"ali.mz758@gmail.com"
] | ali.mz758@gmail.com |
64d5e50f212d26f2fa4bbef37098f7ab07c0b938 | 44500af2e2f63ad4c556e27dcf80914f3a0751f1 | /mall-mbg/src/main/java/com/chunhai/mall/model/SmsFlashPromotionLog.java | 5bcfa94412aedd977e13bb5eb40453163b8a06f2 | [] | no_license | zhouhai22/mall-zch | 50fe7e85ab6e660703576242b0fc8d1aaacf9e40 | 4a83c5a1796c8b45f7f0ac7c14f424ddc1ff9c35 | refs/heads/master | 2023-03-26T06:58:22.173549 | 2021-03-19T02:23:44 | 2021-03-19T02:23:44 | 344,707,497 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,329 | java | package com.chunhai.mall.model;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Date;
public class SmsFlashPromotionLog implements Serializable {
private Integer id;
private Integer memberId;
private Long productId;
private String memberPhone;
private String productName;
@ApiModelProperty(value = "会员订阅时间")
private Date subscribeTime;
private Date sendTime;
private static final long serialVersionUID = 1L;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getMemberId() {
return memberId;
}
public void setMemberId(Integer memberId) {
this.memberId = memberId;
}
public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
public String getMemberPhone() {
return memberPhone;
}
public void setMemberPhone(String memberPhone) {
this.memberPhone = memberPhone;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Date getSubscribeTime() {
return subscribeTime;
}
public void setSubscribeTime(Date subscribeTime) {
this.subscribeTime = subscribeTime;
}
public Date getSendTime() {
return sendTime;
}
public void setSendTime(Date sendTime) {
this.sendTime = sendTime;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", memberId=").append(memberId);
sb.append(", productId=").append(productId);
sb.append(", memberPhone=").append(memberPhone);
sb.append(", productName=").append(productName);
sb.append(", subscribeTime=").append(subscribeTime);
sb.append(", sendTime=").append(sendTime);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | [
"zhouchunhai@cmss.chinamobile.com"
] | zhouchunhai@cmss.chinamobile.com |
843923aefec1cfca7c2b90388db5eed33f726641 | 07fed9ebe0a8f42ea14540d4a6877315902252b9 | /src/test/java/ch/hearc/jpa/TestUtil.java | 513f355ee04db5d7f89487b44e657844a30ff921 | [] | no_license | Cours-HE-ARC/jpa | 392e2fc52f758afcac051b82935327b98dc2845c | 9f4d00b5d8c0b954d2fd0a6f059569735f2656ca | refs/heads/master | 2020-04-17T03:35:51.444167 | 2019-01-22T11:56:41 | 2019-01-22T11:56:41 | 166,191,068 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,023 | java | package ch.hearc.jpa;
import java.util.Random;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.github.javafaker.Faker;
import ch.hearc.jpa.entite.Adresse;
import ch.hearc.jpa.entite.Personne;
import ch.hearc.jpa.entite.Sexe;
@Component
public class TestUtil {
@Autowired
Faker faker;
public Personne generatePersonneWithAdresse() {
Personne p = generatePersonne();
p.setAdresse(generateAdresse());
return p;
}
public Personne generatePersonne() {
String prenom = faker.name().lastName();
String nom = faker.name().firstName();
int rsexe = new Random().nextInt(2);
Sexe sexe = (rsexe == 0)?Sexe.MASCULIN:Sexe.FEMININ;
Personne p = new Personne(nom,prenom,sexe);
return p;
}
public Adresse generateAdresse() {
String rue = faker.address().streetName();
Integer no = Integer.parseInt(faker.address().buildingNumber());
Adresse adresse = new Adresse(rue,no);
return adresse;
}
}
| [
"seb.chevre@gmail.com"
] | seb.chevre@gmail.com |
6ecff6539299dbafab72ecfd0d81898795a99a58 | 5072a7cc99ad9b6fad795369ab84be63233810f2 | /ssm/CRM/src/com/neuedu/crm/view/CustomerController.java | 25a79073e6ddfaf3d6d6e56b571ae8440064b46f | [] | no_license | gitHubChenjm/mygit | 5c0e06af490150ba5a96a6f1317820fb09e5ad56 | 5dbf7d530457061d895e972822e15e94216c47a1 | refs/heads/master | 2020-03-31T11:15:43.388983 | 2018-10-09T01:57:59 | 2018-10-09T01:57:59 | 152,169,518 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 37,693 | java | /**
* Copyright 2018 shuzai.crm.com, Inc. All rights reserved.
*/
package com.neuedu.crm.view;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* <p>Date : 2018/07/19</p>
* <p>Title: 控制器</p>
* <p>Description: 客户信息管理模块(增删查改),联系人子模块(增删查改)
* 交往记录子模块(增删查改), 历史订单子模块(查),订单详细子模块(查)
* 客户流失管理模块(查,改)
* </p>
* <p>Copyright: Copyright (c) 2018</p>
* @author WYY
* @version 1.0
*/
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.google.gson.Gson;
import com.neuedu.crm.bean.Communicate;
import com.neuedu.crm.bean.Contacts;
import com.neuedu.crm.bean.Customer;
import com.neuedu.crm.bean.Loss;
import com.neuedu.crm.bean.Orderitem;
import com.neuedu.crm.bean.Orders;
import com.neuedu.crm.bean.Pager;
import com.neuedu.crm.bean.User;
import com.neuedu.crm.bean.WordBook;
import com.neuedu.crm.service.ICommunicateService;
import com.neuedu.crm.service.IContactsService;
import com.neuedu.crm.service.ICustomerService;
import com.neuedu.crm.service.ILossService;
import com.neuedu.crm.service.IOrderitemService;
import com.neuedu.crm.service.IOrdersService;
import com.neuedu.crm.service.IUserService;
import com.neuedu.crm.service.IWordBookService;
import com.neuedu.crm.utils.LeadingInExcel;
@Controller
@RequestMapping("/customers")
public class CustomerController {
//日志器
private Logger logger = Logger.getRootLogger();
@Autowired
private ICustomerService customerService;
@Autowired
private IUserService userService;
@Autowired
private IWordBookService wordservice;
@Autowired
private IContactsService contactsService;
@Autowired
private ICommunicateService communicateService;
@Autowired
private IOrdersService ordersService;
@Autowired
private IOrderitemService orderitemService;
@Autowired
private ILossService lossService;
//1、客户模块
/**
* 没有分页功能的查询所有客户
* @param model 视图
* @return 目标jsp页面
*/
@RequestMapping("/list")
public String listCustomer(Model model) {
List<Customer> list = customerService.findAll();
List<User> users = userService.findAll(); // 客户经理
List<WordBook> custcategoryIds = wordservice.findWordBookByCategory(4); //客户分类
List<WordBook> creditIds = wordservice.findWordBookByCategory(2); // 信用度
List<WordBook> custfromIds = wordservice.findWordBookByCategory(3); //客户来源
List<WordBook> satisfiedIds = wordservice.findWordBookByCategory(1); //满意度
//将视图传到jsp页面,类似于以前的request.setAttribute()
model.addAttribute("list", list);
model.addAttribute("users", users);
model.addAttribute("custcategorys", custcategoryIds);
model.addAttribute("credits", creditIds);
model.addAttribute("custfroms", custfromIds);
model.addAttribute("satisfieds", satisfiedIds);
for (Customer customer : list) {
logger.info(customer.toString());
}
return "customer/listCustomer"; //返回目标页面
}
/**
* 执行插入数据之前,先去查出所有需要到页面提供显示的信息
* @return view
*/
@RequestMapping("/add")
public ModelAndView addCustomer() {
// 查询客户经理,客户来源,信用度,满意度,客户等级等信息,并传递到页面显示
List<User> users = userService.findAll();
List<WordBook> custcategoryIds = wordservice.findWordBookByCategory(4);
List<WordBook> creditIds = wordservice.findWordBookByCategory(2);
List<WordBook> custfromIds = wordservice.findWordBookByCategory(3);
List<WordBook> satisfiedIds = wordservice.findWordBookByCategory(1);
ModelAndView view = new ModelAndView("customer/addCustomer");
view.getModel().put("users", users);
view.getModel().put("custcategorys", custcategoryIds);
view.getModel().put("credits", creditIds);
view.getModel().put("custfroms", custfromIds);
view.getModel().put("satisfieds", satisfiedIds);
return view;
}
/**
* 执行插入客户
* @param customer 对象里面封装好了页面传回来的数据
* @return {'code':'0'}(成功) 或 {'code':'1'}(失败) 这是json数据的写法
*/
@RequestMapping(value="/doadd",produces = "text/plain;charset=utf-8")
@ResponseBody // 用ResponseBody来自身返回json数据与传输
public String doAddCustomer(Customer customer) {
int ret = customerService.addCustomer(customer);
if (ret != 0){
return "{'code':'0'}"; //从页面来的customer的对象数据,返回封装好的json数据给自身页面
}
else {
return "{'code':'1'}"; //哪个页面在js里通过ajax调用了这个action,就将数据返回给哪个页面的ajax里面
}
}
/**
* 更改客户前的查询,客户经理,客户等级,信用度,满意度,客户来源等信息再传到目标页面
* @param customerId 通过id找出这个客户的所有信息
* @return view
*/
@RequestMapping("/edit")
public ModelAndView toEditCustomer(Integer customerId) {
ModelAndView view = new ModelAndView("customer/updateCustomer");
Customer customer = customerService.findById(customerId);
System.out.println(customer.toString());
List<User> users = userService.findAll();
List<WordBook> custcategoryIds = wordservice.findWordBookByCategory(4);
List<WordBook> creditIds = wordservice.findWordBookByCategory(2);
List<WordBook> custfromIds = wordservice.findWordBookByCategory(3);
List<WordBook> satisfiedIds = wordservice.findWordBookByCategory(1);
view.getModel().put("customer", customer);
view.getModel().put("users", users);
view.getModel().put("custcategorys", custcategoryIds);
view.getModel().put("credits", creditIds);
view.getModel().put("custfroms", custfromIds);
view.getModel().put("satisfieds", satisfiedIds);
return view;
}
/**
* 执行更新客户操作
* @param customer
* @param request
* @return {'code':'0'}(成功) 或 {'code':'1'}(失败)
*/
@RequestMapping(value="/doedit",produces = "text/plain;charset=utf-8")
@ResponseBody
public String doEditCustomer(Customer customer,HttpServletRequest request) {
int ret = customerService.editCustomer(customer);
if (ret != 0) {
// 更新成功
return "{'code':'0'}";
} else {
// 更新失败
return "{'code':'1'}";
}
}
/**
* 执行删除客户操作
* @param customerId
* @param request
* @return {'msg':'1'}(成功) 或 {'msg':'0'}(失败)
*/
@RequestMapping(value="/del",produces = "text/plain;charset=utf-8")
@ResponseBody
public String doDelCustomer(Integer customerId,HttpServletRequest request) {
int ret = customerService.deleteById(customerId);
if (ret != 0) {
// 删除成功
return "{'msg':'1'}";
} else {
// 删除失败
return "{'msg':'0'}";
}
}
/**
* 客户模糊查询前的查出需要的信息,封装成json数据传回jsp页面进行追加下拉框
* @return json数据(users,custcategoryIds,creditIds,custfromIds,satisfiedIds)
*/
@RequestMapping(value="/listSelection",produces = "text/plain;charset=utf-8")
@ResponseBody
public String findSelection() {
List<User> users = userService.findAll();
List<WordBook> custcategoryIds = wordservice.findWordBookByCategory(4);
List<WordBook> creditIds = wordservice.findWordBookByCategory(2);
List<WordBook> custfromIds = wordservice.findWordBookByCategory(3);
List<WordBook> satisfiedIds = wordservice.findWordBookByCategory(1);
Map<String, Object> map = new HashMap<>();
map.put("users", users);
map.put("custcategoryIds", custcategoryIds);
map.put("creditIds", creditIds);
map.put("custfromIds", custfromIds);
map.put("satisfiedIds", satisfiedIds);
return new Gson().toJson(map);
}
/**
* 分页模糊查询——客户
* @param customer 里面封装好了jsp页面ajax传回来的数据
* @param pageNo 页数
* @param pageSize 页码
* @return json数据 (list(customers),pager)
*/
@RequestMapping(value="/listCustomer",produces = "text/plain;charset=utf-8")
@ResponseBody
public String findByPager(Customer customer,Integer pageNo,Integer pageSize) {
//System.out.println(customer.toString());
//System.out.println("----------------------------"+pageNo + pageSize);
if(pageNo == null) {
pageNo = 1; //默认设置第一次的页数为1,因为页数不能为0或从0开始
}
if(pageSize == null) {
pageSize = 10; //设置每一页的记录条数
}
Pager<Customer> pager = new Pager<>(pageNo, pageSize);
//如果jsp页面某属性的值为-1,就要设空,这样这些属性就不会作为条件去到sql里面,而添加此属性的条件
if (customer.getName() == null) {
customer.setName(null);
}
if (customer.getUser().getId() == -1) {
customer.setUser(null);
}
if (customer.getCreditId().getId() == -1) {
customer.setCreditId(null);
}
if (customer.getSatisfiedId().getId() == -1) {
customer.setSatisfiedId(null);
}
if (customer.getCustcategoryId().getId() == -1) {
customer.setCustcategoryId(null);
}
if (customer.getCustfromId().getId() == -1) {
customer.setCustfromId(null);
}
pager.setParam(customer); //设置分页查询的条件
Integer total = customerService.countForPager(pager); //查询总页数
pager.setTotal(total);
List<Customer> customers = customerService.findByPager(pager); //执行分页模糊查询方法
//model.addAttribute("pager", pager);
Map<String, Object> map = new HashMap<>();
map.put("list", customers);
map.put("pager", pager); //将分页模糊查询出来的结果用map封装好,然后Gson.toJson方法json化数据并传回到页面
return new Gson().toJson(map);
}
/**
* 批量删除客户
* @param request
* @param delIds 多个id的数组
* @return {'msg':'1'}(成功) {'msg':'1'}(失败)
*/
@RequestMapping("/delMoreCustomer")
@ResponseBody
public String delIds(HttpServletRequest request,Integer[] delIds) {
int ret = customerService.deleteByCustomerIdList(delIds);
if (ret != 0) {
// 删除成功
return "{'msg':'1'}";
} else {
// 删除失败
return "{'msg':'0'}";
}
}
//2、联系人子模块
/**
* 插入联系人前的查询信息,传到页面进行显示
* @param customerId 通过customerId查询某个客户的联系人,并且将此客户的customerId传到页面
* @return view
*/
@RequestMapping("/addContacts")
public ModelAndView addContacts(Integer customerId) {
ModelAndView view = new ModelAndView("customer/addContacts");
List<Contacts> list = contactsService.findAll();
view.getModel().put("list", list);
view.getModel().put("customerId", customerId);
return view;
}
/**
* 执行插入某个客户的联系人操作
* @param contacts 里面封装好了联系人的属性,然后执行addContacts方法进行插入
* @return {'code':'0'}(成功) 或 {'code':'1'}(失败)
*/
@RequestMapping(value="/doaddContacts",produces = "text/plain;charset=utf-8")
@ResponseBody
public String doAddContacts(Contacts contacts) {
int ret = contactsService.addContacts(contacts);
if (ret != 0){
return "{'code':'0'}";
}
else {
return "{'code':'1'}";
}
}
/**
* 执行更新某个客户联系人前的查询
* @param contactsId 通过contactsId查询这条记录的信息,并传到目标jsp页面
* @return view(list contacts)
*/
@RequestMapping("/editContacts")
public ModelAndView toEditContacts(Integer contactsId) {
ModelAndView view = new ModelAndView("customer/updateContacts");
Contacts contacts = contactsService.findById(contactsId);
List<Contacts> list = contactsService.findAll();
view.getModel().put("list", list);
view.getModel().put("contacts", contacts);
return view;
}
/**
* 执行更新某个客户联系人的操作
* @param contacts 里面封装好了联系人需要更改的属性信息
* @param request
* @return {'code':'0'}(成功) 或 {'code':'1'}(失败)
*/
@RequestMapping(value="/doeditContacts",produces = "text/plain;charset=utf-8")
@ResponseBody
public String doEditContacts(Contacts contacts,HttpServletRequest request) {
int ret = contactsService.editContacts(contacts);
if (ret != 0) {
// 更新成功
return "{'code':'0'}";
} else {
// 更新失败
return "{'code':'1'}";
}
}
/**
* 执行删除客户联系人操作
* @param contactsId
* @param request
* @return {'msg':'1'}(成功) 或 {'msg':'0'}(失败)
*/
@RequestMapping(value="/delContacts",produces = "text/plain;charset=utf-8")
@ResponseBody
public String doDelContacts(Integer contactsId,HttpServletRequest request) {
int ret = contactsService.deleteById(contactsId);
if (ret != 0) {
// 删除成功
return "{'msg':'1'}";
} else {
// 删除失败
return "{'msg':'0'}";
}
}
/**
* 联系人分页模糊查询前的下拉框填充查询
* return json数据(contacts)
*/
@RequestMapping(value="/listContactsJob",produces = "text/plain;charset=utf-8")
@ResponseBody
public String findContactsJob() {
List<Contacts> contacts = contactsService.findAll();
Map<String, Object> map = new HashMap<>();
map.put("contacts", contacts);
return new Gson().toJson(map);
}
/**
* 联系人分页模糊查询前的查询,传到目标jsp页面进行显示
* @param contacts
* @return view(contactss)
*/
@RequestMapping(value="/toListContacts",produces = "text/plain;charset=utf-8")
public ModelAndView toFindByContactsPager(Contacts contacts){
ModelAndView view = new ModelAndView("customer/contactsList");
Customer customer = customerService.findById(contacts.getCustomer().getCustomerId());
contacts.setCustomer(customer);
view.getModel().put("contactss", contacts);
return view;
}
/**
* 执行联系人分页模糊查询操作
* @param contacts 里面封装好了要分页模糊查询的数据
* @param pageNo 当前页数
* @param pageSize 页码
* @return json数据(list(contactss),pager)
*/
@RequestMapping(value="/listContacts",produces = "text/plain;charset=utf-8")
@ResponseBody
public String findByContactsPager(Contacts contacts,Integer pageNo,Integer pageSize) {
//System.out.println(contacts.toString());
if(pageNo == null) {
pageNo = 1;
}
if(pageSize == null) {
pageSize = 10;
}
Pager<Contacts> pager = new Pager<>(pageNo, pageSize);
if (contacts.getName() == null) {
contacts.setName("");
}
if (contacts.getGender().equals("-1")) {
contacts.setGender(null);
}
if (contacts.getJob().equals("-1")) {
contacts.setJob(null);
}
if(contacts.getRemark().equals("null")){
contacts.setRemark(null);
}
pager.setParam(contacts);
Integer total = contactsService.countForPager(pager);
pager.setTotal(total);
List<Contacts> contactss = contactsService.findByPager(pager);
Map<String, Object> map = new HashMap<>();
map.put("list", contactss);
map.put("pager", pager);
return new Gson().toJson(map);
}
/**
* 批量删除联系人
* @param request
* @param delIds 多个id的数组
* @return {'msg':'1'}(成功) {'msg':'1'}(失败)
*/
@RequestMapping("/delMoreContacts")
@ResponseBody
public String delContactsIds(HttpServletRequest request,Integer[] delIds) {
int ret = contactsService.deleteByContactsList(delIds);
if (ret != 0) {
// 删除成功
return "{'msg':'1'}";
} else {
// 删除失败
return "{'msg':'0'}";
}
}
//3、交往记录子模块
/**
* 插入交往记录前的查询
* @param customerId 传回到页面作为参数的必需
* @return view(list(communcates),customerId)
*/
@RequestMapping("/addCommunicate")
public ModelAndView addCommunicate(Integer customerId) {
ModelAndView view = new ModelAndView("customer/addCommunicate");
List<Communicate> list = communicateService.findAll();
view.getModel().put("list", list);
view.getModel().put("customerId", customerId);
return view;
}
/**
* 执行插入联系人操作
* @param communicate 里面封装好了要插入的联系人的数据
* @return {'code':'0'}(成功) 或 {'code':'1'}(失败)
*/
@RequestMapping(value="/doaddCommunicate",produces = "text/plain;charset=utf-8")
@ResponseBody
public String doAddCommunicate(HttpServletRequest request,Communicate communicate,@RequestParam("file1") MultipartFile file1) throws IllegalStateException, IOException {
if(!file1.isEmpty()) {
//上传文件路径
String path = request.getServletContext().getRealPath("/pages/customer/upload/");
//上传文件名
String filename = file1.getOriginalFilename();
//String fileExt = filename.substring(filename.lastIndexOf("."));
//String uuid = UUID.randomUUID().toString();//随机UUID文件名
//String newFile = uuid+fileExt;
String newFile = filename;
File filepath = new File(path,newFile);
logger.info(newFile);
logger.info(filepath.getAbsolutePath());
//判断路径是否存在,如果不存在就创建一个
if (!filepath.getParentFile().exists()) {
filepath.getParentFile().mkdirs();
}
//将上传文件保存到一个目标文件当中
file1.transferTo(new File(path + File.separator + newFile));
//上传成功,保存上传后的文件路径到communicate对象中,再调用业务类保存都数据库中
communicate.setFile("pages/customer/upload/"+newFile);
}
int ret = communicateService.addCommunicate(communicate);
if (ret != 0){
//插入成功
return "{'code':'0'}";
}
else {
//插入失败
return "{'code':'1'}";
}
}
/**
* 更新某个客户的交往记录前的查询
* @param communicateId 通过communicateId查询这条交往记录的信息
* @return view(list(communicates),communicate)
*/
@RequestMapping("/editCommunicate")
public ModelAndView toEditCommunicate(Integer communicateId) {
ModelAndView view = new ModelAndView("customer/updateCommunicate");
Communicate communicate = communicateService.findById(communicateId);
List<Communicate> list = communicateService.findAll();
view.getModel().put("list", list);
view.getModel().put("communicate", communicate);
return view;
}
/**
* 执行更新某个客户交往记录操作
* @param communicate 里面封装装好了需要更改的交往记录的信息
* @param request
* @return {'code':'0'}(成功) 或 {'code':'1'}(失败)
*/
@RequestMapping(value="/doeditCommunicate",produces = "text/plain;charset=utf-8")
@ResponseBody
public String doEditCommunicate(Communicate communicate,HttpServletRequest request,@RequestParam("file1") MultipartFile file1) throws IllegalStateException, IOException {
if(!file1.isEmpty()) {
//上传文件路径
String path = request.getServletContext().getRealPath("/pages/customer/upload/");
//上传文件名
String filename = file1.getOriginalFilename();
String newFile = filename;
File filepath = new File(path,newFile);
logger.info(newFile);
logger.info(filepath.getAbsolutePath());
//判断路径是否存在,如果不存在就创建一个
if (!filepath.getParentFile().exists()) {
filepath.getParentFile().mkdirs();
}
//将上传文件保存到一个目标文件当中
file1.transferTo(new File(path + File.separator + newFile));
//上传成功,保存上传后的文件路径到communicate对象中,再调用业务类保存都数据库中
communicate.setFile("pages/customer/upload/"+newFile);
}
int ret = communicateService.editCommunicate(communicate);
if (ret != 0) {
// 更新成功
return "{'code':'0'}";
} else {
// 更新失败
return "{'code':'1'}";
}
}
/**
* 执行删除某个客户的交往记录操作
* @param communicateId
* @param request
* @return {'msg':'1'}(成功) 或 {'msg':'0'}(失败)
*/
@RequestMapping(value="/delCommunicate",produces = "text/plain;charset=utf-8")
@ResponseBody
public String doDelCommunicate(Integer communicateId,HttpServletRequest request) {
int ret = communicateService.deleteById(communicateId);
if (ret != 0) {
// 删除成功
return "{'msg':'1'}";
} else {
// 删除失败
return "{'msg':'0'}";
}
}
/**
* 查询交流日期并返回页面进行信息显示
* @return json数据(communicates)
*/
@RequestMapping(value="/listCommunicateDate",produces = "text/plain;charset=utf-8")
@ResponseBody
public String findCommunicateDate() {
List<Communicate> communicates = communicateService.findAll();
Map<String, Object> map = new HashMap<>();
map.put("communicates", communicates);
return new Gson().toJson(map);
}
/**
* 交往记录分页模糊查询前的查询
* @param communicate
* @return view(communicates)
*/
@RequestMapping(value="/tolistCommunicate",produces = "text/plain;charset=utf-8")
public ModelAndView toFindByCommunicate(Communicate communicate){
ModelAndView view = new ModelAndView("customer/communicateList");
Customer customer = customerService.findById(communicate.getCustomer().getCustomerId());
communicate.setCustomer(customer);
view.getModel().put("communicates", communicate);
return view;
}
/**
* 交往记录分页模糊查询
* @param communicate
* @param pageNo 当前页数
* @param pageSize 页码
* @return json数据(list(communicates),pager)
*/
@RequestMapping(value="/listCommunicate",produces = "text/plain;charset=utf-8")
@ResponseBody
public String findByCommunicate(Communicate communicate,Integer pageNo,Integer pageSize) {
System.out.println(communicate.toString());
if(pageNo == null) {
pageNo = 1;
}
if(pageSize == null) {
pageSize = 10;
}
if(communicate.getDetail() == null) {
communicate.setDetail("");
}
if (communicate.getRemark() == null) {
communicate.setRemark("");
}
Pager<Communicate> pager = new Pager<>(pageNo, pageSize);
pager.setParam(communicate);
Integer total = communicateService.countForPager(pager);
pager.setTotal(total);
List<Communicate> communicates = communicateService.findByPager(pager);
Map<String, Object> map = new HashMap<>();
map.put("list", communicates);
map.put("pager", pager);
return new Gson().toJson(map);
}
/**
* 批量删除交往记录
* @param request
* @param delIds 多个id的数组
* @return {'msg':'1'}(成功) {'msg':'1'}(失败)
*/
@RequestMapping("/delMoreCommunicate")
@ResponseBody
public String delCommunicateIds(HttpServletRequest request,Integer[] delIds) {
int ret = communicateService.deleteByCommunicateList(delIds);
if (ret != 0) {
// 删除成功
return "{'msg':'1'}";
} else {
// 删除失败
return "{'msg':'0'}";
}
}
/**
* 文件下载模块
* @param fileName 传入一个fileName,通过这个fileName去找到文件所在路径,创建输入输出流,最终以输出流格式输出
* @param request
* @param response
* @return
*/
@RequestMapping("/download")
public String download(String fileName, HttpServletRequest request,
HttpServletResponse response) {
System.out.println(fileName);
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName="
+ fileName);
try {
String path = request.getSession().getServletContext().getRealPath("/")+File.separator;
InputStream inputStream = new FileInputStream(new File(path
+ fileName));
OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
// 这里主要关闭。
os.close();
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 返回值要注意,要不然就出现下面这句错误!
//java+getOutputStream() has already been called for this response
return null;
}
/**
* 批量插入客户
* 读取Excel中的用户信息插入数据库
* @param request
* @param file1
* @return {'code':'0'}(成功) 或 {'code':'1'}(失败)
*/
@RequestMapping(value="/batchimport",produces = "text/plain;charset=utf-8")
@ResponseBody
public String batchImportMethod(HttpServletRequest request,@RequestParam(value="file1") MultipartFile file1) {
//局部变量
LeadingInExcel<Customer> testExcel=null;
List<Customer> uploadAndRead=null;
boolean judgement = false;
String code =null;
String error = "";
//定义需要读取的数据
String formart = "yyyy-MM-dd";
//String propertiesFileName = "config";
//String kyeName = "file_path";
int sheetIndex = 0;
Map<String, String> titleAndAttribute=null;
Class<Customer> clazz=Customer.class;
//定义对应的标题名与对应属性名
titleAndAttribute=new HashMap<String, String>();
titleAndAttribute.put("customer_id", "customerId");
titleAndAttribute.put("name", "name");
titleAndAttribute.put("contacts", "contacts");
titleAndAttribute.put("tel", "tel");
titleAndAttribute.put("user_id", "user");
titleAndAttribute.put("custcategory_id", "custcategoryId");
titleAndAttribute.put("credit_id", "creditId");
titleAndAttribute.put("satisfied_id", "satisfiedId");
titleAndAttribute.put("address", "address");
titleAndAttribute.put("postal", "postal");
titleAndAttribute.put("fax", "fax");
titleAndAttribute.put("url", "url");
titleAndAttribute.put("legal_person", "legalPerson");
titleAndAttribute.put("license", "license");
titleAndAttribute.put("fund", "fund");
titleAndAttribute.put("turnover", "turnover");
titleAndAttribute.put("bank", "bank");
titleAndAttribute.put("bank_number", "bankNumber");
titleAndAttribute.put("state_tax", "stateTax");
titleAndAttribute.put("land_tax", "landTax");
titleAndAttribute.put("custfrom_id", "custfromId");
titleAndAttribute.put("changes", "changes");
//调用解析工具包
testExcel=new LeadingInExcel<Customer>(formart);
//解析excel,获取客户信息集合
try {
uploadAndRead = testExcel.uploadAndRead(request,file1, sheetIndex, titleAndAttribute, clazz);
} catch (Exception e) {
logger.error("读取Excel文件错误!",e);
}
if(uploadAndRead != null && !"[]".equals(uploadAndRead.toString()) && uploadAndRead.size()>=1){
judgement = true;
}
if(judgement){
//把客户信息分为每10条数据为一组迭代添加客户信息(注:将customerList集合作为参数,在Mybatis的相应映射文件中使用foreach标签进行批量添加。)
//int count=0;
int listSize=uploadAndRead.size();
int toIndex=10;
for (int i = 0; i < listSize; i+=10) {
if(i+10>listSize){
toIndex=listSize-i;
}
List<Customer> customerList = uploadAndRead.subList(i, i+toIndex);
for (Customer customer : customerList) {
System.out.println(customer.toString());
}
/** 此处执行集合添加 */
int ret = customerService.addCustomers(customerList);
if (ret == 1) {
code ="0";
}else {
code ="1";
}
}
}else{
code ="1";
}
String res = "{ error:'" + error + "', code:'" + code + "'}";
return res;
}
//4、历史订单子模块
// 此系统对订单模块仅限于查询,而不能插入,更新和删除,如果需要,要在产品系统里面实现
/**
* 添加订单前的查询
* @param customerId
* @return
*/
/*@RequestMapping("/addOrders")
public ModelAndView addOrders(Integer customerId) {
ModelAndView view = new ModelAndView("customer/addOrder");
List<Orders> list = ordersService.findAll();
view.getModel().put("list", list);
view.getModel().put("customerId", customerId);
return view;
}*/
/**
* 执行插入订单
* @param orders
* @return
*/
/*@RequestMapping(value="/doaddOrders",produces = "text/plain;charset=utf-8")
@ResponseBody
public String doAddOrders(Orders orders) {
int ret = ordersService.addOrder(orders);
if (ret != 0){
//插入成功
return "{'code':'0'}";
}
else {
//插入失败
return "{'code':'1'}";
}
}*/
/**
* 更新订单前的查询
* @param orderId
* @return
*/
/*@RequestMapping("/editOrders")
public ModelAndView toEditOrders(Integer orderId) {
ModelAndView view = new ModelAndView("customer/updateOrder");
Orders orders = ordersService.findById(orderId);
List<Orders> list = ordersService.findAll();
view.getModel().put("list", list);
view.getModel().put("orders", orders);
return view;
}*/
/**
* 执行更新订单
* @param orders
* @param request
* @return
*/
/*@RequestMapping(value="/doeditOrders",produces = "text/plain;charset=utf-8")
@ResponseBody
public String doEditOrders(Orders orders,HttpServletRequest request) {
int ret = ordersService.editOrder(orders);
if (ret != 0) {
// 更新成功
return "{'code':'0'}";
} else {
// 更新失败
return "{'code':'1'}";
}
}*/
/**
* 删除订单
* @param orderId
* @param request
* @return
*/
/*@RequestMapping(value="/delOrders",produces = "text/plain;charset=utf-8")
@ResponseBody
public String doDelOrders(Integer orderId,HttpServletRequest request) {
int ret = ordersService.deleteById(orderId);
if (ret != 0) {
// 删除成功
return "{'msg':'1'}";
} else {
// 删除失败
return "{'msg':'0'}";
}
}*/
/**
* 分页模糊查询订单前的查询,将地址查出来填充到jsp页面的下拉框
* @return json数据(orderss)
*/
@RequestMapping(value="/listOrdersAddress",produces = "text/plain;charset=utf-8")
@ResponseBody
public String findOrdersAddress() {
List<Orders> orderss = ordersService.findAll();
Map<String, Object> map = new HashMap<>();
map.put("orderss", orderss);
return new Gson().toJson(map);
}
/**
* 分页模糊查询订单前的查询,将此条订单的信息在jsp页面显示出来
* @param orders
* @return view(orders) url:customer/orderList.jsp
*/
@RequestMapping(value="/tolistOrders",produces = "text/plain;charset=utf-8")
public ModelAndView toFindByOrders(Orders orders){
ModelAndView view = new ModelAndView("customer/orderList");
Customer customer = customerService.findById(orders.getCustomer().getCustomerId());
orders.setCustomer(customer);
view.getModel().put("orders", orders);
return view;
}
/**
* 订单分页模块查询
*/
@RequestMapping(value="/listOrders",produces = "text/plain;charset=utf-8")
@ResponseBody
public String findByOrders(Orders orders,Integer pageNo,Integer pageSize) {
System.out.println(orders.toString());
if(pageNo == null) {
pageNo = 1;
}
if(pageSize == null) {
pageSize = 10;
}
if(orders.getAddress().equals("-1")) {
orders.setAddress(null);
}
if (orders.getState().equals("-1")) {
orders.setState(null);
}
Pager<Orders> pager = new Pager<>(pageNo, pageSize);
pager.setParam(orders);
Integer total = ordersService.countForPager(pager);
pager.setTotal(total);
List<Orders> orderss = ordersService.findByPager(pager);
Map<String, Object> map = new HashMap<>();
map.put("list", orderss);
map.put("pager", pager);
return new Gson().toJson(map);
}
//5、订单详细信息子模块
/**
* 分页模糊查询前的查询,将某条订单的信息传到jsp页面进行显示
* @param orderitem
* @return view(ordes) url:customer/orderitemList.jsp
*/
@RequestMapping(value="/tolistOrderitem",produces = "text/plain;charset=utf-8")
public ModelAndView toFindByOrderitem(Orderitem orderitem){
ModelAndView view = new ModelAndView("customer/orderitemList");
Orders orders = ordersService.findById(orderitem.getOrder().getOrderId());
Customer customer = orders.getCustomer();
//List<Orderitem> orderitems = orderitemService.findByOrderId(orderitem.getOrder().getOrderId());
view.getModel().put("orders", orders);
view.getModel().put("customer", customer);
//view.getModel().put("orderitems", orderitems);
return view;
}
/**
* 订单详细分页模糊查询
* @param orderitem
* @param pageNo
* @param pageSize
* @return json数据(list(orderitems),pager)
*/
@RequestMapping(value="/listOrderItem",produces = "text/plain;charset=utf-8")
@ResponseBody
public String findByOrderItem(Orderitem orderitem,Integer pageNo,Integer pageSize) {
System.out.println(orderitem.toString());
if(pageNo == null) {
pageNo = 1;
}
if(pageSize == null) {
pageSize = 10;
}
Pager<Orderitem> pager = new Pager<>(pageNo, pageSize);
pager.setParam(orderitem);
Integer total = orderitemService.countForPager(pager);
pager.setTotal(total);
List<Orderitem> orderitems = orderitemService.findByPager(pager);
Map<String, Object> map = new HashMap<>();
map.put("list", orderitems);
map.put("pager", pager);
return new Gson().toJson(map);
}
//6、客户流失模块
/**
* 分页模糊查询前的查询,将客户和客户经理传回jsp页面进行下拉框填充
* @return
*/
@RequestMapping(value="/tolistLossUser",produces = "text/plain;charset=utf-8")
@ResponseBody
public String findLossUser() {
List<User> users = userService.findAll();
List<Customer> customers = customerService.findAll();
Map<String, Object> map = new HashMap<>();
map.put("users", users);
map.put("customers", customers);
return new Gson().toJson(map);
}
/**
* 流失信息分页模糊查询
* @param loss
* @param pageNo
* @param pageSize
* @return json数据(list(losss),pager)
*/
@RequestMapping(value="/listLoss",produces = "text/plain;charset=utf-8")
@ResponseBody
public String findByLoss(Loss loss,Integer pageNo,Integer pageSize) {
//System.out.println(loss.toString());
if(pageNo == null) {
pageNo = 1;
}
if(pageSize == null) {
pageSize = 10;
}
if(loss.getUser().getId() == -1) {
loss.setUser(null);
}
if (loss.getCustomer().getCustomerId() == -1) {
loss.setCustomer(null);
}
if(loss.getState().equals("-1")) {
loss.setState(null);
}
if (loss.getMeasure().equals("")) {
loss.setMeasure(null);
}
Pager<Loss> pager = new Pager<>(pageNo, pageSize);
pager.setParam(loss);
Integer total = lossService.countForPager(pager);
pager.setTotal(total);
List<Loss> losss = lossService.findByPager(pager);
Map<String, Object> map = new HashMap<>();
map.put("list", losss);
map.put("pager", pager);
return new Gson().toJson(map);
}
/**
* 暂缓流失更新前的查询
* @param lossId
* @return view(list(loss))
*/
@RequestMapping("/editLossTemp")
public ModelAndView toEditLossTemp(Integer lossId) {
ModelAndView view = new ModelAndView("customer/tempLoss");
Loss loss = lossService.findById(lossId);
view.getModel().put("list", loss);
return view;
}
/**
* 确认流失更新前的查询
* @param lossId
* @return view(list(loss))
*/
@RequestMapping("/editLossComfirm")
public ModelAndView toEditLossComfirm(Integer lossId) {
ModelAndView view = new ModelAndView("customer/comfirmLoss");
Loss loss = lossService.findById(lossId);
System.out.println(loss.toString());
view.getModel().put("list", loss);
return view;
}
/**
* 暂缓流失
* @param loss
* @param request
* @return {'code':'0'}(成功) {'code':'1'}(失败)
*/
@RequestMapping(value="/doeditLoTemp",produces = "text/plain;charset=utf-8")
@ResponseBody
public String doEditLossTemp(Loss loss,HttpServletRequest request) {
System.out.println(loss.toString());
int ret = lossService.editLoss(loss);
if (ret != 0) {
// 更新成功
return "{'code':'0'}";
} else {
// 更新失败
return "{'code':'1'}";
}
}
/**
* 确认流失
* @param loss
* @param request
* @return {'code':'0'}(成功) {'code':'1'}(失败)
*/
@RequestMapping(value="/doeditLoComfirm",produces = "text/plain;charset=utf-8")
@ResponseBody
public String doEditLossComfirm(Loss loss,HttpServletRequest request) {
int ret = lossService.editLoss(loss);
if (ret != 0) {
// 更新成功
return "{'code':'0'}";
} else {
// 更新失败
return "{'code':'1'}";
}
}
}
| [
"chenjiaman000@qq.com"
] | chenjiaman000@qq.com |
e1ad0bea828ef2d2b9fbf5646ac329e6cbf24a81 | 8695848bba6d2fa30d9bfedc37b6d93c0a5523dd | /Account.java | 89df8d2350a1af5f448e53b81eeceaf886b3cd05 | [] | no_license | cvaugh11/BankAccountApp | f83edd8ddbc9662dcee282057283fce9f5aad1cb | ded513eb3be5039b2ab3a0ea5a2d5bec4f33a8bc | refs/heads/master | 2022-10-13T23:01:31.637065 | 2020-06-09T11:24:22 | 2020-06-09T11:24:22 | 266,888,938 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,616 | java | public abstract class Account implements IBaseRate {
private String name, ssn;
private double balance;
private static int index = 1000;
protected String accountNum;
protected double rate;
public Account(String name, String ssn, double deposit) {
this.name = name;
this.ssn = ssn;
this.balance = deposit;
index++;
this.accountNum = setAccountNum();
setRate();
}
public abstract void setRate();
private String setAccountNum() {
String lastTwoOfSsn = ssn.substring(ssn.length() - 2, ssn.length());
int uniqueId = index;
int randomNum = (int) (Math.random() * Math.pow(10, 3));
return lastTwoOfSsn + uniqueId + randomNum;
}
public void compound() {
double interest = balance * (rate / 100);
balance = balance + interest;
System.out.println("Accrued Interest: $" + interest);
printBalance();
}
public void deposit(double amount) {
balance = balance + amount;
System.out.println("Depositing $ " + amount);
printBalance();
}
public void withdraw(double amount) {
balance = balance - amount;
System.out.println("Withdrawing $ " + amount);
printBalance();
}
public void transfer(String where, double amount) {
balance = balance - amount;
System.out.println("Transferring $" + amount + " to " + where);
printBalance();
}
public void printBalance() {
System.out.println("Your balance is now $" + balance);
}
public void showInfo() {
System.out.println(
"Name: " + name + "\nAccount Number: " + accountNum + "\nBalance: " + balance + "\nRate: " + rate + "%");
}
} | [
"RichHomieVaughn@carltons-mbp.home"
] | RichHomieVaughn@carltons-mbp.home |
f6ad5b96fc1b9edf02661b3f9e5dc6cb93fd540c | 8387c50c3ed0a18dc4d2e944f748df472a95d28c | /bhaskar/src/boss/Samplehashmap.java | afd97745ff9df350f294614f94424067bc026469 | [] | no_license | bhaskarsoorisetti/bhaskar | a5456ba72df835631112888eb3b00cdf97672409 | 747332038a88166288fc8aa8d39e56e78eae44d4 | refs/heads/master | 2020-03-07T10:26:38.540811 | 2018-04-06T07:20:59 | 2018-04-06T07:20:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 448 | java | package boss;
import java.util.HashMap;
import java.util.Map.Entry;
public class Samplehashmap {
public static void main (String[] args)
{
//progarm for hashmap
HashMap<Integer,String> hm=new HashMap<Integer,String>();
//storing data to hashmap
hm.put(1,"bhaskar");
hm.put(2,"Aravind");
//getting data from hashmap
for(Entry<Integer,String> m:hm.entrySet())
{
System.out.println(m.getValue());
}
}
}
| [
"Acer@192.168.0.14"
] | Acer@192.168.0.14 |
ecbfd626febe3d58bd52ec6597e748e66bd24786 | b6b029e1bd88eb629286c9296720b74ecdde538d | /kursach/src/java/kursach/dal/RateDal.java | c68c9d44955a4387e3f65b25b7e6cbf97810d679 | [] | no_license | norik0/Auction | ab9cb14fecf63bf86fc963f743568df9958ec726 | 9a04f1e1558bb92a291a280a3fe90c53ed2404bc | refs/heads/master | 2021-04-24T19:55:50.983493 | 2018-03-07T17:39:31 | 2018-03-07T17:39:31 | 117,429,600 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,775 | 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 kursach.dal;
import java.util.List;
import kursach.model.Rate;
import org.apache.ibatis.session.SqlSession;
/**
*
* @author olejaja
*/
public class RateDal extends BaseDal
{
public RateDal () {
super();
}
public List<Rate> selectAll()
{
SqlSession session = sqlSessionFactory.openSession();
List<Rate> list = session.selectList("rate.selectAll");
session.close();
return list;
}
public Rate selectById(int id)
{
SqlSession session = sqlSessionFactory.openSession();
Rate rate= (Rate)session.selectOne("rate.selectById",id);
session.close();
return rate;
}
public Rate selectLastRate()
{
SqlSession session = sqlSessionFactory.openSession();
Rate rate= (Rate)session.selectOne("rate.selectLastRate");
session.close();
return rate;
}
public int insert(Rate rate)
{
SqlSession session = sqlSessionFactory.openSession();
int count = session.insert("rate.insert",rate);
session.commit();
session.close();
return count;
}
public int update(Rate rate)
{
SqlSession session = sqlSessionFactory.openSession();
int count = session.update("rate.update",rate);
session.commit();
session.close();
return count;
}
public int delete(Rate rate)
{
SqlSession session = sqlSessionFactory.openSession();
int count = session.delete("rate.delete",rate);
session.commit();
session.close();
return count;
}
} | [
"ellie074074@gmail.com"
] | ellie074074@gmail.com |
1dd9e8f763a2f8147197eef93b01e69c5a15a267 | 007cc2783c488ccbc61da2c068d0cfa002e2169f | /Factory/src/main/java/au/edu/swin/ict/TEST.java | fd647b493e74308ce58fb80e6cb6124baa4b47f1 | [] | no_license | road-framework/SDSN | cdc9806a3948b800191187d3ecb09c1f00ad58b3 | ad3fbb5c6bc67c6afba6dff9bd909e2c2967bd72 | refs/heads/master | 2021-01-11T07:46:37.383430 | 2019-02-25T15:24:19 | 2019-02-25T15:24:19 | 68,914,667 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,369 | java | package au.edu.swin.ict;
import au.edu.swin.ict.road.composite.exceptions.CompositeInstantiationException;
import au.edu.swin.ict.road.composite.exceptions.ConsistencyViolationException;
import au.edu.swin.ict.road.demarshalling.CompositeDemarshaller;
import au.edu.swin.ict.road.demarshalling.exceptions.CompositeDemarshallingException;
import au.edu.swin.ict.road.xml.bindings.ServiceNetwork;
/**
* TODO - documentation
*/
public class TEST {
public static void main(String args[]) {
CompositeDemarshaller compositeDemarshaller = new CompositeDemarshaller();
try {
ServiceNetwork smc =
compositeDemarshaller.demarshalSMCBinding("C:\\software\\ROAD-2.1-tag\\Factory\\suburb.xsd");
System.out.println(smc.getVirtualServiceNetwork().get(0).getProcess().get(0).getCoS());
} catch (CompositeDemarshallingException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (ConsistencyViolationException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (CompositeInstantiationException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
| [
"indikakumara@users.noreply.github.com"
] | indikakumara@users.noreply.github.com |
77caa3808d833215a6295faf41a8271838403ee2 | 934e92de380589ebd855a54c63930788d2ff6108 | /Week6AssessmentKrebs/src/main/java/controller/NavigationServlet.java | 12cb353021187ff8dafcfe758a5a9e7021f35256 | [] | no_license | JJosephK/Week11Assessment | 464618ccbb8f95c1030613fb96c6cecfcb90a87d | bd62b3d0f6f10ab58f7575fffe5f71acaeecd09b | refs/heads/main | 2023-09-03T21:35:21.676709 | 2021-11-11T23:02:15 | 2021-11-11T23:02:15 | 427,164,499 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,345 | java | package 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 model.groceryItem;
/**
* Servlet implementation class NavigationServlet
*/
@WebServlet("/navigationServlet")
public class NavigationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public NavigationServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String act = request.getParameter("doThisToItem");
String path = "/viewAllItemsServlet";
groceryHelper dao = new groceryHelper();
//after all changes we should redirect to viewallitems servlet
//the only time we dont is if they select to add a new item or edit
if (act.equals("delete")){
try {
Integer tempId = Integer.parseInt(request.getParameter("id"));
groceryItem itemToDelete = dao.searchForItemById(tempId);
dao.deleteItem(itemToDelete);
}catch (NumberFormatException e) {
System.out.println("Forgot to select an item.");
}
}else if (act.equals("edit")) {
try {
Integer tempId = Integer.parseInt(request.getParameter("id"));
groceryItem itemToEdit = dao.searchForItemById(tempId);
request.setAttribute("itemToEdit", itemToEdit);
path = "/edit-item.jsp";
}catch (NumberFormatException e) {
System.out.println("Forgot to select an item");
}
}else if (act.equals("add")) {
path = "/index.html";
}
getServletContext().getRequestDispatcher(path).forward(request, response);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
d9174c0817382ff8aa1e3a952f172b1e92fb75f5 | 772fbf22eacbe858e4bdeebd4ee59326b8ba7856 | /components/podcasts/src/main/java/com/example/mediabase/podcasts/PodcastController.java | a3c401e7a0419faf41388888fda9fe3f78777e96 | [] | no_license | meghadneni/mediabase | 48df76e4217a6ad7daee3a9ce40ec923ecd7576f | 6136a20e2ac5bf422da018b135391d9c1c2bc2cb | refs/heads/master | 2020-07-30T21:34:22.162458 | 2019-09-26T15:24:11 | 2019-09-26T15:24:11 | 210,365,785 | 0 | 0 | null | 2019-09-23T13:43:58 | 2019-09-23T13:43:58 | null | UTF-8 | Java | false | false | 856 | java | package com.example.mediabase.podcasts;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/podcasts")
public class PodcastController {
private PodcastRepository podcastRepository;
public PodcastController(PodcastRepository podcastRepository) {
this.podcastRepository = podcastRepository;
}
@GetMapping()
public Iterable<Podcast> allPodcasts()
{
return podcastRepository.findAll();
}
@PostMapping
public ResponseEntity<Podcast> create(@RequestBody Podcast podcast)
{
podcastRepository.save(podcast);
return new ResponseEntity<>(HttpStatus.CREATED);
}
}
| [
"sairam.darapuneni@perficient.com"
] | sairam.darapuneni@perficient.com |
c98456f7a8cb3adb0b4361ad01aeee5997e23fd0 | 79bbe8d91a38ee7e0108fe4ffe989b9a4f213c6f | /src/main/java/com/boot/security/server/controller/RoleController.java | 72d5afe85b42bac1fc6873224050d502706b95e1 | [] | no_license | 412900691/boot-security-master | 220571ccb8b46c63e055329f65be9cf74917cc72 | 3189cd0fe7e0a270793debebfdecf2cefcaca8b3 | refs/heads/master | 2020-04-13T01:56:49.751827 | 2019-02-20T08:07:24 | 2019-02-20T08:07:24 | 162,888,121 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,291 | java | package com.boot.security.server.controller;
import java.util.List;
import com.boot.security.server.dto.LoginUser;
import com.boot.security.server.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.boot.security.server.annotation.LogAnnotation;
import com.boot.security.server.dao.RoleDao;
import com.boot.security.server.dto.RoleDto;
import com.boot.security.server.model.Role;
import com.boot.security.server.page.table.PageTableHandler;
import com.boot.security.server.page.table.PageTableHandler.CountHandler;
import com.boot.security.server.page.table.PageTableHandler.ListHandler;
import com.boot.security.server.page.table.PageTableRequest;
import com.boot.security.server.page.table.PageTableResponse;
import com.boot.security.server.service.RoleService;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
/**
* 角色相关接口
*
* @author xuhao
*
*/
@Api(tags = "角色")
@RestController
@RequestMapping("/roles")
public class RoleController {
@Autowired
private RoleService roleService;
@Autowired
private RoleDao roleDao;
@LogAnnotation
@PostMapping
@ApiOperation(value = "保存角色")
@PreAuthorize("hasAuthority('sys:role:add')")
public void saveRole(@RequestBody RoleDto roleDto) {
roleService.saveRole(roleDto);
}
@GetMapping
@ApiOperation(value = "角色列表")
@PreAuthorize("hasAuthority('sys:role:query')")
public PageTableResponse listRoles(PageTableRequest request) {
return new PageTableHandler(new CountHandler() {
@Override
public int count(PageTableRequest request) {
return roleDao.count(request.getParams());
}
}, new ListHandler() {
@Override
public List<Role> list(PageTableRequest request) {
List<Role> list = roleDao.list(request.getParams(), request.getOffset(), request.getLimit());
return list;
}
}).handle(request);
}
@GetMapping("/{id}")
@ApiOperation(value = "根据id获取角色")
@PreAuthorize("hasAuthority('sys:role:query')")
public Role get(@PathVariable Long id) {
return roleDao.getById(id);
}
@GetMapping("/all")
@ApiOperation(value = "所有角色")
@PreAuthorize("hasAnyAuthority('sys:user:query','sys:role:query')")
public List<Role> roles() {
return roleDao.list(Maps.newHashMap(), null, null);
}
@GetMapping(params = "userId")
@ApiOperation(value = "根据用户id获取拥有的角色")
@PreAuthorize("hasAnyAuthority('sys:user:query','sys:role:query')")
public List<Role> roles(Long userId) {
return roleDao.listByUserId(userId);
}
@LogAnnotation
@DeleteMapping("/{id}")
@ApiOperation(value = "删除角色")
@PreAuthorize("hasAuthority('sys:role:del')")
public void delete(@PathVariable Long id) {
roleService.deleteRole(id);
}
}
| [
"412900691@users.noreply.github.com"
] | 412900691@users.noreply.github.com |
80df4b397d1f2651992433d91ccbb9fe80e69e75 | 7e7e768605274dc7261ec45d34037e6fbb0733a9 | /data-mapper/org.wso2.developerstudio.visualdatamapper.diagram/src/dataMapper/diagram/edit/policies/EqualItemSemanticEditPolicy.java | ef7905214011a646fda2aca30f793a957e12c482 | [
"Apache-2.0"
] | permissive | thiliniish/developer-studio | c5fbaa0f5719dd40a90de8ac476efbc3bfd3ba1e | 9bce30885e9eafc4f7c1fa2e2cb5242842c39a0d | refs/heads/master | 2020-12-11T07:26:53.135319 | 2014-03-25T11:09:54 | 2014-03-25T11:09:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,463 | java | package dataMapper.diagram.edit.policies;
import org.eclipse.emf.ecore.EAnnotation;
import org.eclipse.gef.commands.Command;
import org.eclipse.gmf.runtime.diagram.core.commands.DeleteCommand;
import org.eclipse.gmf.runtime.emf.commands.core.command.CompositeTransactionalCommand;
import org.eclipse.gmf.runtime.emf.type.core.commands.DestroyElementCommand;
import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyElementRequest;
import org.eclipse.gmf.runtime.notation.View;
/**
* @generated
*/
public class EqualItemSemanticEditPolicy extends
dataMapper.diagram.edit.policies.DataMapperBaseItemSemanticEditPolicy {
/**
* @generated
*/
public EqualItemSemanticEditPolicy() {
super(dataMapper.diagram.providers.DataMapperElementTypes.Equal_2005);
}
/**
* @generated
*/
protected Command getDestroyElementCommand(DestroyElementRequest req) {
View view = (View) getHost().getModel();
CompositeTransactionalCommand cmd = new CompositeTransactionalCommand(getEditingDomain(),
null);
cmd.setTransactionNestingEnabled(false);
EAnnotation annotation = view.getEAnnotation("Shortcut"); //$NON-NLS-1$
if (annotation == null) {
// there are indirectly referenced children, need extra commands: false
addDestroyShortcutsCommand(cmd, view);
// delete host element
cmd.add(new DestroyElementCommand(req));
} else {
cmd.add(new DeleteCommand(getEditingDomain(), view));
}
return getGEFWrapper(cmd.reduce());
}
}
| [
"sumudithavi@gmail.com"
] | sumudithavi@gmail.com |
4c71d76b76950cd0ae6a380f9182e0bb75456e2a | 92df58008a9c43b30acf4abb9d26001d5046d889 | /src/main/java/com/meritamerica/assignment6/models/SavingsAccount.java | 749e834c35d65dd6b744bcebaa413b931ea45904 | [] | no_license | ibabkina/assignment6 | e914698062ad439889881f4b27b327b7733bf311 | 357ae54db921d71ce1892a7657fc7baa44ac1b55 | refs/heads/master | 2023-06-09T08:25:57.115044 | 2021-07-05T20:43:25 | 2021-07-05T20:43:25 | 379,026,799 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,677 | java | package com.meritamerica.assignment6.models;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* This program creates a savings account for a client.
*
* @author Irina Babkina
*
*/
@Entity
@Table(name = "savings_accounts")
public class SavingsAccount extends BankAccount {
private static final double INTEREST_RATE = 0.01;
// private double interestRate = 0.01;
/**
* Default constructor
*/
public SavingsAccount() { super(0, INTEREST_RATE); }
/**
* @param openingBalance
*/
public SavingsAccount(double openingBalance) {
super(openingBalance, INTEREST_RATE);
}
/**
* @param openingBalance
* @param interestRate
*/
public SavingsAccount(double openingBalance, double interestRate){
super(openingBalance, interestRate);
}
/**
* @param accNumber
* @param openingBalance
* @param interestRate
*/
public SavingsAccount(long accNumber, double openingBalance, double interestRate, java.util.Date accountOpenedOn){
super(accNumber, openingBalance, interestRate, accountOpenedOn);
}
// Should throw a java.lang.NumberFormatException if String cannot be correctly parsed
public static SavingsAccount readFromString(String accountData)
throws NumberFormatException, ParseException {
String[] args = accountData.split(",");
SavingsAccount acc = new SavingsAccount(Long.parseLong(args[0]), Double.parseDouble(args[1]),
Double.parseDouble(args[2]), new SimpleDateFormat("MM/dd/yyyy").parse(args[3]));
return acc;
}
// /**
// * @return the interestRate
// */
// public double getInterestRate() { return INTEREST_RATE; }
// /**
// * Calculates the future value of the account balance based on the interest
// * and number of years
// * @param years: number of periods in years
// * @return the future value
// */
// double futureValue(int years){ return this.balance * pow(1 + interestRate, years); }
@Override
public String toString() {
return "\nSavings Account Number: " + this.getAccountNumber()
+ "\nSavings Account Balance: $" + String.format("%.2f", this.getBalance())
+ "\nSavings Account Interest Rate: " + String.format("%.4f", this.getInterestRate())
+ "\nSavings Account Balance in 3 years: " + String.format("%.2f", this.futureValue(3))
+ "\nSavings Account Opened Date " + this.getOpenedOn();
}
@Override
public String writeToString() {
return Long.toString(this.getAccountNumber()) + ","
+ String.format("%.0f", this.getBalance()) + ","
+ String.format("%.2f", this.getInterestRate()) + ","
+ new SimpleDateFormat("MM/dd/yyyy").format(this.openedOn);
}
} | [
"i.babkina700@gmail.com"
] | i.babkina700@gmail.com |
1a032dfdb3ed501b1233a0da9988e60eb75d9cdf | 7cec372953f03f07075244a0cf9040c08e15eee7 | /src/FindPeakElement.java | 6f2e0d6650eb27931792900d0301c142a4e50735 | [] | no_license | qazwsxedc121/leetcode | 7d60290fa1515c043d3273d09475233dafaa3955 | 3ffb881e5beb838cd837f31597537eb3280ba1e1 | refs/heads/master | 2021-01-22T03:43:54.476938 | 2015-10-03T15:24:08 | 2015-10-03T15:24:08 | 28,669,547 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,203 | java | /**
* Created by Administrator on 2015/3/17.
*/
public class FindPeakElement {
public int findPeakElement(int[] num){
int n = num.length;
if(n == 0){
return -1;
}else if(n == 1){
return 0;
}
if(num[0] > num[1]){
return 0;
}else if(num[n-1] > num[n-2]){
return n-1;
}
int l = 0;
int r = n - 1;
int mid = (l + r) / 2;
while(l < r){
if(isPeak(num,l)){
return l;
}else if(isPeak(num,r)){
return r;
}else if(isPeak(num,mid)){
return mid;
}else if(num[mid] < num[mid - 1]){
r = mid - 1;
mid = (l + r + 1) / 2;
}else{
l = mid + 1;
mid = (l + r - 1) / 2;
}
}
return -1;
}
private boolean isPeak(int[] num, int i){
return i > 0 && i < num.length && num[i] > num[i-1] && num[i] > num[i+1];
}
public static void test(){
FindPeakElement f = new FindPeakElement();
System.out.println(f.findPeakElement(new int[]{3,4,3,2,1}));
}
}
| [
"qazwsxedc121@gmail.com"
] | qazwsxedc121@gmail.com |
9212d94f65407718dec40fc694cccb5e9f46c95d | 49cf9308c31f62f32f7afd7bc9a3884c70455ad4 | /04_FactoryMode/src/main/java/com/xiaoliu66/github/after/ICommodity.java | 299546804ecbb69f62fbc1880cee2f1ff3a90f06 | [] | no_license | xiaoliu66/LearnDesignModels | 104422326d022bb0c287b160705d089389f143d9 | b94bbfa51fe6334ad9304ff8a3683b39d97aeacc | refs/heads/master | 2023-06-04T09:07:16.461189 | 2021-06-16T15:07:20 | 2021-06-16T15:07:20 | 370,734,371 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 309 | java | package com.xiaoliu66.github.after;
import java.util.Map;
/**
* @author xiaoliu66@github.com
* @since 2021/6/10 21:45
* @version 1.0
* 发送奖品接口
*/
public interface ICommodity {
void sendCommodity(String uId, String commodityId, String bizId, Map<String,String> exMap) throws Exception;
}
| [
"lunhuilk@163.com"
] | lunhuilk@163.com |
4385235adcc91e76a281e809fec938f0a756585d | fe85418943041835cb30a5d7951176f633b56a13 | /sample-core-java/src/main/java/org/mac/sample/corejava/concurrency/juc/collections/PriorityLinkedList.java | bbd509073316d43607b105f3b894d99483f76108 | [] | no_license | stinymac/samples | 073cfc1535880f11204139153bb723351bae336a | 1e9edcdc7204808c10edda3e816a0871c5384217 | refs/heads/master | 2022-12-23T05:57:19.683866 | 2020-09-14T01:34:51 | 2020-09-14T01:34:51 | 140,654,344 | 1 | 0 | null | 2022-12-15T23:37:31 | 2018-07-12T03:09:34 | Java | UTF-8 | Java | false | false | 2,428 | java | /*
* ( (
* )\ ) ( )\ ) ) (
* ( ( (()/( ))\( ((_| /( /(( ))\
* )\ )\ ((_))((_)\ _ )(_)|_))\ /((_)
* ((_|(_) _| (_))((_) ((_)__)((_|_))
* / _/ _ \/ _` / -_|_-< / _` \ V // -_)
* \__\___/\__,_\___/__/_\__,_|\_/ \___|
*
* 东隅已逝,桑榆非晚。(The time has passed,it is not too late.)
* 虽不能至,心向往之。(Although I can't, my heart is longing for it.)
*
*/
package org.mac.sample.corejava.concurrency.juc.collections;
/**
*
* @author Mac
* @create 2018-06-17 22:51
**/
public class PriorityLinkedList<E extends Comparable<E>> {
private final class Node<E extends Comparable<E>> {
E element;
Node<E> next;
Node<E> prev;
public Node(E element) {
this.element = element;
}
}
private Node<E> head;
private Node<E> tail;
private int size;
public PriorityLinkedList() {
this.head = this.tail = null;
this.size = 0;
}
public int size() {
return this.size;
}
public boolean isEmpty() {
return this.size == 0;
}
public void add(E e){
Node<E> newNode = new Node<E>(e);
if (tail == null) {
head = tail = newNode;
} else {
Node t = tail;
while (t != null && t.element.compareTo(e) > 0) {
t = t.prev;
}
if (t != null) {
if (t == tail) {
t.next = newNode;
newNode.prev = t;
tail = newNode;
} else {
newNode.next = t.next;
t.next.prev = newNode;
t.next = newNode;
newNode.prev = t;
}
} else {
newNode.next = head;
head.prev = newNode;
head = newNode;
}
}
this.size++;
}
@Override
public String toString() {
Node<E> h = head;
StringBuilder builder = new StringBuilder("[ ");
while (h != null ) {
E e = h.element;
if(h.next == null) {
builder.append(e.toString());
} else {
builder.append(e.toString()+",");
}
h = h.next;
}
builder.append(" ]");
return builder.toString();
}
}
| [
"machao1@jianke.com"
] | machao1@jianke.com |
5edcda42e8f774745ef1dc09eb8912704a3eb0b3 | 563e39394d014c3e915d09d44a545646ac613f32 | /libopengl/src/main/java/com/bestarmedia/libopengl/filter/texture/TextureSampling3mul3Filter.java | a4512a6c2f7444a97de6a7ee691040bc1ce792d9 | [] | no_license | androidok/KTV | ca6378027e2382bf12af770ceaebec1221b53385 | c9054e244e534187d135eaac9dc1b25f8d13b693 | refs/heads/master | 2022-04-02T11:33:27.193851 | 2020-01-02T09:07:35 | 2020-01-02T09:07:35 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,783 | java | /*
*
* *
* * * Copyright (C) 2016 ChillingVan
* * *
* * * 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.bestarmedia.libopengl.filter.texture;
import android.opengl.GLES20;
import android.support.annotation.FloatRange;
import com.bestarmedia.libopengl.ICanvasGL;
import com.bestarmedia.libopengl.OpenGLUtil;
import com.bestarmedia.libopengl.canvas.gl.BasicTexture;
/**
* Created by Chilling on 2016/11/6.
*/
public abstract class TextureSampling3mul3Filter extends BasicTextureFilter implements OneValueFilter {
public static final String UNIFORM_TEXEL_WIDTH = "texelWidth";
public static final String UNIFORM_TEXEL_HEIGHT = "texelHeight";
public static final String VARYING_LEFT_TEXTURE_COORDINATE = "leftTextureCoordinate";
public static final String VARYING_RIGHT_TEXTURE_COORDINATE = "rightTextureCoordinate";
public static final String VARYING_TOP_TEXTURE_COORDINATE = "topTextureCoordinate";
public static final String VARYING_TOP_LEFT_TEXTURE_COORDINATE = "topLeftTextureCoordinate";
public static final String VARYING_TOP_RIGHT_TEXTURE_COORDINATE = "topRightTextureCoordinate";
public static final String VARYING_BOTTOM_TEXTURE_COORDINATE = "bottomTextureCoordinate";
public static final String VARYING_BOTTOM_LEFT_TEXTURE_COORDINATE = "bottomLeftTextureCoordinate";
public static final String VARYING_BOTTOM_RIGHT_TEXTURE_COORDINATE = "bottomRightTextureCoordinate";
public static final String THREE_X_THREE_TEXTURE_SAMPLING_VERTEX_SHADER = "" +
"attribute vec2 " + POSITION_ATTRIBUTE + ";\n" +
"\n" +
"\n" +
"uniform highp float " + UNIFORM_TEXEL_WIDTH + "; \n" +
"uniform highp float " + UNIFORM_TEXEL_HEIGHT + "; \n" +
"\n" +
"varying vec2 " + VARYING_TEXTURE_COORD + ";\n" +
"varying vec2 " + VARYING_LEFT_TEXTURE_COORDINATE + ";\n" +
"varying vec2 " + VARYING_RIGHT_TEXTURE_COORDINATE + ";\n" +
"\n" +
"varying vec2 " + VARYING_TOP_TEXTURE_COORDINATE + ";\n" +
"varying vec2 " + VARYING_TOP_LEFT_TEXTURE_COORDINATE + ";\n" +
"varying vec2 " + VARYING_TOP_RIGHT_TEXTURE_COORDINATE + ";\n" +
"\n" +
"varying vec2 " + VARYING_BOTTOM_TEXTURE_COORDINATE + ";\n" +
"varying vec2 " + VARYING_BOTTOM_LEFT_TEXTURE_COORDINATE + ";\n" +
"varying vec2 " + VARYING_BOTTOM_RIGHT_TEXTURE_COORDINATE + ";\n" +
"\n" +
"uniform mat4 " + MATRIX_UNIFORM + ";\n" + "uniform mat4 " + TEXTURE_MATRIX_UNIFORM + ";\n" + "void main() {\n" +
" vec4 pos = vec4(" + POSITION_ATTRIBUTE + ", 0.0, 1.0);\n" + "" +
" gl_Position = " + MATRIX_UNIFORM + " * pos;\n" +
"\n" +
" vec2 widthStep = vec2(" + UNIFORM_TEXEL_WIDTH + ", 0.0);\n" +
" vec2 heightStep = vec2(0.0, " + UNIFORM_TEXEL_HEIGHT + ");\n" +
" vec2 widthHeightStep = vec2(" + UNIFORM_TEXEL_WIDTH + ", " + UNIFORM_TEXEL_HEIGHT + ");\n" +
" vec2 widthNegativeHeightStep = vec2(" + UNIFORM_TEXEL_WIDTH + ", -" + UNIFORM_TEXEL_HEIGHT + ");\n" +
"\n" +
" " + VARYING_TEXTURE_COORD + " = (" + TEXTURE_MATRIX_UNIFORM + " * pos).xy;\n" +
" " + VARYING_LEFT_TEXTURE_COORDINATE + " = " + VARYING_TEXTURE_COORD + ".xy - widthStep;\n" +
" " + VARYING_RIGHT_TEXTURE_COORDINATE + " = " + VARYING_TEXTURE_COORD + ".xy + widthStep;\n" +
"\n" +
" " + VARYING_TOP_TEXTURE_COORDINATE + " = " + VARYING_TEXTURE_COORD + ".xy - heightStep;\n" +
" " + VARYING_TOP_LEFT_TEXTURE_COORDINATE + " = " + VARYING_TEXTURE_COORD + ".xy - widthHeightStep;\n" +
" " + VARYING_TOP_RIGHT_TEXTURE_COORDINATE + " = " + VARYING_TEXTURE_COORD + ".xy + widthNegativeHeightStep;\n" +
"\n" +
" " + VARYING_BOTTOM_TEXTURE_COORDINATE + " = " + VARYING_TEXTURE_COORD + ".xy + heightStep;\n" +
" " + VARYING_BOTTOM_LEFT_TEXTURE_COORDINATE + " = " + VARYING_TEXTURE_COORD + ".xy - widthNegativeHeightStep;\n" +
" " + VARYING_BOTTOM_RIGHT_TEXTURE_COORDINATE + " = " + VARYING_TEXTURE_COORD + ".xy + widthHeightStep;\n" +
"}";
private int mUniformTexelWidthLocation;
private int mUniformTexelHeightLocation;
private boolean mHasOverriddenImageWidthFactor = false;
private boolean mHasOverriddenImageHeightFactor = false;
private float mTexelWidth;
private float mTexelHeight;
private float mLineSize = 1.0f;
public TextureSampling3mul3Filter(@FloatRange(from = 0, to = 5) float lineSize) {
this.mLineSize = lineSize;
}
@Override
public String getVertexShader() {
return THREE_X_THREE_TEXTURE_SAMPLING_VERTEX_SHADER;
}
public void setTexelWidth(final float texelWidth) {
mHasOverriddenImageWidthFactor = true;
mTexelWidth = texelWidth;
setLineSize(mLineSize);
}
public void setTexelHeight(final float texelHeight) {
mHasOverriddenImageHeightFactor = true;
mTexelHeight = texelHeight;
setLineSize(mLineSize);
}
public void setLineSize(@FloatRange(from = 0, to = 5) final float size) {
mLineSize = size;
}
@Override
public void onPreDraw(int program, BasicTexture texture, ICanvasGL canvas) {
super.onPreDraw(program, texture, canvas);
mTexelWidth = !mHasOverriddenImageWidthFactor ? mLineSize / texture.getWidth() : mTexelWidth;
mTexelHeight = !mHasOverriddenImageHeightFactor ? mLineSize / texture.getHeight() : mTexelHeight;
mUniformTexelWidthLocation = GLES20.glGetUniformLocation(program, UNIFORM_TEXEL_WIDTH);
mUniformTexelHeightLocation = GLES20.glGetUniformLocation(program, UNIFORM_TEXEL_HEIGHT);
if (mTexelWidth != 0) {
OpenGLUtil.setFloat(mUniformTexelWidthLocation, mTexelWidth);
OpenGLUtil.setFloat(mUniformTexelHeightLocation, mTexelHeight);
}
}
@Override
public void setValue(@FloatRange(from = 0, to = 5) float lineSize) {
setLineSize(lineSize);
}
}
| [
"40749627+lisimian0626@users.noreply.github.com"
] | 40749627+lisimian0626@users.noreply.github.com |
674da0b3a0c182c273cf1209efc509d16987ae56 | 96f6ac99230fcc98c4fa4aec4d08745878c7fb73 | /src/main/java/com/example/demo/Service/Impl/UserServiceImpl.java | 51223ed2ade99e50891745f77c11a272dfec4579 | [] | no_license | Carlos-zero/redwork | fb5e8b2315ba2e7d471bb30d86eabbf9a3f74d6c | 97ab58ebf0dbfc564be9e34c77ec9aec4e7552cf | refs/heads/master | 2020-04-08T23:14:54.303923 | 2019-03-22T16:21:12 | 2019-03-22T16:21:12 | 159,817,394 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,749 | java | package com.example.demo.Service.Impl;
import com.example.demo.Been.User;
import com.example.demo.Dao.Impl.UserSqlDaoImpl;
import com.example.demo.Dao.UserSqlDao;
import com.example.demo.Annotation.Role;
import com.example.demo.Service.UserService;
import java.sql.SQLException;
public class UserServiceImpl implements UserService {
private static final UserSqlDao USER_SQL_DAO;
private static User user=new User();
static {
USER_SQL_DAO = new UserSqlDaoImpl();
}
@Override
public User getUserLogin(String user_name, String password) throws SQLException {
user=USER_SQL_DAO.login(user_name, password);
return user;
}
public User getUser(){
return user;
}
@Role(need_role = "admin")
@Override
public String getAdminResUpData(String password, String email, String telephone, String user_name) throws SQLException {
String result=USER_SQL_DAO.updateData(password, email, telephone, user_name);
return result;
}
@Role(need_role = "god")
@Override
public String getGodResUpRole(String user_name, String role) throws SQLException {
String result=USER_SQL_DAO.updateRole(user_name, role);
return result;
}
@Role(need_role = "god")
@Override
public String getGodResAddUser(String user_name, String password, String email, String telephone, String role) throws SQLException {
String result=USER_SQL_DAO.insertUser(user_name, password, email, telephone, role);
return result;
}
@Role(need_role = "god")
@Override
public String getGodResDelUser(String user_name) throws SQLException {
String result=USER_SQL_DAO.deleteUser(user_name);
return result;
}
}
| [
"948017088@qq.com"
] | 948017088@qq.com |
3cb54b3c1e5e92a81c46efbd35fdb3adf9338c2a | d71e879b3517cf4fccde29f7bf82cff69856cfcd | /ExtractedJars/iRobot_com.irobot.home/javafiles/com/irobot/home/SmartMapTipsActivity_$a.java | ed33d4800d032c4a8d84ee62a8dc58b0a6a1474d | [
"MIT"
] | permissive | Andreas237/AndroidPolicyAutomation | b8e949e072d08cf6c6166c3f15c9c63379b8f6ce | c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a | refs/heads/master | 2020-04-10T02:14:08.789751 | 2019-05-16T19:29:11 | 2019-05-16T19:29:11 | 160,739,088 | 5 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,685 | java | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.irobot.home;
import android.app.Activity;
import android.content.Context;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import org.androidannotations.api.a.a;
import org.androidannotations.api.a.e;
// Referenced classes of package com.irobot.home:
// SmartMapTipsActivity_
public static class SmartMapTipsActivity_$a extends a
{
public e a(int i)
{
if(e != null)
//* 0 0:aload_0
//* 1 1:getfield #21 <Field Fragment e>
//* 2 4:ifnull 22
e.startActivityForResult(c, i);
// 3 7:aload_0
// 4 8:getfield #21 <Field Fragment e>
// 5 11:aload_0
// 6 12:getfield #25 <Field android.content.Intent c>
// 7 15:iload_1
// 8 16:invokevirtual #31 <Method void Fragment.startActivityForResult(android.content.Intent, int)>
else
//* 9 19:goto 95
if(d != null)
//* 10 22:aload_0
//* 11 23:getfield #33 <Field android.app.Fragment d>
//* 12 26:ifnull 48
d.startActivityForResult(c, i, a);
// 13 29:aload_0
// 14 30:getfield #33 <Field android.app.Fragment d>
// 15 33:aload_0
// 16 34:getfield #25 <Field android.content.Intent c>
// 17 37:iload_1
// 18 38:aload_0
// 19 39:getfield #36 <Field android.os.Bundle a>
// 20 42:invokevirtual #41 <Method void android.app.Fragment.startActivityForResult(android.content.Intent, int, android.os.Bundle)>
else
//* 21 45:goto 95
if(b instanceof Activity)
//* 22 48:aload_0
//* 23 49:getfield #45 <Field Context b>
//* 24 52:instanceof #47 <Class Activity>
//* 25 55:ifeq 80
ActivityCompat.startActivityForResult((Activity)b, c, i, a);
// 26 58:aload_0
// 27 59:getfield #45 <Field Context b>
// 28 62:checkcast #47 <Class Activity>
// 29 65:aload_0
// 30 66:getfield #25 <Field android.content.Intent c>
// 31 69:iload_1
// 32 70:aload_0
// 33 71:getfield #36 <Field android.os.Bundle a>
// 34 74:invokestatic #52 <Method void ActivityCompat.startActivityForResult(Activity, android.content.Intent, int, android.os.Bundle)>
else
//* 35 77:goto 95
b.startActivity(c, a);
// 36 80:aload_0
// 37 81:getfield #45 <Field Context b>
// 38 84:aload_0
// 39 85:getfield #25 <Field android.content.Intent c>
// 40 88:aload_0
// 41 89:getfield #36 <Field android.os.Bundle a>
// 42 92:invokevirtual #58 <Method void Context.startActivity(android.content.Intent, android.os.Bundle)>
return new e(b);
// 43 95:new #60 <Class e>
// 44 98:dup
// 45 99:aload_0
// 46 100:getfield #45 <Field Context b>
// 47 103:invokespecial #62 <Method void e(Context)>
// 48 106:areturn
}
private android.app.Fragment d;
private Fragment e;
public SmartMapTipsActivity_$a(Context context)
{
super(context, com/irobot/home/SmartMapTipsActivity_);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:ldc1 #7 <Class SmartMapTipsActivity_>
// 3 4:invokespecial #17 <Method void a(Context, Class)>
// 4 7:return
}
}
| [
"silenta237@gmail.com"
] | silenta237@gmail.com |
9dd47a0121ae2d4fe96aa08fbbc60b97a50f9b6f | bdcdcf52c63a1037786ac97fbb4da88a0682e0e8 | /src/test/java/io/akeyless/client/model/GatewayCreateProducerRedisTest.java | 195dadc561c41b9db9941c70d8dd162932c991d1 | [
"Apache-2.0"
] | permissive | akeylesslabs/akeyless-java | 6e37d9ec59d734f9b14e475ce0fa3e4a48fc99ea | cfb00a0e2e90ffc5c375b62297ec64373892097b | refs/heads/master | 2023-08-03T15:06:06.802513 | 2023-07-30T11:59:23 | 2023-07-30T11:59:23 | 341,514,151 | 2 | 4 | Apache-2.0 | 2023-07-11T08:57:17 | 2021-02-23T10:22:38 | Java | UTF-8 | Java | false | false | 3,351 | java | /*
* Akeyless API
* The purpose of this application is to provide access to Akeyless API.
*
* The version of the OpenAPI document: 2.0
* Contact: support@akeyless.io
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package io.akeyless.client.model;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
/**
* Model tests for GatewayCreateProducerRedis
*/
public class GatewayCreateProducerRedisTest {
private final GatewayCreateProducerRedis model = new GatewayCreateProducerRedis();
/**
* Model tests for GatewayCreateProducerRedis
*/
@Test
public void testGatewayCreateProducerRedis() {
// TODO: test GatewayCreateProducerRedis
}
/**
* Test the property 'aclRules'
*/
@Test
public void aclRulesTest() {
// TODO: test aclRules
}
/**
* Test the property 'deleteProtection'
*/
@Test
public void deleteProtectionTest() {
// TODO: test deleteProtection
}
/**
* Test the property 'host'
*/
@Test
public void hostTest() {
// TODO: test host
}
/**
* Test the property 'json'
*/
@Test
public void jsonTest() {
// TODO: test json
}
/**
* Test the property 'name'
*/
@Test
public void nameTest() {
// TODO: test name
}
/**
* Test the property 'password'
*/
@Test
public void passwordTest() {
// TODO: test password
}
/**
* Test the property 'port'
*/
@Test
public void portTest() {
// TODO: test port
}
/**
* Test the property 'producerEncryptionKeyName'
*/
@Test
public void producerEncryptionKeyNameTest() {
// TODO: test producerEncryptionKeyName
}
/**
* Test the property 'ssl'
*/
@Test
public void sslTest() {
// TODO: test ssl
}
/**
* Test the property 'sslCertificate'
*/
@Test
public void sslCertificateTest() {
// TODO: test sslCertificate
}
/**
* Test the property 'tags'
*/
@Test
public void tagsTest() {
// TODO: test tags
}
/**
* Test the property 'targetName'
*/
@Test
public void targetNameTest() {
// TODO: test targetName
}
/**
* Test the property 'token'
*/
@Test
public void tokenTest() {
// TODO: test token
}
/**
* Test the property 'uidToken'
*/
@Test
public void uidTokenTest() {
// TODO: test uidToken
}
/**
* Test the property 'userTtl'
*/
@Test
public void userTtlTest() {
// TODO: test userTtl
}
/**
* Test the property 'username'
*/
@Test
public void usernameTest() {
// TODO: test username
}
}
| [
"github@akeyless.io"
] | github@akeyless.io |
88f5402a22715c22986dde5c0df2f4bbd67a5bf8 | 2474744df850fd4d170a65ef78e1202aea89d8b8 | /jehc-base/src/main/java/jehc/xtmodules/xtcore/base/binder/FloatEditor.java | 246c4d2a3fd3b004b16a7f56eebde8c79ae350c9 | [] | no_license | cgb-extjs-gwt/jehc | 073c98ba8d25c8cf0ffa769bf09788e01bae375b | 69112cc9b79c96bb258fc472f22c946f8c5a2008 | refs/heads/master | 2023-04-27T08:04:06.440924 | 2018-08-24T08:53:24 | 2018-08-24T08:53:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 506 | java | package jehc.xtmodules.xtcore.base.binder;
import org.springframework.beans.propertyeditors.PropertiesEditor;
public class FloatEditor extends PropertiesEditor{
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (text == null || text.equals("")) {
text = "0";
}
setValue(Float.parseFloat(text));
}
@Override
public String getAsText() {
return getValue().toString();
}
}
| [
"244831954@qq.com"
] | 244831954@qq.com |
7103113547a74fcd653d289aaadb750b6f574a05 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/7/7_0c4eedcb5aec711741514cc0c8606e07ef0f51b2/DefaultBroadcaster/7_0c4eedcb5aec711741514cc0c8606e07ef0f51b2_DefaultBroadcaster_s.java | 186a06d09232e58604533c5f454f1756ee96fec7 | [] | 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 | 50,854 | java | /*
* Copyright 2012 Jeanfrancois Arcand
*
* 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.
*/
/*
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2007-2008 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*
*/
package org.atmosphere.cpr;
import org.atmosphere.cpr.BroadcastFilter.BroadcastAction;
import org.atmosphere.cpr.BroadcasterConfig.DefaultBroadcasterCache;
import org.atmosphere.di.InjectorProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import static org.atmosphere.cpr.ApplicationConfig.MAX_INACTIVE;
import static org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.EMPTY;
import static org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.EMPTY_DESTROY;
import static org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.IDLE;
import static org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.IDLE_DESTROY;
import static org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.IDLE_RESUME;
import static org.atmosphere.cpr.BroadcasterLifeCyclePolicy.ATMOSPHERE_RESOURCE_POLICY.NEVER;
/**
* {@link Broadcaster} implementation.
* <p/>
* Broadcast messages to suspended response using the caller's Thread.
* This basic {@link Broadcaster} use an {@link java.util.concurrent.ExecutorService}
* to broadcast message, hence the broadcast operation is asynchronous. Make sure
* you block on {@link #broadcast(Object)}.get()} if you need synchronous operations.
*
* @author Jeanfrancois Arcand
*/
public class DefaultBroadcaster implements Broadcaster {
public static final String CACHED = DefaultBroadcaster.class.getName() + ".messagesCached";
public static final String ASYNC_TOKEN = DefaultBroadcaster.class.getName() + ".token";
private static final Logger logger = LoggerFactory.getLogger(DefaultBroadcaster.class);
private static final String DESTROYED = "This Broadcaster has been destroyed and cannot be used {} by invoking {}";
protected final ConcurrentLinkedQueue<AtmosphereResource> resources =
new ConcurrentLinkedQueue<AtmosphereResource>();
protected BroadcasterConfig bc;
protected final BlockingQueue<Entry> messages = new LinkedBlockingQueue<Entry>();
protected final BlockingQueue<AsyncWriteToken> asyncWriteQueue = new LinkedBlockingQueue<AsyncWriteToken>();
protected final CopyOnWriteArrayList<BroadcasterListener> broadcasterListeners = new CopyOnWriteArrayList<BroadcasterListener>();
protected final AtomicBoolean started = new AtomicBoolean(false);
protected final AtomicBoolean destroyed = new AtomicBoolean(false);
protected SCOPE scope = SCOPE.APPLICATION;
protected String name = DefaultBroadcaster.class.getSimpleName();
protected final ConcurrentLinkedQueue<Entry> delayedBroadcast = new ConcurrentLinkedQueue<Entry>();
protected final ConcurrentLinkedQueue<Entry> broadcastOnResume = new ConcurrentLinkedQueue<Entry>();
protected final ConcurrentLinkedQueue<BroadcasterLifeCyclePolicyListener> lifeCycleListeners = new ConcurrentLinkedQueue<BroadcasterLifeCyclePolicyListener>();
protected Future<?> notifierFuture;
protected Future<?> asyncWriteFuture;
public BroadcasterCache broadcasterCache;
private POLICY policy = POLICY.FIFO;
private final AtomicLong maxSuspendResource = new AtomicLong(-1);
private final AtomicBoolean requestScoped = new AtomicBoolean(false);
private final AtomicBoolean recentActivity = new AtomicBoolean(false);
private BroadcasterLifeCyclePolicy lifeCyclePolicy = new BroadcasterLifeCyclePolicy.Builder()
.policy(NEVER).build();
private Future<?> currentLifecycleTask;
protected URI uri;
protected AtmosphereConfig config;
protected BroadcasterCache.STRATEGY cacheStrategy = BroadcasterCache.STRATEGY.AFTER_FILTER;
private final Object[] awaitBarrier = new Object[0];
private final Object[] concurrentSuspendBroadcast = new Object[0];
public DefaultBroadcaster(String name, URI uri, AtmosphereConfig config) {
this.name = name;
this.uri = uri;
this.config = config;
broadcasterCache = new DefaultBroadcasterCache();
bc = createBroadcasterConfig(config);
String s = config.getInitParameter(ApplicationConfig.BROADCASTER_CACHE_STRATEGY);
if (s != null) {
if (s.equalsIgnoreCase("afterFilter")) {
cacheStrategy = BroadcasterCache.STRATEGY.AFTER_FILTER;
} else if (s.equalsIgnoreCase("beforeFilter")) {
cacheStrategy = BroadcasterCache.STRATEGY.BEFORE_FILTER;
}
}
}
public DefaultBroadcaster(String name, AtmosphereConfig config) {
this(name, URI.create("http://localhost"), config);
}
/**
* Create {@link BroadcasterConfig}
*
* @param config the {@link AtmosphereConfig}
* @return an instance of {@link BroadcasterConfig}
*/
protected BroadcasterConfig createBroadcasterConfig(AtmosphereConfig config) {
return new BroadcasterConfig(config.framework().broadcasterFilters, config);
}
/**
* {@inheritDoc}
*/
public synchronized void destroy() {
if (destroyed.getAndSet(true)) return;
notifyDestroyListener();
try {
logger.trace("Broadcaster {} is being destroyed and cannot be re-used", getID());
if (BroadcasterFactory.getDefault() != null) {
BroadcasterFactory.getDefault().remove(this, this.getID());
}
if (currentLifecycleTask != null) {
currentLifecycleTask.cancel(true);
}
started.set(false);
releaseExternalResources();
if (notifierFuture != null) {
notifierFuture.cancel(true);
}
if (asyncWriteFuture != null) {
asyncWriteFuture.cancel(true);
}
if (bc != null) {
bc.destroy();
}
if (broadcasterCache != null) {
broadcasterCache.stop();
}
resources.clear();
broadcastOnResume.clear();
messages.clear();
asyncWriteQueue.clear();
delayedBroadcast.clear();
} catch (Throwable t) {
logger.error("Unexpected exception during Broadcaster destroy {}", getID(), t);
}
}
/**
* {@inheritDoc}
*/
public Collection<AtmosphereResource> getAtmosphereResources() {
return Collections.unmodifiableCollection(resources);
}
/**
* {@inheritDoc}
*/
public void setScope(SCOPE scope) {
if (destroyed.get()) {
logger.debug(DESTROYED, getID(), "setScope");
return;
}
this.scope = scope;
if (scope != SCOPE.REQUEST) {
return;
}
logger.debug("Changing broadcaster scope for {}. This broadcaster will be destroyed.", getID());
synchronized (resources) {
try {
// Next, we need to create a new broadcaster per resource.
for (AtmosphereResource resource : resources) {
Broadcaster b = BroadcasterFactory.getDefault()
.get(getClass(), getClass().getSimpleName() + "/" + UUID.randomUUID());
if (DefaultBroadcaster.class.isAssignableFrom(this.getClass())) {
BroadcasterCache cache = bc.getBroadcasterCache().getClass().newInstance();
InjectorProvider.getInjector().inject(cache);
DefaultBroadcaster.class.cast(b).broadcasterCache = cache;
DefaultBroadcaster.class.cast(b).getBroadcasterConfig().setBroadcasterCache(cache);
}
resource.setBroadcaster(b);
b.setScope(SCOPE.REQUEST);
if (resource.getAtmosphereResourceEvent().isSuspended()) {
b.addAtmosphereResource(resource);
}
logger.debug("Resource {} not using broadcaster {}", resource, b.getID());
}
// Do not destroy because this is a new Broadcaster
if (resources.isEmpty()) {
return;
}
destroy();
} catch (Exception e) {
logger.error("Failed to set request scope for current resources", e);
}
}
}
/**
* {@inheritDoc}
*/
public SCOPE getScope() {
return scope;
}
/**
* {@inheritDoc}
*/
public synchronized void setID(String id) {
if (id == null) {
id = getClass().getSimpleName() + "/" + UUID.randomUUID();
}
if (BroadcasterFactory.getDefault() == null)
return; // we are shutdown or destroyed, but someone still reference
Broadcaster b = BroadcasterFactory.getDefault().lookup(this.getClass(), id);
if (b != null && b.getScope() == SCOPE.REQUEST) {
throw new IllegalStateException("Broadcaster ID already assigned to SCOPE.REQUEST. Cannot change the id");
} else if (b != null) {
return;
}
BroadcasterFactory.getDefault().remove(this, name);
this.name = id;
BroadcasterFactory.getDefault().add(this, name);
}
/**
* {@inheritDoc}
*/
public String getID() {
return name;
}
/**
* {@inheritDoc}
*/
public void resumeAll() {
synchronized (resources) {
for (AtmosphereResource r : resources) {
try {
r.resume();
} catch (Throwable t) {
logger.trace("resumeAll", t);
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void releaseExternalResources() {
}
/**
* {@inheritDoc}
*/
@Override
public void setBroadcasterLifeCyclePolicy(final BroadcasterLifeCyclePolicy lifeCyclePolicy) {
this.lifeCyclePolicy = lifeCyclePolicy;
if (currentLifecycleTask != null) {
currentLifecycleTask.cancel(false);
}
if (bc != null && bc.getScheduledExecutorService() == null) {
logger.error("No Broadcaster's SchedulerExecutorService has been configured on {}. BroadcasterLifeCyclePolicy won't work.", getID());
return;
}
if (lifeCyclePolicy.getLifeCyclePolicy() == IDLE
|| lifeCyclePolicy.getLifeCyclePolicy() == IDLE_RESUME
|| lifeCyclePolicy.getLifeCyclePolicy() == IDLE_DESTROY) {
recentActivity.set(false);
int time = lifeCyclePolicy.getTimeout();
if (time == -1) {
throw new IllegalStateException("BroadcasterLifeCyclePolicy time is not set");
}
final AtomicReference<Future<?>> ref = new AtomicReference<Future<?>>();
currentLifecycleTask = bc.getScheduledExecutorService().scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
// Check for activity since the last execution.
if (recentActivity.getAndSet(false)) {
return;
} else if (resources.isEmpty()) {
if (lifeCyclePolicy.getLifeCyclePolicy() == IDLE) {
notifyEmptyListener();
notifyIdleListener();
releaseExternalResources();
logger.debug("Applying BroadcasterLifeCyclePolicy IDLE policy to Broadcaster {}", getID());
} else if (lifeCyclePolicy.getLifeCyclePolicy() == IDLE_DESTROY) {
notifyEmptyListener();
notifyIdleListener();
destroy(false);
logger.debug("Applying BroadcasterLifeCyclePolicy IDLE_DESTROY policy to Broadcaster {}", getID());
}
} else if (lifeCyclePolicy.getLifeCyclePolicy() == IDLE_RESUME) {
notifyIdleListener();
destroy(true);
logger.debug("Applying BroadcasterLifeCyclePolicy IDLE_RESUME policy to Broadcaster {}", getID());
}
} catch (Throwable t) {
if (destroyed.get()) {
logger.trace("Scheduled BroadcasterLifeCyclePolicy exception", t);
} else {
logger.warn("Scheduled BroadcasterLifeCyclePolicy exception", t);
}
}
}
void destroy(boolean resume) {
if (resume) {
logger.info("All AtmosphereResource will now be resumed from Broadcaster {}", getID());
resumeAll();
}
DefaultBroadcaster.this.destroy();
/**
* The value may be null if the timeout is too low. Hopefully next execution will
* cancel the task properly.
*/
if (ref.get() != null) {
currentLifecycleTask.cancel(true);
}
}
}, time, time, lifeCyclePolicy.getTimeUnit());
ref.set(currentLifecycleTask);
}
}
/**
* {@inheritDoc}
*/
@Override
public void addBroadcasterLifeCyclePolicyListener(BroadcasterLifeCyclePolicyListener b) {
lifeCycleListeners.add(b);
}
/**
* {@inheritDoc}
*/
@Override
public void removeBroadcasterLifeCyclePolicyListener(BroadcasterLifeCyclePolicyListener b) {
lifeCycleListeners.remove(b);
}
/**
* {@inheritDoc}
*/
@Override
public boolean isDestroyed() {
return destroyed.get();
}
/**
* {@inheritDoc}
*/
@Override
public <T> Future<T> awaitAndBroadcast(T t, long time, TimeUnit timeUnit) {
if (resources.isEmpty()) {
synchronized (awaitBarrier) {
try {
logger.trace("Awaiting for AtmosphereResource for {} {}", time, timeUnit);
awaitBarrier.wait(translateTimeUnit(time, timeUnit));
} catch (Throwable e) {
logger.warn("awaitAndBroadcast", e);
return null;
}
}
}
return broadcast(t);
}
/**
* {@inheritDoc}
*/
@Override
public Broadcaster addBroadcasterListener(BroadcasterListener b) {
broadcasterListeners.add(b);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public Broadcaster removeBroadcasterListener(BroadcasterListener b) {
broadcasterListeners.remove(b);
return this;
}
public static final class Entry {
public Object message;
public Object multipleAtmoResources;
public BroadcasterFuture<?> future;
public boolean writeLocally;
public Object originalMessage;
public Entry(Object message, Object multipleAtmoResources, BroadcasterFuture<?> future, Object originalMessage) {
this.message = message;
this.multipleAtmoResources = multipleAtmoResources;
this.future = future;
this.writeLocally = true;
this.originalMessage = originalMessage;
}
public Entry(Object message, Object multipleAtmoResources, BroadcasterFuture<?> future, boolean writeLocally) {
this.message = message;
this.multipleAtmoResources = multipleAtmoResources;
this.future = future;
this.writeLocally = writeLocally;
this.originalMessage = message;
}
@Override
public String toString() {
return "Entry{" +
"message=" + message +
", multipleAtmoResources=" + multipleAtmoResources +
", future=" + future +
'}';
}
}
protected Runnable getBroadcastHandler() {
return new Runnable() {
public void run() {
Entry msg = null;
while (started.get()) {
try {
msg = messages.poll(10, TimeUnit.SECONDS);
if (msg == null) {
if (destroyed.get()) {
return;
} else {
continue;
}
}
push(msg);
} catch (InterruptedException ex) {
return;
} catch (Throwable ex) {
if (!started.get() || destroyed.get()) {
logger.trace("Failed to submit broadcast handler runnable on shutdown for Broadcaster {}", getID(), ex);
return;
} else {
logger.warn("This message {} will be lost", msg);
logger.debug("Failed to submit broadcast handler runnable to for Broadcaster {}", getID(), ex);
}
}
}
}
};
}
protected void start() {
if (!started.getAndSet(true)) {
broadcasterCache = bc.getBroadcasterCache();
broadcasterCache.start();
setID(name);
notifierFuture = bc.getExecutorService().submit(getBroadcastHandler());
asyncWriteFuture = bc.getAsyncWriteService().submit(getAsyncWriteHandler());
}
}
protected void push(Entry entry) {
push(entry, true);
}
protected void push(Entry entry, boolean rec) {
if (destroyed.get()) {
return;
}
// We need to synchronize t make sure there is no suspend operation retrieving cached messages concurrently.
// https://github.com/Atmosphere/atmosphere/issues/170
synchronized (concurrentSuspendBroadcast) {
recentActivity.set(true);
String prevMessage = entry.message.toString();
if (rec && !delayedBroadcast.isEmpty()) {
Iterator<Entry> i = delayedBroadcast.iterator();
StringBuilder b = new StringBuilder();
while (i.hasNext()) {
Entry e = i.next();
e.future.cancel(true);
try {
// Append so we do a single flush
if (e.message instanceof String
&& entry.message instanceof String) {
b.append(e.message);
} else {
push(e, false);
}
} finally {
i.remove();
}
}
if (b.length() > 0) {
entry.message = b.append(entry.message).toString();
}
}
Object finalMsg = translate(entry.message);
if (finalMsg == null) {
logger.trace("Broascast message was null {}", finalMsg);
return;
}
Object prevM = entry.originalMessage;
entry.originalMessage = (entry.originalMessage != entry.message ? translate(entry.originalMessage) : finalMsg);
if (entry.originalMessage == null) {
logger.trace("Broascast message was null {}", prevM);
return;
}
entry.message = finalMsg;
if (resources.isEmpty()) {
logger.debug("Broadcaster {} doesn't have any associated resource. Message will be cached in the configured BroadcasterCache", getID());
AtmosphereResource r = null;
if (entry.multipleAtmoResources != null && AtmosphereResource.class.isAssignableFrom(entry.multipleAtmoResources.getClass())) {
r = AtmosphereResource.class.cast(entry.multipleAtmoResources);
}
trackBroadcastMessage(r, cacheStrategy == BroadcasterCache.STRATEGY.AFTER_FILTER ? entry.message : entry.originalMessage);
if (entry.future != null) {
entry.future.done();
}
return;
}
try {
if (entry.multipleAtmoResources == null) {
for (AtmosphereResource r : resources) {
finalMsg = perRequestFilter(r, entry);
if (finalMsg == null) {
logger.debug("Skipping broadcast delivery resource {} ", r);
continue;
}
if (entry.writeLocally) {
queueWriteIO(r, finalMsg, entry);
}
}
} else if (entry.multipleAtmoResources instanceof AtmosphereResource) {
finalMsg = perRequestFilter((AtmosphereResource) entry.multipleAtmoResources, entry);
if (finalMsg == null) {
logger.debug("Skipping broadcast delivery resource {} ", entry.multipleAtmoResources);
return;
}
if (entry.writeLocally) {
queueWriteIO((AtmosphereResource) entry.multipleAtmoResources, finalMsg, entry);
}
} else if (entry.multipleAtmoResources instanceof Set) {
Set<AtmosphereResource> sub = (Set<AtmosphereResource>) entry.multipleAtmoResources;
for (AtmosphereResource r : sub) {
finalMsg = perRequestFilter(r, entry);
if (finalMsg == null) {
logger.debug("Skipping broadcast delivery resource {} ", r);
continue;
}
if (entry.writeLocally) {
queueWriteIO(r, finalMsg, entry);
}
}
}
entry.message = prevMessage;
} catch (InterruptedException ex) {
logger.debug(ex.getMessage(), ex);
}
}
}
protected void queueWriteIO(AtmosphereResource r, Object finalMsg, Entry entry) throws InterruptedException {
asyncWriteQueue.put(new AsyncWriteToken(r, finalMsg, entry.future, entry.originalMessage));
}
protected Object perRequestFilter(AtmosphereResource r, Entry msg) {
// A broadcaster#broadcast(msg,Set) may contains null value.
if (r == null) {
logger.trace("Null AtmosphereResource passed inside a Set");
return msg.message;
}
Object finalMsg = msg.message;
if (AtmosphereResourceImpl.class.isAssignableFrom(r.getClass())) {
synchronized (r) {
if (isAtmosphereResourceValid(r)) {
if (bc.hasPerRequestFilters()) {
BroadcastAction a = bc.filter(r, msg.message, msg.originalMessage);
if (a.action() == BroadcastAction.ACTION.ABORT) {
return null;
}
if (a.message() != msg.originalMessage) {
finalMsg = a.message();
}
}
} else {
// The resource is no longer valid.
removeAtmosphereResource(r);
BroadcasterFactory.getDefault().removeAllAtmosphereResource(r);
}
if (cacheStrategy == BroadcasterCache.STRATEGY.AFTER_FILTER) {
trackBroadcastMessage(r, finalMsg);
}
}
}
return finalMsg;
}
private Object translate(Object msg) {
if (Callable.class.isAssignableFrom(msg.getClass())) {
try {
return Callable.class.cast(msg).call();
} catch (Exception e) {
logger.warn("Callable exception", e);
return null;
}
}
return msg;
}
protected void executeAsyncWrite(final AsyncWriteToken token) {
boolean notifyListeners = true;
boolean lostCandidate = false;
final AtmosphereResourceEventImpl event = (AtmosphereResourceEventImpl) token.resource.getAtmosphereResourceEvent();
final AtmosphereResourceImpl r = AtmosphereResourceImpl.class.cast(token.resource);
r.getRequest().setAttribute(getID(), token.future);
try {
event.setMessage(token.msg);
// Make sure we cache the message in case the AtmosphereResource has been cancelled, resumed or the client disconnected.
if (!isAtmosphereResourceValid(r)) {
removeAtmosphereResource(r);
lostCandidate = true;
return;
}
try {
r.getRequest().setAttribute(MAX_INACTIVE, System.currentTimeMillis());
} catch (Throwable t) {
logger.warn("Invalid AtmosphereResource state {}. The connection has been remotely" +
" closed and will be added to the configured BroadcasterCache for later retrieval", event);
logger.trace("If you are using Tomcat 7.0.22 and lower, your most probably hitting http://is.gd/NqicFT");
logger.trace("", t);
// The Request/Response associated with the AtmosphereResource has already been written and commited
removeAtmosphereResource(r, false);
BroadcasterFactory.getDefault().removeAllAtmosphereResource(r);
event.setCancelled(true);
event.setThrowable(t);
r.setIsInScope(false);
lostCandidate = true;
return;
}
r.getRequest().setAttribute(ASYNC_TOKEN, token);
broadcast(r, event);
} finally {
if (notifyListeners) {
r.notifyListeners();
}
if (token.future != null) {
token.future.done();
}
if (lostCandidate) {
cacheLostMessage(r, token);
}
token.destroy();
}
}
protected Runnable getAsyncWriteHandler() {
return new Runnable() {
public void run() {
AsyncWriteToken token = null;
try {
token = asyncWriteQueue.poll(10, TimeUnit.SECONDS);
if (token == null) {
if (!destroyed.get()) {
bc.getAsyncWriteService().submit(this);
}
return;
}
synchronized (token.resource) {
// We want this thread to wait for the write operation to happens to kept the order
bc.getAsyncWriteService().submit(this);
executeAsyncWrite(token);
}
} catch (InterruptedException ex) {
return;
} catch (Throwable ex) {
if (!started.get() || destroyed.get()) {
logger.trace("Failed to execute a write operation. Broadcaster is destroyed or not yet started for Broadcaster {}", getID(), ex);
return;
} else {
if (token != null) {
logger.warn("This message {} will be lost, adding it to the BroadcasterCache", token.msg);
cacheLostMessage(token.resource, token);
}
logger.debug("Failed to execute a write operation for Broadcaster {}", getID(), ex);
}
}
}
};
}
protected void checkCachedAndPush(final AtmosphereResource r, final AtmosphereResourceEvent e) {
retrieveTrackedBroadcast(r, e);
if (e.getMessage() instanceof List && !((List) e.getMessage()).isEmpty()) {
r.getRequest().setAttribute(CACHED, "true");
// Must make sure execute only one thread
synchronized (r) {
broadcast(r, e);
}
}
}
protected boolean retrieveTrackedBroadcast(final AtmosphereResource r, final AtmosphereResourceEvent e) {
List<?> missedMsg = broadcasterCache.retrieveFromCache(r);
if (missedMsg != null && !missedMsg.isEmpty()) {
e.setMessage(missedMsg);
return true;
}
return false;
}
protected void trackBroadcastMessage(final AtmosphereResource r, Object msg) {
if (destroyed.get() || broadcasterCache == null) return;
try {
broadcasterCache.addToCache(r, msg);
} catch (Throwable t) {
logger.warn("Unable to track messages {}", msg, t);
}
}
protected void broadcast(final AtmosphereResource r, final AtmosphereResourceEvent e) {
try {
r.getAtmosphereHandler().onStateChange(e);
} catch (Throwable t) {
onException(t, r);
}
}
public void onException(Throwable t, final AtmosphereResource ar) {
logger.debug("onException()", t);
final AtmosphereResourceImpl r = AtmosphereResourceImpl.class.cast(ar);
// Remove to prevent other broadcast to re-use it.
removeAtmosphereResource(r);
final AtmosphereResourceEventImpl event = r.getAtmosphereResourceEvent();
event.setThrowable(t);
r.notifyListeners(event);
r.removeEventListeners();
/**
* Make sure we resume the connection on every IOException.
*/
if (bc != null && bc.getAsyncWriteService() != null) {
bc.getAsyncWriteService().execute(new Runnable() {
@Override
public void run() {
try {
r.resume();
} catch (Throwable t) {
logger.trace("Was unable to resume a corrupted AtmosphereResource {}", r);
logger.trace("Cause", t);
}
}
});
} else {
r.resume();
}
cacheLostMessage(r, (AsyncWriteToken) r.getRequest(false).getAttribute(ASYNC_TOKEN));
}
/**
* Cache the message because an unexpected exception occurred.
*
* @param r
*/
public void cacheLostMessage(AtmosphereResource r) {
// Quite ugly cast that need to be fixed all over the place
cacheLostMessage(r, (AsyncWriteToken)
AtmosphereResourceImpl.class.cast(r).getRequest(false).getAttribute(ASYNC_TOKEN));
}
/**
* Cache the message because an unexpected exception occurred.
*
* @param r
*/
public void cacheLostMessage(AtmosphereResource r, AsyncWriteToken token) {
try {
if (token != null && token.originalMessage != null) {
Object m = cacheStrategy.equals(BroadcasterCache.STRATEGY.BEFORE_FILTER) ? token.originalMessage : token.msg;
broadcasterCache.addToCache(r, m);
logger.trace("Lost message cached {}", m);
}
} catch (Throwable t2) {
logger.trace("Unable to cache message", t2);
}
}
@Override
public void setSuspendPolicy(long maxSuspendResource, POLICY policy) {
this.maxSuspendResource.set(maxSuspendResource);
this.policy = policy;
}
/**
* {@inheritDoc}
*/
@Override
public <T> Future<T> broadcast(T msg) {
if (destroyed.get()) {
logger.debug(DESTROYED, getID(), "broadcast(T msg)");
return (new BroadcasterFuture<Object>(msg, broadcasterListeners, this)).done();
}
start();
Object newMsg = filter(msg);
if (newMsg == null) return (new BroadcasterFuture<Object>(msg, broadcasterListeners, this)).done();
BroadcasterFuture<Object> f = new BroadcasterFuture<Object>(newMsg, resources.size(), broadcasterListeners, this);
messages.offer(new Entry(newMsg, null, f, msg));
return f;
}
/**
* Invoke the {@link BroadcastFilter}
*
* @param msg
* @return
*/
protected Object filter(Object msg) {
BroadcastAction a = bc.filter(msg);
if (a.action() == BroadcastAction.ACTION.ABORT || msg == null)
return null;
else
return a.message();
}
/**
* {@inheritDoc}
*/
@Override
public <T> Future<T> broadcast(T msg, AtmosphereResource r) {
if (destroyed.get()) {
logger.debug(DESTROYED, getID(), "broadcast(T msg, AtmosphereResource<?, ?> r");
return (new BroadcasterFuture<Object>(msg, broadcasterListeners, this)).done();
}
start();
Object newMsg = filter(msg);
if (newMsg == null) return (new BroadcasterFuture<Object>(msg, broadcasterListeners, this)).done();
BroadcasterFuture<Object> f = new BroadcasterFuture<Object>(newMsg, resources.size(), broadcasterListeners, this);
messages.offer(new Entry(newMsg, r, f, msg));
return f;
}
/**
* {@inheritDoc}
*/
@Override
public <T> Future<T> broadcastOnResume(T msg) {
if (destroyed.get()) {
logger.debug(DESTROYED, getID(), "broadcastOnResume(T msg)");
return (new BroadcasterFuture<Object>(msg, broadcasterListeners, this)).done();
}
start();
Object newMsg = filter(msg);
if (newMsg == null) return (new BroadcasterFuture<Object>(msg, broadcasterListeners, this)).done();
BroadcasterFuture<Object> f = new BroadcasterFuture<Object>(newMsg, resources.size(), broadcasterListeners, this);
broadcastOnResume.offer(new Entry(newMsg, null, f, msg));
return f;
}
protected void broadcastOnResume(AtmosphereResource r) {
Iterator<Entry> i = broadcastOnResume.iterator();
while (i.hasNext()) {
Entry e = i.next();
e.multipleAtmoResources = r;
push(e);
}
if (resources.isEmpty()) {
broadcastOnResume.clear();
}
}
/**
* {@inheritDoc}
*/
@Override
public <T> Future<T> broadcast(T msg, Set<AtmosphereResource> subset) {
if (destroyed.get()) {
logger.debug(DESTROYED, getID(), "broadcast(T msg, Set<AtmosphereResource<?, ?>> subset)");
return (new BroadcasterFuture<Object>(msg, broadcasterListeners, this)).done();
}
start();
Object newMsg = filter(msg);
if (newMsg == null) return (new BroadcasterFuture<Object>(msg, broadcasterListeners, this)).done();
BroadcasterFuture<Object> f = new BroadcasterFuture<Object>(null, newMsg, subset.size(), broadcasterListeners, this);
messages.offer(new Entry(newMsg, subset, f, msg));
return f;
}
/**
* {@inheritDoc}
*/
@Override
public Broadcaster addAtmosphereResource(AtmosphereResource r) {
try {
if (destroyed.get()) {
logger.debug(DESTROYED, getID(), "addAtmosphereResource(AtmosphereResource<?, ?> r");
return this;
}
start();
if (scope == SCOPE.REQUEST && requestScoped.getAndSet(true)) {
throw new IllegalStateException("Broadcaster " + this
+ " cannot be used as its scope is set to REQUEST");
}
// To avoid excessive synchronization, we allow resources.size() to get larger that maxSuspendResource
if (maxSuspendResource.get() > 0 && resources.size() >= maxSuspendResource.get()) {
// Resume the first in.
if (policy == POLICY.FIFO) {
// TODO handle null return from poll()
AtmosphereResource resource = resources.poll();
try {
logger.warn("Too many resource. Forcing resume of {} ", resource);
resource.resume();
} catch (Throwable t) {
logger.warn("failed to resume resource {} ", resource, t);
}
} else if (policy == POLICY.REJECT) {
throw new RejectedExecutionException(String.format("Maximum suspended AtmosphereResources %s", maxSuspendResource));
}
}
if (resources.contains(r)) {
return this;
}
// We need to synchronize here to let the push method cache message.
// https://github.com/Atmosphere/atmosphere/issues/170
synchronized (concurrentSuspendBroadcast) {
// Re-add yourself
if (resources.isEmpty()) {
BroadcasterFactory.getDefault().add(this, name);
}
checkCachedAndPush(r, r.getAtmosphereResourceEvent());
if (isAtmosphereResourceValid(r)) {
resources.add(r);
}
}
} finally {
// OK reset
if (resources.size() > 0) {
synchronized (awaitBarrier) {
awaitBarrier.notifyAll();
}
}
}
return this;
}
private boolean isAtmosphereResourceValid(AtmosphereResource r) {
return !AtmosphereResourceImpl.class.cast(r).isResumed()
&& !AtmosphereResourceImpl.class.cast(r).isCancelled()
&& AtmosphereResourceImpl.class.cast(r).isInScope();
}
/**
* {@inheritDoc}
*/
@Override
public Broadcaster removeAtmosphereResource(AtmosphereResource r) {
return removeAtmosphereResource(r, true);
}
protected Broadcaster removeAtmosphereResource(AtmosphereResource r, boolean executeDone) {
if (destroyed.get()) {
logger.debug(DESTROYED, getID(), "removeAtmosphereResource(AtmosphereResource r)");
return this;
}
// Here we need to make sure we aren't in the process of broadcasting and unlock the Future.
if (executeDone) {
BroadcasterFuture f = (BroadcasterFuture) r.getRequest().getAttribute(getID());
if (f != null) {
r.getRequest().removeAttribute(getID());
f.done();
}
}
resources.remove(r);
if (resources.isEmpty()) {
notifyEmptyListener();
if (scope != SCOPE.REQUEST && lifeCyclePolicy.getLifeCyclePolicy() == EMPTY) {
releaseExternalResources();
} else if (scope == SCOPE.REQUEST || lifeCyclePolicy.getLifeCyclePolicy() == EMPTY_DESTROY) {
BroadcasterFactory.getDefault().remove(this, name);
destroy();
}
}
return this;
}
private void notifyIdleListener() {
for (BroadcasterLifeCyclePolicyListener b : lifeCycleListeners) {
b.onIdle();
}
}
private void notifyDestroyListener() {
for (BroadcasterLifeCyclePolicyListener b : lifeCycleListeners) {
b.onDestroy();
}
}
private void notifyEmptyListener() {
for (BroadcasterLifeCyclePolicyListener b : lifeCycleListeners) {
b.onEmpty();
}
}
/**
* Set the {@link BroadcasterConfig} instance.
*
* @param bc
*/
@Override
public void setBroadcasterConfig(BroadcasterConfig bc) {
this.bc = bc;
}
/**
* Return the current {@link BroadcasterConfig}
*
* @return the current {@link BroadcasterConfig}
*/
public BroadcasterConfig getBroadcasterConfig() {
return bc;
}
/**
* {@inheritDoc}
*/
public <T> Future<T> delayBroadcast(T o) {
return delayBroadcast(o, 0, null);
}
/**
* {@inheritDoc}
*/
public <T> Future<T> delayBroadcast(final T o, long delay, TimeUnit t) {
if (destroyed.get()) {
logger.debug(DESTROYED, getID(), "delayBroadcast(final T o, long delay, TimeUnit t)");
return null;
}
start();
final Object msg = filter(o);
if (msg == null) return null;
final BroadcasterFuture<Object> future = new BroadcasterFuture<Object>(msg, broadcasterListeners, this);
final Entry e = new Entry(msg, null, future, o);
Future<T> f;
if (delay > 0) {
f = bc.getScheduledExecutorService().schedule(new Callable<T>() {
public T call() throws Exception {
delayedBroadcast.remove(e);
if (Callable.class.isAssignableFrom(o.getClass())) {
try {
Object r = Callable.class.cast(o).call();
final Object msg = filter(r);
if (msg != null) {
Entry entry = new Entry(msg, null, null, r);
push(entry);
}
return (T) msg;
} catch (Exception e1) {
logger.error("", e);
}
}
final Object msg = filter(o);
final Entry e = new Entry(msg, null, null, o);
push(e);
return (T) msg;
}
}, delay, t);
e.future = new BroadcasterFuture<Object>(f, msg, broadcasterListeners, this);
}
delayedBroadcast.offer(e);
return future;
}
/**
* {@inheritDoc}
*/
public Future<?> scheduleFixedBroadcast(final Object o, long period, TimeUnit t) {
return scheduleFixedBroadcast(o, 0, period, t);
}
/**
* {@inheritDoc}
*/
public Future<?> scheduleFixedBroadcast(final Object o, long waitFor, long period, TimeUnit t) {
if (destroyed.get()) {
logger.debug(DESTROYED, getID(), "scheduleFixedBroadcast(final Object o, long waitFor, long period, TimeUnit t)");
return null;
}
start();
if (period == 0 || t == null) {
return null;
}
final Object msg = filter(o);
if (msg == null) return null;
return bc.getScheduledExecutorService().scheduleWithFixedDelay(new Runnable() {
public void run() {
if (Callable.class.isAssignableFrom(o.getClass())) {
try {
Object r = Callable.class.cast(o).call();
final Object msg = filter(r);
if (msg != null) {
Entry entry = new Entry(msg, null, null, r);
push(entry);
}
return;
} catch (Exception e) {
logger.error("", e);
}
}
final Object msg = filter(o);
final Entry e = new Entry(msg, null, null, o);
push(e);
}
}, waitFor, period, t);
}
public String toString() {
return new StringBuilder().append("\nName: ").append(name).append("\n")
.append("\n\tScope: ").append(scope).append("\n")
.append("\n\tBroasdcasterCache ").append(broadcasterCache).append("\n")
.append("\n\tAtmosphereResource: ").append(resources.size()).append("\n")
.append(this.getClass().getName()).append("@").append(this.hashCode())
.toString();
}
protected final static class AsyncWriteToken {
AtmosphereResource resource;
Object msg;
BroadcasterFuture future;
Object originalMessage;
public AsyncWriteToken(AtmosphereResource resource, Object msg, BroadcasterFuture future, Object originalMessage) {
this.resource = resource;
this.msg = msg;
this.future = future;
this.originalMessage = originalMessage;
}
public void destroy() {
this.resource = null;
this.msg = null;
this.future = null;
this.originalMessage = null;
}
@Override
public String toString() {
return "AsyncWriteToken{" +
"resource=" + resource +
", msg=" + msg +
", future=" + future +
'}';
}
}
private long translateTimeUnit(long period, TimeUnit tu) {
if (period == -1) return period;
switch (tu) {
case SECONDS:
return TimeUnit.MILLISECONDS.convert(period, TimeUnit.SECONDS);
case MINUTES:
return TimeUnit.MILLISECONDS.convert(period, TimeUnit.MINUTES);
case HOURS:
return TimeUnit.MILLISECONDS.convert(period, TimeUnit.HOURS);
case DAYS:
return TimeUnit.MILLISECONDS.convert(period, TimeUnit.DAYS);
case MILLISECONDS:
return period;
case MICROSECONDS:
return TimeUnit.MILLISECONDS.convert(period, TimeUnit.MICROSECONDS);
case NANOSECONDS:
return TimeUnit.MILLISECONDS.convert(period, TimeUnit.NANOSECONDS);
}
return period;
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
648b27f51f726687f12a4cd84a5ed1e9a22b6664 | cd8f4a2284573291d41bca061a09fee527e26061 | /src/serve_more.java | b684850f9070589d0a5edb3d8715772defb0a77c | [] | no_license | LefKok/Thesis | 06f432ce451cebde3023922fdf6626853cb94135 | 954d0ec8a93f395434dde597b6d2565a0d3c77d3 | refs/heads/master | 2020-03-30T06:20:22.760370 | 2015-06-16T10:53:49 | 2015-06-16T10:53:49 | 35,273,877 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,777 | java | /**
* This Method returns the experience the VE had with another VE for a service
* @param id the sensor
* @param service the service
* @return the trust level
*/
public synchronized double ask_experience(String id, String service) {
Application_struct f = friends.get(service);
if (f!=null) {
Followee_struct f1 = f.get_followee(id);
if (f1!=null){
return f1.return_trust();
}
}
return -0.1; //negative means no experience at all
}
/**
*
* @param s the service
* @param i the TTL
* @param id id of the requester so that i do not lie to myself when colluding
* @return
*/
public synchronized Outcome get_assistance(String s, int i,int id) {
Application_struct recommenders = friends.get("recommendation");
PriorityQueue<ComparableFriend> MyQueue=recommenders.rank_friends("assists");
while (!MyQueue.isEmpty() && outcome == null){
ComparableFriend temp = MyQueue.poll();
if ( temp.value > 0.5)
{
TemplateTRM_Sensor current = recommenders.get_followee(temp.id).Sensor;
Application_struct new_requiredService = current.get_app(s);
if (new_requiredService!=null){
outcome = new_requiredService.request_Service();
}if (i>0 && outcome==null) outcome = current.get_assistance(s, i-1,this.id);
}
if (outcome!=null){
recommenders.addNewAssist(temp.id,(MyOutcome)outcome);}
}else break;
}
return outcome;
}
/**
* This methods returns the actual service value
* @param service
* @return the satisfaction
*/
public synchronized double serve(String service) {
if(servicesGoodness2.get(service)!=null && this.isActive()){
double quality = servicesGoodness2.get(service);
return Math.round(10 * (quality)) / 10.0;}
else return -0.1;
}
| [
"kokoris.kogias.eleftherios@gmail.com"
] | kokoris.kogias.eleftherios@gmail.com |
52ffb877c5c915f2f3abe3e50184083289e556d9 | 00713344d7d0f471b5ae607079c328b12d969d5b | /DBConnection.java | 5841024801d05f1c2e8a313a814c67faea867a92 | [] | no_license | trassinfotek/WEB-MVC-using-Tomcat | fdc8a12e6355f7c3eac371fababd3e15c0795237 | 7d268fcad02a5e3fc9775c97dd1fde0ee64b8a47 | refs/heads/master | 2020-08-02T09:05:43.144290 | 2019-09-27T10:48:38 | 2019-09-27T10:48:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 754 | java | package com.nc.utils;
import java.sql.Connection;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class DBConnection {
static Connection con=null;
public static Connection getConnection(){
try{
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/TestDB");
con=ds.getConnection();
return con;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
} | [
"noreply@github.com"
] | noreply@github.com |
bd8a4a0481db4325b56ddd56e48925d5bfc08f8c | e3a23b7362bd9ba25ba99876a49694ea01400bb3 | /yuigwt/src/org/sgx/yuigwt/yui/node/NodeList.java | 0893b8f748a9eed6cd26d0861ce76b807b5f5659 | [] | no_license | cancerberoSgx/yuigwt | 1039ee216c528ba29f5bb6537d7e6d773fedfb61 | 2fd4cd39fc1dfe527742036d3427490748bbf24b | refs/heads/master | 2020-03-22T12:30:43.329425 | 2018-07-07T06:23:36 | 2018-07-07T06:23:36 | 140,044,515 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,083 | java | package org.sgx.yuigwt.yui.node;
import org.sgx.yuigwt.yui.util.SimpleCallback;
public class NodeList extends NodeBase {
protected NodeList(){}
/**
*
* @param l Arrays/NodeLists and/or values to concatenate to the resulting NodeList
* @return A new NodeList comprised of this NodeList joined with the input.
*/
public final native NodeList concat(NodeList l)/*-{
return concat(l);
}-*/;
public static interface NodeListIterator {
void next(Node n, int index, NodeList instance);
}
/**
* Applies the given function to each Node in the NodeList.
* @param iterator The function to apply. It receives 3 arguments: the current node instance, the node's index, and the NodeList instance
* @return self for method chaining
*/
public native final NodeList each(NodeListIterator iterator) /*-{
this.each($entry(function(n, index, instance){
return iterator.@org.sgx.yuigwt.yui.node.NodeList.NodeListIterator::next(Lorg/sgx/yuigwt/yui/node/Node;ILorg/sgx/yuigwt/yui/node/NodeList;)(n, index, instance);
}));
return this;
}-*/;
/**
* Retrieves the Node instance at the given index.
*/
public native final Node item(int index) /*-{
return this.item(index);
}-*/;
/**
* Makes each node visible. If the "transition" module is loaded, show optionally animates the showing of the node using either the default transition effect ('fadeIn'), or the given named effect.
* @param name A named Transition effect to use as the show effect.
* @param config Options to use with the transition.
* @param c An optional function to run after the transition completes.
* @return self for method chaining
*/
public native final NodeList show(String name, Transition config, SimpleCallback c) /*-{
var f = $entry(function(){
return c.@org.sgx.yuigwt.yui.util.SimpleCallback::call()();
});
return this.show(name, config, f);
}-*/;
/**
* Makes each node visible. If the "transition" module is loaded, show optionally animates the showing of the node using either the default transition effect ('fadeIn'), or the given named effect.
* @param name A named Transition effect to use as the show effect.
* @return self for method chaining
*/
public native final NodeList show(String name) /*-{
return this.show(name);
}-*/;
/**
* @return The first item in the NodeList.
*/
public native final Node shift() /*-{
return this.shift();
}-*/;
/**
* Returns the current number of items in the NodeList.
* @return
*/
public native final int size() /*-{
return this.size();
}-*/;
/**
*
* @param begin Zero-based index at which to begin extraction. As a negative index, start indicates an offset from the end of the sequence. slice(-2) extracts the second-to-last element and the last element in the sequence.
* @param end Zero-based index at which to end extraction. slice extracts up to but not including end. slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3). As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. If end is omitted, slice extracts to the end of the sequence.
* @return A new NodeList comprised of this NodeList joined with the input.
*/
public native final NodeList slice(int begin, int end) /*-{
return this.slice(begin, end);
}-*/;
/**
* Executes the function once for each node until a true value is returned.
* @param c he function to apply. It receives 3 arguments: the current node instance, the node's index, and the NodeList instance
* @return Whether or not the function returned true for any node.
*/
public native final boolean some(NodeListCallback c) /*-{
var f = $entry(function(n,i,nl){
return c.@org.sgx.yuigwt.yui.node.NodeListCallback::call(Lorg/sgx/yuigwt/yui/node/Node;ILorg/sgx/yuigwt/yui/node/NodeList;)(n,i,nl);
});
return this.some(f);
}-*/;
/**
*
* @param index Index at which to start changing the array. If negative, will begin that many elements from the end.
* @param howMany An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. In this case, you should specify at least one new element. If no howMany parameter is specified (second syntax above, which is a SpiderMonkey extension), all elements after index are removed. {Node | DOMNode| element1, ..., elementN The elements to add to the array. If you don't specify any elements, splice simply removes elements from the array.
* @return The element(s) removed.
*/
public native final NodeList splice(int index, int howMany) /*-{
return this.splice(index, howMany);
}-*/;
/**
* Returns the index of the node in the NodeList instance or -1 if the node isn't found.
* @param n the node to search for
* @return the index of the node value or -1 if not found
*/
public native final int indexOf(Node n) /*-{
return this.indexOf(n);
}-*/;
/**
* Determines if the instance is bound to any nodes
* @return Whether or not the NodeList is bound to any nodes
*/
public native final boolean isEmpty() /*-{
return this.isEmpty();
}-*/;
}
| [
"sebastigurin@gmail.com"
] | sebastigurin@gmail.com |
993b54b8cd2bdf2feea84a1264e9e7f2b2c6f070 | 6d038e23c1665cbdcb7ea23cf2cc64de6444baf3 | /target/test-classes/projects/basic/project/basic/src/main/java/it/pkg/security/exception/JwtTokenMissingException.java | 2c164a8093602d8f46486ef2a64e7b2ef78f2a8c | [] | no_license | udayanid/Fluorescent-Rest-archetype | 2f33f94fa3161b82bd94656ef66de47980f0bdd2 | 3e021ea140bf5a2149ddc28552c9f3e162cbe143 | refs/heads/master | 2022-07-10T09:04:46.818358 | 2020-05-18T21:02:37 | 2020-05-18T21:02:37 | 265,052,298 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 291 | java | package it.pkg.security.exception;
import org.springframework.security.core.AuthenticationException;
public class JwtTokenMissingException extends AuthenticationException {
private static final long serialVersionUID = 1L;
public JwtTokenMissingException(String msg) {
super(msg);
}
} | [
"udhayan.addon@gmail.com"
] | udhayan.addon@gmail.com |
25e8fd3bd566de76f6b15337af838625c37d984e | 472c0d86187f8ffcfab9e4859e1119670fc71b57 | /library/time-library/src/test/java/uk/gov/gchq/gaffer/time/function/ToTimeBucketStartTest.java | 184f93b8da1ccc3dd38a3391cd2577949d9fd36d | [
"Apache-2.0",
"LicenseRef-scancode-proprietary-license"
] | permissive | gchq/Gaffer | f90fabf9f13f586a0b4ccf42e88e700d46fc3524 | 8d3f4e848c3c899cb69a0c96dd730741a0ac8588 | refs/heads/develop | 2023-08-03T20:11:20.206214 | 2023-07-21T14:20:29 | 2023-07-21T14:20:29 | 47,973,088 | 669 | 221 | Apache-2.0 | 2023-09-14T20:41:57 | 2015-12-14T12:12:39 | Java | UTF-8 | Java | false | false | 2,652 | java | /*
* Copyright 2021 Crown Copyright
*
* 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 uk.gov.gchq.gaffer.time.function;
import org.junit.jupiter.api.Test;
import uk.gov.gchq.gaffer.jsonserialisation.JSONSerialiser;
import uk.gov.gchq.gaffer.time.CommonTimeUtil;
import uk.gov.gchq.koryphe.function.FunctionTest;
import java.io.IOException;
import java.time.Instant;
import static org.junit.jupiter.api.Assertions.assertEquals;
class ToTimeBucketStartTest extends FunctionTest<ToTimeBucketStart> {
private static final Long SECOND_TIMESTAMPS = Instant.now().getEpochSecond();
@Test
public void shouldCreateTimeBucketWithSingleTimeInIt() {
// Given
final ToTimeBucketStart toTimeBucketStart = new ToTimeBucketStart();
toTimeBucketStart.setBucket(CommonTimeUtil.TimeBucket.SECOND);
// When
Long result = toTimeBucketStart.apply(SECOND_TIMESTAMPS);
long expected = (((long) Math.ceil(SECOND_TIMESTAMPS)) / 1000) * 1000;
// Then
assertEquals(expected, result);
}
@Override
protected Class[] getExpectedSignatureInputClasses() {
return new Class[]{Long.class};
}
@Override
protected Class[] getExpectedSignatureOutputClasses() {
return new Class[]{Long.class};
}
@Test
@Override
public void shouldJsonSerialiseAndDeserialise() throws IOException {
// Given
final ToTimeBucketStart toTimeBucketStart =
new ToTimeBucketStart();
// When
final String json = new String(JSONSerialiser.serialise(toTimeBucketStart));
ToTimeBucketStart deserialisedToTimeBucketStart = JSONSerialiser.deserialise(json, ToTimeBucketStart.class);
// Then
assertEquals(toTimeBucketStart, deserialisedToTimeBucketStart);
assertEquals("{\"class\":\"uk.gov.gchq.gaffer.time.function.ToTimeBucketStart\"}", json);
}
@Override
protected ToTimeBucketStart getInstance() {
return new ToTimeBucketStart();
}
@Override
protected Iterable<ToTimeBucketStart> getDifferentInstancesOrNull() {
return null;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
8b0591e2301e9d69fa0d4da6ae2d0f377f2633a4 | f03eaf33d6afd2fb2084686334e1d0435345c6e0 | /app/src/main/java/com/example/ricardo/my_final_proyect/Adapter/GetPlayerAdapter.java | 889d8cedca25fd268e5a14a06af53f05066928d6 | [] | no_license | ricardovelazquezserna/Game2048 | 95639f152df8cdcfe27dd51a53f1fd4e9e95b886 | e79de6b04d3bc6df1cc7942a5328b678dbaddea6 | refs/heads/master | 2021-01-10T05:09:11.134128 | 2015-12-12T10:43:38 | 2015-12-12T10:43:38 | 46,635,115 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,881 | java | package com.example.ricardo.my_final_proyect.Adapter;
import java.util.ArrayList;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import com.example.ricardo.my_final_proyect.Player.GetPlayersActivity;
import com.example.ricardo.my_final_proyect.Player.Player;
import com.example.ricardo.my_final_proyect.R;
public class GetPlayerAdapter extends BaseAdapter implements OnClickListener {
private static final String debugTag = "GetPlayerAdapter";
private GetPlayersActivity activity;
private LayoutInflater layoutInflater;
private ArrayList<Player> playerArrayList;
public GetPlayerAdapter(GetPlayersActivity a, LayoutInflater l, ArrayList<Player> data) {
this.activity = a;
this.layoutInflater = l;
this.playerArrayList = data;
}
@Override
public int getCount() {
return this.playerArrayList.size();
}
@Override
public boolean areAllItemsEnabled() {
return true;
}
@Override
public Object getItem(int arg0) {
return null;
}
@Override
public long getItemId(int pos) {
return pos;
}
public static class ViewHolder
{
private TextView namePlayer,matricula,status;
private Button searchButton;
Player player;
}
@Override
public View getView( int pos, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = layoutInflater.inflate (R.layout.player_row_layout, parent, false);
holder.namePlayer = (TextView) convertView.findViewById(R.id.playernameTV);
holder.matricula = (TextView) convertView.findViewById(R.id.playernumberTV);
holder.status= (TextView) convertView.findViewById(R.id.playerstatusTV);
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
}
Player player = playerArrayList.get(pos);
holder.namePlayer.setText(player.getName());
holder.matricula.setText(player.getMatricula());
holder.status.setText(player.getStatus());
return convertView;
}
@Override
public void onClick(View v) {
ViewHolder holder = (ViewHolder) v.getTag();
if (v instanceof Button) {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
this.activity.startActivity(intent);
}
Log.d(debugTag, "OnClick pressed.");
}
}
| [
"ricardo.velazquez.serna@hotmail.com"
] | ricardo.velazquez.serna@hotmail.com |
11d4d8f19bae0c34952da1b9e281331a782823a2 | 4cb6c661824ce7e7a979562197a89003ca926f0c | /src/ph/edu/dlsu/ui/MenuVBox.java | b32127f420c74ff7e7ea40d13f26274064cd3a09 | [] | no_license | melvincabatuan/JavaFXPlayVideo | 131754ebc0687254ee42b07f0cfc9245d1139346 | 6ef1c6290391a4836641d010239812e0a1ff44ae | refs/heads/master | 2021-01-10T07:30:45.140014 | 2016-03-11T02:39:54 | 2016-03-11T02:39:54 | 53,633,745 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 579 | java | package ph.edu.dlsu.ui;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
/**
* Created by cobalt on 3/6/16.
*/
public class MenuVBox extends VBox {
public MenuVBox(CustomMenuItem... items) {
getChildren().add(createSeparator());
for (CustomMenuItem item : items) {
getChildren().addAll(item, createSeparator());
}
}
private Line createSeparator() {
Line sep = new Line();
sep.setEndX(240);
sep.setStroke(Color.DARKGREY);
return sep;
}
} | [
"melvincabatuan@gmail.com"
] | melvincabatuan@gmail.com |
0176ed3eaebc7cdeda236b6358d11a17aa00e80d | 5c9bb819911aa1fb994035bca04552e68a87761f | /src/main/java/com/commerce/dao/IDAO.java | 3701238b300d0b8ef29a0652683b4b53a4a79483 | [] | no_license | ktktktsdfsd/E-Commerce | d29520eccef2f553be613dccd30f14cb2ad14639 | 8c361e1f60f457956a75afb419940cdf67986cac | refs/heads/master | 2020-05-24T04:11:35.885521 | 2018-05-20T05:39:07 | 2018-05-20T05:39:07 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 385 | java | package com.commerce.dao;
import org.jinq.orm.stream.JinqStream;
import java.util.List;
interface IDAO<T> {
T get(Integer id);
T get(JinqStream.Where<T, Exception> where);
void insert(T entity);
void update(T entity);
void delete(T entity);
void delete(Integer id);
List<T> getList();
List<T> getList(JinqStream.Where<T, Exception> where);
}
| [
"furkan.isitan@bil.omu.edu.tr"
] | furkan.isitan@bil.omu.edu.tr |
a52bc98f7e3e9be700820288d5b9db03cab7b504 | d1c30a4fc86c7cfb73851602b3d10909040ba3c3 | /src/main/java/com/feng/common/IndexController.java | 1028af9a3d500e08de0cea1e311f1ffdf7e14277 | [] | no_license | qiuzhi/JFinal | 30968f1e33a78e9259e98e6dbd4dc03af03ee040 | 8f42eeadf500bc0c0f3d0cff6f98e2ce8f1907c8 | refs/heads/master | 2019-01-20T00:19:18.525045 | 2016-05-25T15:51:40 | 2016-05-25T15:51:40 | 59,667,386 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 287 | java | package com.feng.common;
import com.jfinal.core.Controller;
/**
* Created by Feng on 2016-5-25.
*/
public class IndexController extends Controller {
/**
* 默认跳转
*/
public void index() {
// renderText("hello,Yes");
render("index.ftl");
}
}
| [
"qiuyufeng@gmail.com"
] | qiuyufeng@gmail.com |
1b0a9d0bfb4e8a7affc4755564558fb4234a74fc | ef1386ef2913d670eadf6640602644f6423ce371 | /egnyte-android-sdk/src/main/java/com/egnyte/androidsdk/entities/UploadResult.java | ac3bb2a46b08510040d7ccbb6c75b6574799bca7 | [
"Apache-2.0"
] | permissive | mchernydev/egnyte-android-sdk | cd4d344503c75a4c163a0ef94ee09cba178eec0c | ffbfd44ee93d6b35b4554ea94ba5dee59431ef4c | refs/heads/master | 2020-03-27T22:16:16.795267 | 2017-01-12T16:05:11 | 2017-01-12T16:05:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 872 | java | package com.egnyte.androidsdk.entities;
import org.json.JSONException;
import org.json.JSONObject;
public class UploadResult {
/**
* SHA512 hash of uploaded file
*/
public final String checksum;
/**
* EntryId identifying version of uploaded file
*/
public final String entryId;
/**
* GroupId identifying uploaded file
*/
public final String groupId;
public UploadResult(String checksum, String entryId, String groupId) {
this.checksum = checksum;
this.entryId = entryId;
this.groupId = groupId;
}
public static UploadResult parse(JSONObject jsonObject) throws JSONException {
return new UploadResult(
jsonObject.getString("checksum"),
jsonObject.getString("entry_id"),
jsonObject.getString("group_id")
);
}
}
| [
"msikora@egnyte.com"
] | msikora@egnyte.com |
78410316d750a69c170d1712d06b407e295edb4f | 7e4aa61664557b9fcaef4117a42305c5f176120d | /workspace/Leetcode/src/leetcode/Replace_Words_648.java | 290d5b8ec87166ce4ed67ded1dc6cc787f06b009 | [] | no_license | Lucy18/leetcode | 21007fc1c3070d5fe3d8209fddaf87747c72b376 | 93d729d7363428434018caf832b82f72443d9e97 | refs/heads/master | 2021-01-20T00:23:52.951087 | 2018-05-06T12:50:47 | 2018-05-06T12:50:47 | 89,125,237 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 949 | java | package leetcode;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class Replace_Words_648 {
public String replaceWords(List<String> dict, String sentence) {
String result="";
HashSet<String> set=new HashSet<String>();
for(String s:dict){
set.add(s);
}
String[] words=sentence.split(" ");
for(int i=0;i<words.length;i++){
String word=words[i];
for(int j=1;j<=word.length()&&j<101;j++){
String subWord=word.substring(0,j);
if(set.contains(subWord)){
word=subWord;
break;
}
}
result+=word+" ";
}
return result.substring(0,result.length()-1);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Replace_Words_648 r=new Replace_Words_648();
List<String> dict=new ArrayList<String>();
dict.add("cat");dict.add("bat");dict.add("rat");
System.out.println(r.replaceWords(dict, "the cattle was rattled by the battery"));
}
}
| [
"916648359@qq.com"
] | 916648359@qq.com |
44e1c6d574a2727111e01ed69102e1e7245ea979 | 9e48130acb86b59d0b54f162fdd259505f1c1b3f | /src/main/java/_07_Others/controller/AddCommentsServlet.java | c122533caf0ba3439221ac66ab64a91b40a2904e | [] | no_license | Alaa0504/whattodrink_HB | e7d925af822986eb5bdcb9a702b488e40adf9892 | 656dc5c30e16111652451aa34b8e9c92564d839c | refs/heads/main | 2023-08-31T05:29:34.308107 | 2021-10-20T04:56:15 | 2021-10-20T04:56:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,174 | java | package _07_Others.controller;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import _01_Register.c_01_register.service.CustomerService;
import _01_Register.c_01_register.service.serviceImpl.CustomerServiceImpl;
import _03_ListDrinks.service.DrinkService;
import _03_ListDrinks.service.serviceImpl.DrinkServiceImpl;
import _04_ShoppingCart.model.ItemBean;
import _04_ShoppingCart.service.ItemService;
import _04_ShoppingCart.service.OrderService;
import _04_ShoppingCart.service.serviceImpl.ItemServiceImpl;
import _04_ShoppingCart.service.serviceImpl.OrderServiceImpl;
import _07_Others.model.CommentBean;
import _07_Others.service.CommentService;
import _07_Others.service.serviceImpl.CommentServiceImpl;
@MultipartConfig
@WebServlet("/AddCommentsServlet")
public class AddCommentsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ItemService itemService = new ItemServiceImpl();
String order_id = request.getParameter("order_id");
List<ItemBean> itemBeans = itemService.findByOrderId(order_id);
request.setAttribute("itemBeans", itemBeans);
RequestDispatcher rd = request.getRequestDispatcher("/_07_Others/c__07_others_review/review.jsp");
rd.forward(request, response);
return;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String dirPath = "c:/_JSP/workspace"
+ getServletContext().getContextPath()
+ "/src/main/webapp/images/comment";
File dir = new File(dirPath);
if (!dir.exists()) {
dir.mkdirs();
}
CustomerService customerService = new CustomerServiceImpl();
OrderService orderService = new OrderServiceImpl();
DrinkService drinkService = new DrinkServiceImpl();
CommentService commentService = new CommentServiceImpl();
for (int i = 0; i < request.getParameterValues("product_id").length; i++) {
CommentBean commentBean = new CommentBean();
commentBean.setCustomer_id(Integer.parseInt(request.getParameterValues("customer_id")[i]));
commentBean.setOrder_id(request.getParameterValues("order_id")[i]);
commentBean.setProduct_id(Integer.parseInt(request.getParameterValues("product_id")[i]));
commentBean.setStar(BigDecimal.valueOf(Double.parseDouble(request.getParameterValues("star")[i])));
if (!request.getParameterValues("comment")[i].isBlank()) {
commentBean.setFeedback(request.getParameterValues("comment")[i]);
}
commentBean.setComment_date(new Timestamp(System.currentTimeMillis()));
if (request.getParameterValues("upload")[i].equals("1")) {
System.out.println("第" + i + "筆有上傳圖片");
commentBean.setComment_picpath(dirPath.substring(dirPath.indexOf("images")) + "/" + request.getParameterValues("item_id")[i] + ".jpg");
commentBean.setComment_picname(request.getParameterValues("item_id")[i] + ".jpg");
}
commentBean.setCustomerBean(customerService.findByCustomerId(commentBean.getCustomer_id()));
commentBean.setOrderBean(orderService.findById(commentBean.getOrder_id()));
commentBean.setDrinkBean(drinkService.findById(commentBean.getProduct_id()));
commentService.save(commentBean);
}
//存評價照片至指定位置
Iterator<Part> pics = request.getParts().iterator();
int i = 0;
while (pics.hasNext()) {
Part pic = pics.next();
if (pic.getName().equals("photo[0]")) {
String fileName = dirPath + "/" + request.getParameterValues("item_id")[i] + ".jpg";
i++;
if (pic.getSubmittedFileName() != null) {
pic.write(fileName);
}
}
}
}
}
| [
"bachiest@gmail.com"
] | bachiest@gmail.com |
7df62bc01058b03c1062a2c54b77c32b73e03d9b | 675122400ebaa8e86412cebe1735c157676cd2c8 | /src/main/java/ap/edu/dao/academics/CourseSubjectsRepo.java | b534eb8644c89b9dc75c0a85d516563349d64980 | [] | no_license | rrotti1825/AcademiaOn24Feb | dc0b3d94bc0b645caf4e0fcb0bae3ad208ea37b8 | 21891064c8d226edda2e41f2601e1bc7c629239e | refs/heads/master | 2020-04-24T22:27:32.549070 | 2019-02-24T08:14:59 | 2019-02-24T08:14:59 | 172,312,682 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 290 | java | package ap.edu.dao.academics;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import ap.edu.entity.academia.CourseSubjects;
@Repository
public interface CourseSubjectsRepo extends JpaRepository<CourseSubjects, Long>{
}
//
| [
"c62941@txt.textron.com"
] | c62941@txt.textron.com |
1f642231de2cc3104b3af32e0653be19e2b82984 | 70dca6815c2157a2ae49d3c6f7ab3bad879adddc | /leetcode/java/5425.maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts.java | a7349d545a9321f0a6e40b4f2a875d6fc804cbd4 | [
"BSD-3-Clause"
] | permissive | phiysng/leetcode | 25229b829d2685f56ea3b58337136ebe7b810ca5 | a8ec1e598e92c2155f8abefa4c4bf5ce8c3838fa | refs/heads/master | 2023-03-03T08:30:19.677369 | 2023-02-19T10:32:17 | 2023-02-19T10:32:17 | 180,983,537 | 5 | 0 | BSD-3-Clause | 2019-12-03T10:24:18 | 2019-04-12T10:11:58 | C++ | UTF-8 | Java | false | false | 1,126 | java | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class Solution {
public int maxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) {
Arrays.sort(horizontalCuts);
Arrays.sort(verticalCuts);
// 可以尝试在上面两个数组增加0和h/w,从而可以简化下面的代码
List<Integer> hor = new ArrayList<>();
hor.add(horizontalCuts[0]);
List<Integer> ver = new ArrayList<>();
ver.add(verticalCuts[0]);
for (int i = 0; i < horizontalCuts.length - 1; i++) {
hor.add(horizontalCuts[i + 1] - horizontalCuts[i]);
}
hor.add(h - horizontalCuts[horizontalCuts.length - 1]);
for (int i = 0; i < verticalCuts.length - 1; i++) {
ver.add(verticalCuts[i + 1] - verticalCuts[i]);
}
ver.add(w - verticalCuts[verticalCuts.length - 1]);
long m1 = hor.stream().max(Integer::compareTo).get();
long m2 = ver.stream().max(Integer::compareTo).get();
int cast = (1000000000 + 7);
return (int) ((long) (m1) * ((long) m2) % cast);
}
}
| [
"wuyuanshou@protonmail.com"
] | wuyuanshou@protonmail.com |
7e94d62a6f0f108c0f97e522be5ff6b1d89d5432 | 6eb2ff022d27386e92dbec236531b0e8c48c3259 | /src/main/java/com/raczkowski/entity/transactions/Bank.java | 3ffb38bdaba8737f8566c8b274016ae676ca05e4 | [] | no_license | CodecoolGlobal/spring-hibernate-intro | 879c02907e8a81fca20d3614c5c32f15ae0e505b | 408c3be49f07097eb35ebb8bbfd65210e17b8e60 | refs/heads/master | 2022-12-27T17:17:14.589885 | 2020-10-16T20:50:35 | 2020-10-16T20:50:35 | 301,115,335 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 662 | java | package com.raczkowski.entity.transactions;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Bank {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public Bank() {
}
public Bank(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| [
"p.raczkowski@ocado.com"
] | p.raczkowski@ocado.com |
93361232bb1d93c6e5fd530fd641e17cad166d7f | f769dc15703b76844852a52e83346f058bcdefa1 | /app/src/main/java/in/ac/mnnit/sos/services/LocationDetailsHolder.java | 88924e5e0dbb339f293ae875667ef35c28af4c7e | [] | no_license | Sumintar/sos | 165ca6dd2b99548aadba04322980db62cf849a9a | 8cd7159cea05d2fce1ee41d004f644e5707cc983 | refs/heads/master | 2021-04-26T23:26:38.556613 | 2017-04-17T03:45:06 | 2017-04-17T03:45:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,961 | java | package in.ac.mnnit.sos.services;
import com.google.android.gms.maps.model.LatLng;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import in.ac.mnnit.sos.MainActivity;
/**
* Created by Banda Prashanth Yadav on 24/3/17.
*/
public class LocationDetailsHolder {
private LocationService locationService;
public static List<LatLng> points;
public static LatLng LATEST_LOCATION = null;
public static LatLng LAST_KNOWN_LOCATION = null;
public static String LAST_KNOWN_LOCATION_NAME = null;
public static String LATEST_LOCATION_NAME = null;
public LocationDetailsHolder() {
this.locationService = new LocationService(MainActivity.MAIN_ACTIVITY_CONTEXT);
}
public void addPoint(LatLng point){
if(points == null){
points = new ArrayList<>();
}
points.add(point);
// updateLatestLocationName();
}
public void updateLastKnownLocation(LatLng lastKnownLocation){
LAST_KNOWN_LOCATION = lastKnownLocation;
// updateLastLocationName();
}
public void updateLastLocationName(){
LAST_KNOWN_LOCATION_NAME = null;
try {
if(LAST_KNOWN_LOCATION != null)
LAST_KNOWN_LOCATION_NAME = locationService.getAddressFromLatLng(LAST_KNOWN_LOCATION);
} catch (IOException e) {
e.printStackTrace();
}
}
public void updateLatestLocationName(){
LATEST_LOCATION_NAME = null;
try {
if(LATEST_LOCATION != null)
LATEST_LOCATION_NAME = locationService.getAddressFromLatLng(LATEST_LOCATION);
} catch (IOException e) {
e.printStackTrace();
}
}
public LatLng getLastBestLocation(){
if(LATEST_LOCATION != null)
return LATEST_LOCATION;
else if(LAST_KNOWN_LOCATION != null)
return LAST_KNOWN_LOCATION;
else
return null;
}
}
| [
"prashanth1395@gmail.com"
] | prashanth1395@gmail.com |
1a478799a071e3073944e9393d2db87c44b80f91 | 587b82924439913b6e0018e6ac48f56f6206f58e | /WebSecutiryInSpring_version6/src/main/java/com/codegym/WebAppConfig/WebAppConfig.java | 806a7570ea33084554771cfc26a63a87b0985976 | [] | no_license | Vutienbka/SpringMVC | ec46181d6dbde18c15063f59bbf64ba671367c2e | 3edd0187ca2160812422fa135b296f248db984bc | refs/heads/master | 2022-12-21T13:49:40.514496 | 2020-04-30T16:06:02 | 2020-04-30T16:06:02 | 249,144,249 | 0 | 0 | null | 2022-12-16T10:52:42 | 2020-03-22T08:43:35 | CSS | UTF-8 | Java | false | false | 8,270 | java | package com.codegym.WebAppConfig;
//import com.codegym.Authentication.Authentication;
import com.codegym.Auditor.AuditorAwareImpl;
import com.codegym.Authorization.CustomSuccessHandler;
import com.codegym.Authentication.Authentication;
import com.codegym.Service.AdminService.AdminService;
import com.codegym.Service.AdminService.IAdminService;
import com.codegym.Service.BookService.BookService;
import com.codegym.Service.BookService.IBookService;
import com.codegym.Service.CategoriesService.CategoriesService;
import com.codegym.Service.CategoriesService.ICategoriesService;
import com.codegym.Service.RoleService.IRoleService;
import com.codegym.Service.RoleService.RoleService;
import com.codegym.Service.UserService.IUserService;
import com.codegym.Service.UserService.UserService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Locale;
import java.util.Properties;
@Configuration
@EnableWebMvc
@EnableTransactionManagement
@ComponentScan("com.codegym.Controller")
@EnableJpaRepositories("com.codegym.Repository")
@EnableWebSecurity
public class WebAppConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {
ApplicationContext applicationContext;
@Autowired
Environment environment;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/JQuery/**")
.addResourceLocations("file:/home/vutienbka/Downloads/CustomerManageJPARepository/src/main/resources/JQuery/");
}
// ---------------------------------------------------------
@Bean
MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("message");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
interceptor.setParamName("lang");
registry.addInterceptor(interceptor);
}
@Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver localeResolver = new SessionLocaleResolver();
localeResolver.setDefaultLocale(new Locale("en"));
return localeResolver;
}
//-----------------------------------------------------------
@Bean
public SpringResourceTemplateResolver templateResolver() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(this.applicationContext);
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
// templateResolver.setCharacterEncoding("UTF-8");
return templateResolver;
}
@Bean
public TemplateEngine templateEngine() {
TemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.addDialect(new SpringSecurityDialect());
return templateEngine;
}
@Bean
public ThymeleafViewResolver viewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setCharacterEncoding("UTF-8");
return viewResolver;
}
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/BookStoreCaseStudy");
dataSource.setUsername("root");
dataSource.setPassword("123456");
return dataSource;
}
@Bean
@Qualifier(value = "entityManager")
public EntityManager entityManager(EntityManagerFactory entityManagerFactory) {
return entityManagerFactory.createEntityManager();
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource());
emf.setPackagesToScan(new String[]{"com.codegym.Entity"});
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
emf.setJpaVendorAdapter(vendorAdapter);
emf.setJpaProperties(additionalProperties());
return emf;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
private Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "update");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return properties;
}
@Bean
IAdminService getAdminService(){
return new AdminService();
}
@Bean
IUserService getUserService(){
return new UserService();
}
@Bean
IRoleService getRoleService(){
return new RoleService();
}
@Bean
IBookService getBookService(){
return new BookService();
}
@Bean
ICategoriesService getCategoriesService(){
return new CategoriesService();
}
@Bean
Authentication getAuthentication(){
return new Authentication();
}
@Bean
CustomSuccessHandler customSuccessHandler(){
return new CustomSuccessHandler();
}
@Bean
public AuditorAwareImpl getAuditorAware(){
return new AuditorAwareImpl();
}
} | [
"vutienbka@gmail.com"
] | vutienbka@gmail.com |
7d4940a30829abcbfb59e233d936c7938819f5e9 | 3bde04cafba6e24f1ab4b8d658d0fa96cee3b667 | /src/test/java/it/polito/ezshop/integrationTests/UC2Scenarios.java | e83180fdfafbf4efa7450b1415398b190def6192 | [] | no_license | RiccardoGracis/se1-project | 4743e106ca81935cc65944dbe69da7d0e1db79e4 | fc83d22cb90ebb58123d060e35395b4cca37abcc | refs/heads/main | 2023-08-23T00:06:12.325828 | 2021-11-05T10:42:50 | 2021-11-05T10:42:50 | 424,904,762 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,063 | java | package it.polito.ezshop.integrationTests;
import org.junit.Test;
import static org.junit.Assert.*;
import java.sql.SQLException;
import it.polito.ezshop.data.EZShop;
import it.polito.ezshop.data.EZShopInterface;
import it.polito.ezshop.data.UserImpl;
import it.polito.ezshop.exceptions.*;
/*** UC2: Manage users and rights ***/
public class UC2Scenarios {
/*** Scenario 2-1: create user and define rights ***/
@Test
public void testScenario2_1() throws InvalidUserIdException, InvalidPasswordException, InvalidRoleException,
UnauthorizedException, InvalidUsernameException, SQLException {
EZShopInterface ezShop = new it.polito.ezshop.data.EZShop();
// Preconditions
((EZShop) ezShop).db.deleteEntireDB();
((EZShop) ezShop).db.openConnection();
((EZShop) ezShop).db.createUserTable();
((EZShop) ezShop).db.closeConnection();
((EZShop) ezShop).deleteAllUsers();
ezShop.createUser("admin", "admin", "Administrator");
ezShop.login("admin", "admin");
// Steps
int id = ezShop.createUser("u1", "pwd1", "Cashier");
assertEquals(ezShop.getUser(id).getId(), (Integer) id);
assertEquals(ezShop.getUser(id).getUsername(), "u1");
assertEquals(ezShop.getUser(id).getPassword(), "pwd1");
assertEquals(ezShop.getUser(id).getRole(), "Cashier");
ezShop.updateUserRights(id, "ShopManager");
assertEquals(ezShop.getUser(id).getRole(), "ShopManager");
// Postconditions
assertNotNull(ezShop.getUser(id));
}
/*** Scenario 2-2: delete user ***/
@Test
public void testScenario2_2() throws SQLException, InvalidUsernameException, InvalidPasswordException,
InvalidRoleException, InvalidUserIdException, UnauthorizedException {
EZShopInterface ezShop = new it.polito.ezshop.data.EZShop();
// Preconditions
((EZShop) ezShop).db.deleteEntireDB();
((EZShop) ezShop).db.openConnection();
((EZShop) ezShop).db.createUserTable();
((EZShop) ezShop).db.closeConnection();
((EZShop) ezShop).deleteAllUsers();
ezShop.createUser("admin", "admin", "Administrator");
ezShop.login("admin", "admin");
int id = ezShop.createUser("u1", "pwd1", "Cashier");
// Steps
boolean res = ezShop.deleteUser(id);
// PostCondition
assertTrue(res);
assertNull(ezShop.getUser(id));
}
/*** Scenario 2-3: modify user rights ***/
@Test
public void testScenario2_3() throws SQLException, InvalidUsernameException, InvalidPasswordException,
InvalidRoleException, InvalidUserIdException, UnauthorizedException {
EZShopInterface ezShop = new it.polito.ezshop.data.EZShop();
// Preconditions
((EZShop) ezShop).db.deleteEntireDB();
((EZShop) ezShop).db.openConnection();
((EZShop) ezShop).db.createUserTable();
((EZShop) ezShop).db.closeConnection();
((EZShop) ezShop).deleteAllUsers();
ezShop.createUser("admin", "admin", "Administrator");
ezShop.login("admin", "admin");
int id = ezShop.createUser("u1", "pwd1", "Cashier");
// Steps
boolean res = ezShop.updateUserRights(id, "ShopManager");
// PostCondition
assertTrue(res);
assertTrue(((UserImpl) ezShop.getUser(id)).isShopManager());
}
}
| [
"s287961@studenti.polito.it"
] | s287961@studenti.polito.it |
64696f5d64b28d5dc46db50c312be338db354925 | 349c6644fb1fe84334b432c49292f44c14bce847 | /src/main/sources/com/yoparty/bean/ActivityExample.java | dd801d92f473b4328b2814214eeed03843930967 | [] | no_license | wdfwolf3/yopartynet | 6e79f7cbfa0f02e33d398bb56ccc98092fa77e6a | c6c32869797989a85656d3653da4c7bfe38f3cb3 | refs/heads/master | 2021-01-19T16:59:42.957367 | 2017-08-22T07:04:40 | 2017-08-22T07:04:40 | 101,032,280 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 52,273 | java | package com.yoparty.bean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class ActivityExample implements Serializable {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public ActivityExample() {
oredCriteria = new ArrayList<Criteria>();
}
public String getOrderByClause() {
return orderByClause;
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public boolean isDistinct() {
return distinct;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria implements Serializable {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Integer value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Integer value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Integer value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Integer> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Integer> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andTitleIsNull() {
addCriterion("title is null");
return (Criteria) this;
}
public Criteria andTitleIsNotNull() {
addCriterion("title is not null");
return (Criteria) this;
}
public Criteria andTitleEqualTo(String value) {
addCriterion("title =", value, "title");
return (Criteria) this;
}
public Criteria andTitleNotEqualTo(String value) {
addCriterion("title <>", value, "title");
return (Criteria) this;
}
public Criteria andTitleGreaterThan(String value) {
addCriterion("title >", value, "title");
return (Criteria) this;
}
public Criteria andTitleGreaterThanOrEqualTo(String value) {
addCriterion("title >=", value, "title");
return (Criteria) this;
}
public Criteria andTitleLessThan(String value) {
addCriterion("title <", value, "title");
return (Criteria) this;
}
public Criteria andTitleLessThanOrEqualTo(String value) {
addCriterion("title <=", value, "title");
return (Criteria) this;
}
public Criteria andTitleLike(String value) {
addCriterion("title like", value, "title");
return (Criteria) this;
}
public Criteria andTitleNotLike(String value) {
addCriterion("title not like", value, "title");
return (Criteria) this;
}
public Criteria andTitleIn(List<String> values) {
addCriterion("title in", values, "title");
return (Criteria) this;
}
public Criteria andTitleNotIn(List<String> values) {
addCriterion("title not in", values, "title");
return (Criteria) this;
}
public Criteria andTitleBetween(String value1, String value2) {
addCriterion("title between", value1, value2, "title");
return (Criteria) this;
}
public Criteria andTitleNotBetween(String value1, String value2) {
addCriterion("title not between", value1, value2, "title");
return (Criteria) this;
}
public Criteria andStartTimeIsNull() {
addCriterion("start_time is null");
return (Criteria) this;
}
public Criteria andStartTimeIsNotNull() {
addCriterion("start_time is not null");
return (Criteria) this;
}
public Criteria andStartTimeEqualTo(String value) {
addCriterion("start_time =", value, "startTime");
return (Criteria) this;
}
public Criteria andStartTimeNotEqualTo(String value) {
addCriterion("start_time <>", value, "startTime");
return (Criteria) this;
}
public Criteria andStartTimeGreaterThan(String value) {
addCriterion("start_time >", value, "startTime");
return (Criteria) this;
}
public Criteria andStartTimeGreaterThanOrEqualTo(String value) {
addCriterion("start_time >=", value, "startTime");
return (Criteria) this;
}
public Criteria andStartTimeLessThan(String value) {
addCriterion("start_time <", value, "startTime");
return (Criteria) this;
}
public Criteria andStartTimeLessThanOrEqualTo(String value) {
addCriterion("start_time <=", value, "startTime");
return (Criteria) this;
}
public Criteria andStartTimeLike(String value) {
addCriterion("start_time like", value, "startTime");
return (Criteria) this;
}
public Criteria andStartTimeNotLike(String value) {
addCriterion("start_time not like", value, "startTime");
return (Criteria) this;
}
public Criteria andStartTimeIn(List<String> values) {
addCriterion("start_time in", values, "startTime");
return (Criteria) this;
}
public Criteria andStartTimeNotIn(List<String> values) {
addCriterion("start_time not in", values, "startTime");
return (Criteria) this;
}
public Criteria andStartTimeBetween(String value1, String value2) {
addCriterion("start_time between", value1, value2, "startTime");
return (Criteria) this;
}
public Criteria andStartTimeNotBetween(String value1, String value2) {
addCriterion("start_time not between", value1, value2, "startTime");
return (Criteria) this;
}
public Criteria andEndTimeIsNull() {
addCriterion("end_time is null");
return (Criteria) this;
}
public Criteria andEndTimeIsNotNull() {
addCriterion("end_time is not null");
return (Criteria) this;
}
public Criteria andEndTimeEqualTo(String value) {
addCriterion("end_time =", value, "endTime");
return (Criteria) this;
}
public Criteria andEndTimeNotEqualTo(String value) {
addCriterion("end_time <>", value, "endTime");
return (Criteria) this;
}
public Criteria andEndTimeGreaterThan(String value) {
addCriterion("end_time >", value, "endTime");
return (Criteria) this;
}
public Criteria andEndTimeGreaterThanOrEqualTo(String value) {
addCriterion("end_time >=", value, "endTime");
return (Criteria) this;
}
public Criteria andEndTimeLessThan(String value) {
addCriterion("end_time <", value, "endTime");
return (Criteria) this;
}
public Criteria andEndTimeLessThanOrEqualTo(String value) {
addCriterion("end_time <=", value, "endTime");
return (Criteria) this;
}
public Criteria andEndTimeLike(String value) {
addCriterion("end_time like", value, "endTime");
return (Criteria) this;
}
public Criteria andEndTimeNotLike(String value) {
addCriterion("end_time not like", value, "endTime");
return (Criteria) this;
}
public Criteria andEndTimeIn(List<String> values) {
addCriterion("end_time in", values, "endTime");
return (Criteria) this;
}
public Criteria andEndTimeNotIn(List<String> values) {
addCriterion("end_time not in", values, "endTime");
return (Criteria) this;
}
public Criteria andEndTimeBetween(String value1, String value2) {
addCriterion("end_time between", value1, value2, "endTime");
return (Criteria) this;
}
public Criteria andEndTimeNotBetween(String value1, String value2) {
addCriterion("end_time not between", value1, value2, "endTime");
return (Criteria) this;
}
public Criteria andSubmitDateIsNull() {
addCriterion("submit_date is null");
return (Criteria) this;
}
public Criteria andSubmitDateIsNotNull() {
addCriterion("submit_date is not null");
return (Criteria) this;
}
public Criteria andSubmitDateEqualTo(String value) {
addCriterion("submit_date =", value, "submitDate");
return (Criteria) this;
}
public Criteria andSubmitDateNotEqualTo(String value) {
addCriterion("submit_date <>", value, "submitDate");
return (Criteria) this;
}
public Criteria andSubmitDateGreaterThan(String value) {
addCriterion("submit_date >", value, "submitDate");
return (Criteria) this;
}
public Criteria andSubmitDateGreaterThanOrEqualTo(String value) {
addCriterion("submit_date >=", value, "submitDate");
return (Criteria) this;
}
public Criteria andSubmitDateLessThan(String value) {
addCriterion("submit_date <", value, "submitDate");
return (Criteria) this;
}
public Criteria andSubmitDateLessThanOrEqualTo(String value) {
addCriterion("submit_date <=", value, "submitDate");
return (Criteria) this;
}
public Criteria andSubmitDateLike(String value) {
addCriterion("submit_date like", value, "submitDate");
return (Criteria) this;
}
public Criteria andSubmitDateNotLike(String value) {
addCriterion("submit_date not like", value, "submitDate");
return (Criteria) this;
}
public Criteria andSubmitDateIn(List<String> values) {
addCriterion("submit_date in", values, "submitDate");
return (Criteria) this;
}
public Criteria andSubmitDateNotIn(List<String> values) {
addCriterion("submit_date not in", values, "submitDate");
return (Criteria) this;
}
public Criteria andSubmitDateBetween(String value1, String value2) {
addCriterion("submit_date between", value1, value2, "submitDate");
return (Criteria) this;
}
public Criteria andSubmitDateNotBetween(String value1, String value2) {
addCriterion("submit_date not between", value1, value2, "submitDate");
return (Criteria) this;
}
public Criteria andLeaderNameIsNull() {
addCriterion("leader_name is null");
return (Criteria) this;
}
public Criteria andLeaderNameIsNotNull() {
addCriterion("leader_name is not null");
return (Criteria) this;
}
public Criteria andLeaderNameEqualTo(String value) {
addCriterion("leader_name =", value, "leaderName");
return (Criteria) this;
}
public Criteria andLeaderNameNotEqualTo(String value) {
addCriterion("leader_name <>", value, "leaderName");
return (Criteria) this;
}
public Criteria andLeaderNameGreaterThan(String value) {
addCriterion("leader_name >", value, "leaderName");
return (Criteria) this;
}
public Criteria andLeaderNameGreaterThanOrEqualTo(String value) {
addCriterion("leader_name >=", value, "leaderName");
return (Criteria) this;
}
public Criteria andLeaderNameLessThan(String value) {
addCriterion("leader_name <", value, "leaderName");
return (Criteria) this;
}
public Criteria andLeaderNameLessThanOrEqualTo(String value) {
addCriterion("leader_name <=", value, "leaderName");
return (Criteria) this;
}
public Criteria andLeaderNameLike(String value) {
addCriterion("leader_name like", value, "leaderName");
return (Criteria) this;
}
public Criteria andLeaderNameNotLike(String value) {
addCriterion("leader_name not like", value, "leaderName");
return (Criteria) this;
}
public Criteria andLeaderNameIn(List<String> values) {
addCriterion("leader_name in", values, "leaderName");
return (Criteria) this;
}
public Criteria andLeaderNameNotIn(List<String> values) {
addCriterion("leader_name not in", values, "leaderName");
return (Criteria) this;
}
public Criteria andLeaderNameBetween(String value1, String value2) {
addCriterion("leader_name between", value1, value2, "leaderName");
return (Criteria) this;
}
public Criteria andLeaderNameNotBetween(String value1, String value2) {
addCriterion("leader_name not between", value1, value2, "leaderName");
return (Criteria) this;
}
public Criteria andType1IsNull() {
addCriterion("type1 is null");
return (Criteria) this;
}
public Criteria andType1IsNotNull() {
addCriterion("type1 is not null");
return (Criteria) this;
}
public Criteria andType1EqualTo(String value) {
addCriterion("type1 =", value, "type1");
return (Criteria) this;
}
public Criteria andType1NotEqualTo(String value) {
addCriterion("type1 <>", value, "type1");
return (Criteria) this;
}
public Criteria andType1GreaterThan(String value) {
addCriterion("type1 >", value, "type1");
return (Criteria) this;
}
public Criteria andType1GreaterThanOrEqualTo(String value) {
addCriterion("type1 >=", value, "type1");
return (Criteria) this;
}
public Criteria andType1LessThan(String value) {
addCriterion("type1 <", value, "type1");
return (Criteria) this;
}
public Criteria andType1LessThanOrEqualTo(String value) {
addCriterion("type1 <=", value, "type1");
return (Criteria) this;
}
public Criteria andType1Like(String value) {
addCriterion("type1 like", value, "type1");
return (Criteria) this;
}
public Criteria andType1NotLike(String value) {
addCriterion("type1 not like", value, "type1");
return (Criteria) this;
}
public Criteria andType1In(List<String> values) {
addCriterion("type1 in", values, "type1");
return (Criteria) this;
}
public Criteria andType1NotIn(List<String> values) {
addCriterion("type1 not in", values, "type1");
return (Criteria) this;
}
public Criteria andType1Between(String value1, String value2) {
addCriterion("type1 between", value1, value2, "type1");
return (Criteria) this;
}
public Criteria andType1NotBetween(String value1, String value2) {
addCriterion("type1 not between", value1, value2, "type1");
return (Criteria) this;
}
public Criteria andType2IsNull() {
addCriterion("type2 is null");
return (Criteria) this;
}
public Criteria andType2IsNotNull() {
addCriterion("type2 is not null");
return (Criteria) this;
}
public Criteria andType2EqualTo(String value) {
addCriterion("type2 =", value, "type2");
return (Criteria) this;
}
public Criteria andType2NotEqualTo(String value) {
addCriterion("type2 <>", value, "type2");
return (Criteria) this;
}
public Criteria andType2GreaterThan(String value) {
addCriterion("type2 >", value, "type2");
return (Criteria) this;
}
public Criteria andType2GreaterThanOrEqualTo(String value) {
addCriterion("type2 >=", value, "type2");
return (Criteria) this;
}
public Criteria andType2LessThan(String value) {
addCriterion("type2 <", value, "type2");
return (Criteria) this;
}
public Criteria andType2LessThanOrEqualTo(String value) {
addCriterion("type2 <=", value, "type2");
return (Criteria) this;
}
public Criteria andType2Like(String value) {
addCriterion("type2 like", value, "type2");
return (Criteria) this;
}
public Criteria andType2NotLike(String value) {
addCriterion("type2 not like", value, "type2");
return (Criteria) this;
}
public Criteria andType2In(List<String> values) {
addCriterion("type2 in", values, "type2");
return (Criteria) this;
}
public Criteria andType2NotIn(List<String> values) {
addCriterion("type2 not in", values, "type2");
return (Criteria) this;
}
public Criteria andType2Between(String value1, String value2) {
addCriterion("type2 between", value1, value2, "type2");
return (Criteria) this;
}
public Criteria andType2NotBetween(String value1, String value2) {
addCriterion("type2 not between", value1, value2, "type2");
return (Criteria) this;
}
public Criteria andType3IsNull() {
addCriterion("type3 is null");
return (Criteria) this;
}
public Criteria andType3IsNotNull() {
addCriterion("type3 is not null");
return (Criteria) this;
}
public Criteria andType3EqualTo(String value) {
addCriterion("type3 =", value, "type3");
return (Criteria) this;
}
public Criteria andType3NotEqualTo(String value) {
addCriterion("type3 <>", value, "type3");
return (Criteria) this;
}
public Criteria andType3GreaterThan(String value) {
addCriterion("type3 >", value, "type3");
return (Criteria) this;
}
public Criteria andType3GreaterThanOrEqualTo(String value) {
addCriterion("type3 >=", value, "type3");
return (Criteria) this;
}
public Criteria andType3LessThan(String value) {
addCriterion("type3 <", value, "type3");
return (Criteria) this;
}
public Criteria andType3LessThanOrEqualTo(String value) {
addCriterion("type3 <=", value, "type3");
return (Criteria) this;
}
public Criteria andType3Like(String value) {
addCriterion("type3 like", value, "type3");
return (Criteria) this;
}
public Criteria andType3NotLike(String value) {
addCriterion("type3 not like", value, "type3");
return (Criteria) this;
}
public Criteria andType3In(List<String> values) {
addCriterion("type3 in", values, "type3");
return (Criteria) this;
}
public Criteria andType3NotIn(List<String> values) {
addCriterion("type3 not in", values, "type3");
return (Criteria) this;
}
public Criteria andType3Between(String value1, String value2) {
addCriterion("type3 between", value1, value2, "type3");
return (Criteria) this;
}
public Criteria andType3NotBetween(String value1, String value2) {
addCriterion("type3 not between", value1, value2, "type3");
return (Criteria) this;
}
public Criteria andPriceIsNull() {
addCriterion("price is null");
return (Criteria) this;
}
public Criteria andPriceIsNotNull() {
addCriterion("price is not null");
return (Criteria) this;
}
public Criteria andPriceEqualTo(Short value) {
addCriterion("price =", value, "price");
return (Criteria) this;
}
public Criteria andPriceNotEqualTo(Short value) {
addCriterion("price <>", value, "price");
return (Criteria) this;
}
public Criteria andPriceGreaterThan(Short value) {
addCriterion("price >", value, "price");
return (Criteria) this;
}
public Criteria andPriceGreaterThanOrEqualTo(Short value) {
addCriterion("price >=", value, "price");
return (Criteria) this;
}
public Criteria andPriceLessThan(Short value) {
addCriterion("price <", value, "price");
return (Criteria) this;
}
public Criteria andPriceLessThanOrEqualTo(Short value) {
addCriterion("price <=", value, "price");
return (Criteria) this;
}
public Criteria andPriceIn(List<Short> values) {
addCriterion("price in", values, "price");
return (Criteria) this;
}
public Criteria andPriceNotIn(List<Short> values) {
addCriterion("price not in", values, "price");
return (Criteria) this;
}
public Criteria andPriceBetween(Short value1, Short value2) {
addCriterion("price between", value1, value2, "price");
return (Criteria) this;
}
public Criteria andPriceNotBetween(Short value1, Short value2) {
addCriterion("price not between", value1, value2, "price");
return (Criteria) this;
}
public Criteria andOriginIsNull() {
addCriterion("origin is null");
return (Criteria) this;
}
public Criteria andOriginIsNotNull() {
addCriterion("origin is not null");
return (Criteria) this;
}
public Criteria andOriginEqualTo(String value) {
addCriterion("origin =", value, "origin");
return (Criteria) this;
}
public Criteria andOriginNotEqualTo(String value) {
addCriterion("origin <>", value, "origin");
return (Criteria) this;
}
public Criteria andOriginGreaterThan(String value) {
addCriterion("origin >", value, "origin");
return (Criteria) this;
}
public Criteria andOriginGreaterThanOrEqualTo(String value) {
addCriterion("origin >=", value, "origin");
return (Criteria) this;
}
public Criteria andOriginLessThan(String value) {
addCriterion("origin <", value, "origin");
return (Criteria) this;
}
public Criteria andOriginLessThanOrEqualTo(String value) {
addCriterion("origin <=", value, "origin");
return (Criteria) this;
}
public Criteria andOriginLike(String value) {
addCriterion("origin like", value, "origin");
return (Criteria) this;
}
public Criteria andOriginNotLike(String value) {
addCriterion("origin not like", value, "origin");
return (Criteria) this;
}
public Criteria andOriginIn(List<String> values) {
addCriterion("origin in", values, "origin");
return (Criteria) this;
}
public Criteria andOriginNotIn(List<String> values) {
addCriterion("origin not in", values, "origin");
return (Criteria) this;
}
public Criteria andOriginBetween(String value1, String value2) {
addCriterion("origin between", value1, value2, "origin");
return (Criteria) this;
}
public Criteria andOriginNotBetween(String value1, String value2) {
addCriterion("origin not between", value1, value2, "origin");
return (Criteria) this;
}
public Criteria andDestinationIsNull() {
addCriterion("destination is null");
return (Criteria) this;
}
public Criteria andDestinationIsNotNull() {
addCriterion("destination is not null");
return (Criteria) this;
}
public Criteria andDestinationEqualTo(String value) {
addCriterion("destination =", value, "destination");
return (Criteria) this;
}
public Criteria andDestinationNotEqualTo(String value) {
addCriterion("destination <>", value, "destination");
return (Criteria) this;
}
public Criteria andDestinationGreaterThan(String value) {
addCriterion("destination >", value, "destination");
return (Criteria) this;
}
public Criteria andDestinationGreaterThanOrEqualTo(String value) {
addCriterion("destination >=", value, "destination");
return (Criteria) this;
}
public Criteria andDestinationLessThan(String value) {
addCriterion("destination <", value, "destination");
return (Criteria) this;
}
public Criteria andDestinationLessThanOrEqualTo(String value) {
addCriterion("destination <=", value, "destination");
return (Criteria) this;
}
public Criteria andDestinationLike(String value) {
addCriterion("destination like", value, "destination");
return (Criteria) this;
}
public Criteria andDestinationNotLike(String value) {
addCriterion("destination not like", value, "destination");
return (Criteria) this;
}
public Criteria andDestinationIn(List<String> values) {
addCriterion("destination in", values, "destination");
return (Criteria) this;
}
public Criteria andDestinationNotIn(List<String> values) {
addCriterion("destination not in", values, "destination");
return (Criteria) this;
}
public Criteria andDestinationBetween(String value1, String value2) {
addCriterion("destination between", value1, value2, "destination");
return (Criteria) this;
}
public Criteria andDestinationNotBetween(String value1, String value2) {
addCriterion("destination not between", value1, value2, "destination");
return (Criteria) this;
}
public Criteria andNumberIsNull() {
addCriterion("number is null");
return (Criteria) this;
}
public Criteria andNumberIsNotNull() {
addCriterion("number is not null");
return (Criteria) this;
}
public Criteria andNumberEqualTo(Short value) {
addCriterion("number =", value, "number");
return (Criteria) this;
}
public Criteria andNumberNotEqualTo(Short value) {
addCriterion("number <>", value, "number");
return (Criteria) this;
}
public Criteria andNumberGreaterThan(Short value) {
addCriterion("number >", value, "number");
return (Criteria) this;
}
public Criteria andNumberGreaterThanOrEqualTo(Short value) {
addCriterion("number >=", value, "number");
return (Criteria) this;
}
public Criteria andNumberLessThan(Short value) {
addCriterion("number <", value, "number");
return (Criteria) this;
}
public Criteria andNumberLessThanOrEqualTo(Short value) {
addCriterion("number <=", value, "number");
return (Criteria) this;
}
public Criteria andNumberIn(List<Short> values) {
addCriterion("number in", values, "number");
return (Criteria) this;
}
public Criteria andNumberNotIn(List<Short> values) {
addCriterion("number not in", values, "number");
return (Criteria) this;
}
public Criteria andNumberBetween(Short value1, Short value2) {
addCriterion("number between", value1, value2, "number");
return (Criteria) this;
}
public Criteria andNumberNotBetween(Short value1, Short value2) {
addCriterion("number not between", value1, value2, "number");
return (Criteria) this;
}
public Criteria andSignupNumberIsNull() {
addCriterion("signup_number is null");
return (Criteria) this;
}
public Criteria andSignupNumberIsNotNull() {
addCriterion("signup_number is not null");
return (Criteria) this;
}
public Criteria andSignupNumberEqualTo(Short value) {
addCriterion("signup_number =", value, "signupNumber");
return (Criteria) this;
}
public Criteria andSignupNumberNotEqualTo(Short value) {
addCriterion("signup_number <>", value, "signupNumber");
return (Criteria) this;
}
public Criteria andSignupNumberGreaterThan(Short value) {
addCriterion("signup_number >", value, "signupNumber");
return (Criteria) this;
}
public Criteria andSignupNumberGreaterThanOrEqualTo(Short value) {
addCriterion("signup_number >=", value, "signupNumber");
return (Criteria) this;
}
public Criteria andSignupNumberLessThan(Short value) {
addCriterion("signup_number <", value, "signupNumber");
return (Criteria) this;
}
public Criteria andSignupNumberLessThanOrEqualTo(Short value) {
addCriterion("signup_number <=", value, "signupNumber");
return (Criteria) this;
}
public Criteria andSignupNumberIn(List<Short> values) {
addCriterion("signup_number in", values, "signupNumber");
return (Criteria) this;
}
public Criteria andSignupNumberNotIn(List<Short> values) {
addCriterion("signup_number not in", values, "signupNumber");
return (Criteria) this;
}
public Criteria andSignupNumberBetween(Short value1, Short value2) {
addCriterion("signup_number between", value1, value2, "signupNumber");
return (Criteria) this;
}
public Criteria andSignupNumberNotBetween(Short value1, Short value2) {
addCriterion("signup_number not between", value1, value2, "signupNumber");
return (Criteria) this;
}
public Criteria andStatusIsNull() {
addCriterion("status is null");
return (Criteria) this;
}
public Criteria andStatusIsNotNull() {
addCriterion("status is not null");
return (Criteria) this;
}
public Criteria andStatusEqualTo(Byte value) {
addCriterion("status =", value, "status");
return (Criteria) this;
}
public Criteria andStatusNotEqualTo(Byte value) {
addCriterion("status <>", value, "status");
return (Criteria) this;
}
public Criteria andStatusGreaterThan(Byte value) {
addCriterion("status >", value, "status");
return (Criteria) this;
}
public Criteria andStatusGreaterThanOrEqualTo(Byte value) {
addCriterion("status >=", value, "status");
return (Criteria) this;
}
public Criteria andStatusLessThan(Byte value) {
addCriterion("status <", value, "status");
return (Criteria) this;
}
public Criteria andStatusLessThanOrEqualTo(Byte value) {
addCriterion("status <=", value, "status");
return (Criteria) this;
}
public Criteria andStatusIn(List<Byte> values) {
addCriterion("status in", values, "status");
return (Criteria) this;
}
public Criteria andStatusNotIn(List<Byte> values) {
addCriterion("status not in", values, "status");
return (Criteria) this;
}
public Criteria andStatusBetween(Byte value1, Byte value2) {
addCriterion("status between", value1, value2, "status");
return (Criteria) this;
}
public Criteria andStatusNotBetween(Byte value1, Byte value2) {
addCriterion("status not between", value1, value2, "status");
return (Criteria) this;
}
public Criteria andGatherIsNull() {
addCriterion("gather is null");
return (Criteria) this;
}
public Criteria andGatherIsNotNull() {
addCriterion("gather is not null");
return (Criteria) this;
}
public Criteria andGatherEqualTo(String value) {
addCriterion("gather =", value, "gather");
return (Criteria) this;
}
public Criteria andGatherNotEqualTo(String value) {
addCriterion("gather <>", value, "gather");
return (Criteria) this;
}
public Criteria andGatherGreaterThan(String value) {
addCriterion("gather >", value, "gather");
return (Criteria) this;
}
public Criteria andGatherGreaterThanOrEqualTo(String value) {
addCriterion("gather >=", value, "gather");
return (Criteria) this;
}
public Criteria andGatherLessThan(String value) {
addCriterion("gather <", value, "gather");
return (Criteria) this;
}
public Criteria andGatherLessThanOrEqualTo(String value) {
addCriterion("gather <=", value, "gather");
return (Criteria) this;
}
public Criteria andGatherLike(String value) {
addCriterion("gather like", value, "gather");
return (Criteria) this;
}
public Criteria andGatherNotLike(String value) {
addCriterion("gather not like", value, "gather");
return (Criteria) this;
}
public Criteria andGatherIn(List<String> values) {
addCriterion("gather in", values, "gather");
return (Criteria) this;
}
public Criteria andGatherNotIn(List<String> values) {
addCriterion("gather not in", values, "gather");
return (Criteria) this;
}
public Criteria andGatherBetween(String value1, String value2) {
addCriterion("gather between", value1, value2, "gather");
return (Criteria) this;
}
public Criteria andGatherNotBetween(String value1, String value2) {
addCriterion("gather not between", value1, value2, "gather");
return (Criteria) this;
}
public Criteria andCompletedIsNull() {
addCriterion("completed is null");
return (Criteria) this;
}
public Criteria andCompletedIsNotNull() {
addCriterion("completed is not null");
return (Criteria) this;
}
public Criteria andCompletedEqualTo(Boolean value) {
addCriterion("completed =", value, "completed");
return (Criteria) this;
}
public Criteria andCompletedNotEqualTo(Boolean value) {
addCriterion("completed <>", value, "completed");
return (Criteria) this;
}
public Criteria andCompletedGreaterThan(Boolean value) {
addCriterion("completed >", value, "completed");
return (Criteria) this;
}
public Criteria andCompletedGreaterThanOrEqualTo(Boolean value) {
addCriterion("completed >=", value, "completed");
return (Criteria) this;
}
public Criteria andCompletedLessThan(Boolean value) {
addCriterion("completed <", value, "completed");
return (Criteria) this;
}
public Criteria andCompletedLessThanOrEqualTo(Boolean value) {
addCriterion("completed <=", value, "completed");
return (Criteria) this;
}
public Criteria andCompletedIn(List<Boolean> values) {
addCriterion("completed in", values, "completed");
return (Criteria) this;
}
public Criteria andCompletedNotIn(List<Boolean> values) {
addCriterion("completed not in", values, "completed");
return (Criteria) this;
}
public Criteria andCompletedBetween(Boolean value1, Boolean value2) {
addCriterion("completed between", value1, value2, "completed");
return (Criteria) this;
}
public Criteria andCompletedNotBetween(Boolean value1, Boolean value2) {
addCriterion("completed not between", value1, value2, "completed");
return (Criteria) this;
}
public Criteria andVerifyIsNull() {
addCriterion("verify is null");
return (Criteria) this;
}
public Criteria andVerifyIsNotNull() {
addCriterion("verify is not null");
return (Criteria) this;
}
public Criteria andVerifyEqualTo(Boolean value) {
addCriterion("verify =", value, "verify");
return (Criteria) this;
}
public Criteria andVerifyNotEqualTo(Boolean value) {
addCriterion("verify <>", value, "verify");
return (Criteria) this;
}
public Criteria andVerifyGreaterThan(Boolean value) {
addCriterion("verify >", value, "verify");
return (Criteria) this;
}
public Criteria andVerifyGreaterThanOrEqualTo(Boolean value) {
addCriterion("verify >=", value, "verify");
return (Criteria) this;
}
public Criteria andVerifyLessThan(Boolean value) {
addCriterion("verify <", value, "verify");
return (Criteria) this;
}
public Criteria andVerifyLessThanOrEqualTo(Boolean value) {
addCriterion("verify <=", value, "verify");
return (Criteria) this;
}
public Criteria andVerifyIn(List<Boolean> values) {
addCriterion("verify in", values, "verify");
return (Criteria) this;
}
public Criteria andVerifyNotIn(List<Boolean> values) {
addCriterion("verify not in", values, "verify");
return (Criteria) this;
}
public Criteria andVerifyBetween(Boolean value1, Boolean value2) {
addCriterion("verify between", value1, value2, "verify");
return (Criteria) this;
}
public Criteria andVerifyNotBetween(Boolean value1, Boolean value2) {
addCriterion("verify not between", value1, value2, "verify");
return (Criteria) this;
}
public Criteria andFilePrefixIsNull() {
addCriterion("file_prefix is null");
return (Criteria) this;
}
public Criteria andFilePrefixIsNotNull() {
addCriterion("file_prefix is not null");
return (Criteria) this;
}
public Criteria andFilePrefixEqualTo(String value) {
addCriterion("file_prefix =", value, "filePrefix");
return (Criteria) this;
}
public Criteria andFilePrefixNotEqualTo(String value) {
addCriterion("file_prefix <>", value, "filePrefix");
return (Criteria) this;
}
public Criteria andFilePrefixGreaterThan(String value) {
addCriterion("file_prefix >", value, "filePrefix");
return (Criteria) this;
}
public Criteria andFilePrefixGreaterThanOrEqualTo(String value) {
addCriterion("file_prefix >=", value, "filePrefix");
return (Criteria) this;
}
public Criteria andFilePrefixLessThan(String value) {
addCriterion("file_prefix <", value, "filePrefix");
return (Criteria) this;
}
public Criteria andFilePrefixLessThanOrEqualTo(String value) {
addCriterion("file_prefix <=", value, "filePrefix");
return (Criteria) this;
}
public Criteria andFilePrefixLike(String value) {
addCriterion("file_prefix like", value, "filePrefix");
return (Criteria) this;
}
public Criteria andFilePrefixNotLike(String value) {
addCriterion("file_prefix not like", value, "filePrefix");
return (Criteria) this;
}
public Criteria andFilePrefixIn(List<String> values) {
addCriterion("file_prefix in", values, "filePrefix");
return (Criteria) this;
}
public Criteria andFilePrefixNotIn(List<String> values) {
addCriterion("file_prefix not in", values, "filePrefix");
return (Criteria) this;
}
public Criteria andFilePrefixBetween(String value1, String value2) {
addCriterion("file_prefix between", value1, value2, "filePrefix");
return (Criteria) this;
}
public Criteria andFilePrefixNotBetween(String value1, String value2) {
addCriterion("file_prefix not between", value1, value2, "filePrefix");
return (Criteria) this;
}
public Criteria andPicDirIsNull() {
addCriterion("pic_dir is null");
return (Criteria) this;
}
public Criteria andPicDirIsNotNull() {
addCriterion("pic_dir is not null");
return (Criteria) this;
}
public Criteria andPicDirEqualTo(String value) {
addCriterion("pic_dir =", value, "picDir");
return (Criteria) this;
}
public Criteria andPicDirNotEqualTo(String value) {
addCriterion("pic_dir <>", value, "picDir");
return (Criteria) this;
}
public Criteria andPicDirGreaterThan(String value) {
addCriterion("pic_dir >", value, "picDir");
return (Criteria) this;
}
public Criteria andPicDirGreaterThanOrEqualTo(String value) {
addCriterion("pic_dir >=", value, "picDir");
return (Criteria) this;
}
public Criteria andPicDirLessThan(String value) {
addCriterion("pic_dir <", value, "picDir");
return (Criteria) this;
}
public Criteria andPicDirLessThanOrEqualTo(String value) {
addCriterion("pic_dir <=", value, "picDir");
return (Criteria) this;
}
public Criteria andPicDirLike(String value) {
addCriterion("pic_dir like", value, "picDir");
return (Criteria) this;
}
public Criteria andPicDirNotLike(String value) {
addCriterion("pic_dir not like", value, "picDir");
return (Criteria) this;
}
public Criteria andPicDirIn(List<String> values) {
addCriterion("pic_dir in", values, "picDir");
return (Criteria) this;
}
public Criteria andPicDirNotIn(List<String> values) {
addCriterion("pic_dir not in", values, "picDir");
return (Criteria) this;
}
public Criteria andPicDirBetween(String value1, String value2) {
addCriterion("pic_dir between", value1, value2, "picDir");
return (Criteria) this;
}
public Criteria andPicDirNotBetween(String value1, String value2) {
addCriterion("pic_dir not between", value1, value2, "picDir");
return (Criteria) this;
}
public Criteria andThumbIsNull() {
addCriterion("thumb is null");
return (Criteria) this;
}
public Criteria andThumbIsNotNull() {
addCriterion("thumb is not null");
return (Criteria) this;
}
public Criteria andThumbEqualTo(String value) {
addCriterion("thumb =", value, "thumb");
return (Criteria) this;
}
public Criteria andThumbNotEqualTo(String value) {
addCriterion("thumb <>", value, "thumb");
return (Criteria) this;
}
public Criteria andThumbGreaterThan(String value) {
addCriterion("thumb >", value, "thumb");
return (Criteria) this;
}
public Criteria andThumbGreaterThanOrEqualTo(String value) {
addCriterion("thumb >=", value, "thumb");
return (Criteria) this;
}
public Criteria andThumbLessThan(String value) {
addCriterion("thumb <", value, "thumb");
return (Criteria) this;
}
public Criteria andThumbLessThanOrEqualTo(String value) {
addCriterion("thumb <=", value, "thumb");
return (Criteria) this;
}
public Criteria andThumbLike(String value) {
addCriterion("thumb like", value, "thumb");
return (Criteria) this;
}
public Criteria andThumbNotLike(String value) {
addCriterion("thumb not like", value, "thumb");
return (Criteria) this;
}
public Criteria andThumbIn(List<String> values) {
addCriterion("thumb in", values, "thumb");
return (Criteria) this;
}
public Criteria andThumbNotIn(List<String> values) {
addCriterion("thumb not in", values, "thumb");
return (Criteria) this;
}
public Criteria andThumbBetween(String value1, String value2) {
addCriterion("thumb between", value1, value2, "thumb");
return (Criteria) this;
}
public Criteria andThumbNotBetween(String value1, String value2) {
addCriterion("thumb not between", value1, value2, "thumb");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion implements Serializable {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
}
} | [
"fwolff@vip.qq.com"
] | fwolff@vip.qq.com |
5d7fb6d661b21c115b75038fa45d25f85720f830 | d7130fdaf51db9b45347aeb77188c1ee26d8e56e | /leo10/app/src/main/java/com/android/systemui/statusbar/salt/SaltMainBattery.java | 8d1a18154bca7f3ff3212970b550970c65ff9414 | [] | no_license | FusionPlmH/Fusion-Project | 317af268c8bcb2cc6e7c30cf39a9cc3bc62cb84e | 19ac1c5158bc48f3013dce82fe5460d988206103 | refs/heads/master | 2022-04-07T00:36:40.424705 | 2020-03-16T16:06:28 | 2020-03-16T16:06:28 | 247,745,495 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,358 | java | package com.android.systemui.statusbar.salt;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.BatteryManager;
import android.animation.ArgbEvaluator;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.ImageView;
import com.android.systemui.Dependency;
import com.android.systemui.coloring.QSColoringServiceManager;
import com.android.systemui.statusbar.policy.ConfigurationController;
import com.android.systemui.statusbar.policy.DarkIconDispatcher;
import static com.android.settingslib.salt.SaltConfigCenter.getLeoMianBatteryStyle;
import static com.android.settingslib.salt.SaltConfigFrame.SaltSettings.setLeoImagePadding;
import static com.android.settingslib.salt.SaltValues.Values17;
import static com.android.settingslib.salt.SaltValues.mDarkModeFillColor;
import static com.android.settingslib.salt.SaltValues.mLightModeFillColor;
import static com.android.settingslib.salt.utils.LeoManages.LeoSysUiManages;
import static com.android.settingslib.salt.utils.LeoManages.*;
public class SaltMainBattery extends ImageView implements DarkIconDispatcher.DarkReceiver, ConfigurationController.ConfigurationListener {
public int mBatteryChargeColor,mBatteryStandbyColor;
private Context mContext;
public static final String BATTERY_TAG="leo_battery_view";
private String ACTION_BATTERY= Intent.ACTION_BATTERY_CHANGED;
private Drawable mCustomBattery;
private Drawable mCustomBatteryCharge;
private String mCustomBatteryPKG;
public SaltMainBattery(Context context) {
this(context, null);
}
public SaltMainBattery(Context context, AttributeSet attributeSet) {
this(context, attributeSet, 0);
}
public SaltMainBattery(Context context, AttributeSet attributeSet, int level) {
super(context, attributeSet, level);
init(context);
}
private boolean mBatteryCharging;
public int mBatteryLevel;
public int mNonAdaptedColor;
private void init(Context context) {
mContext=context;
}
private final BroadcastReceiver mBatteryReceiver= new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_BATTERY.equals(action)) {
mBatteryLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
mBatteryCharging= intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0) == BatteryManager.BATTERY_STATUS_CHARGING;
handleBatteryChange();
}
}
};
private void getCustomBattery(String str) {
if (isCustomBatteryInstalled(str)) {
try {
Context createPackageContext =getContext().createPackageContext(str, 3);
mCustomBattery = createPackageContext.getResources().getDrawable(createPackageContext.getResources().getIdentifier("stat_sys_battery", "drawable",str));
mCustomBatteryCharge = createPackageContext.getResources().getDrawable(createPackageContext.getResources().getIdentifier("stat_sys_battery_charge", "drawable", str));
return;
} catch (Exception e) {
e.printStackTrace();
return;
}
}
mCustomBattery = null;
mCustomBatteryCharge = null;
}
private void handleBatteryChange() {
LeoSysUiManages(mContext);
setImageDrawable(null);
setImageDrawable(mBatteryCharging?mCustomBatteryCharge:mCustomBattery);
setImageLevel(mBatteryLevel);
}
private boolean isCustomBatteryInstalled(String str) {
try {
return (TextUtils.isEmpty(str) || this.mContext.getPackageManager().getApplicationInfo(str, 0) == null) ? false : true;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
public void updateSettings() {
LeoSysUiManages(mContext);
setLeoImagePadding(this,setLeoStatusBarMainBatteryStartPadding,setLeoStatusBarMainBatteryEndPadding);
mCustomBatteryPKG =getLeoMianBatteryStyle (setLeoStatusbarMainBatteryPackage);
getCustomBattery(mCustomBatteryPKG);
handleBatteryChange();
mBatteryStandbyColor=setLeoStatusBarMainBatteryColor;
mBatteryChargeColor=setLeoStatusBarMainBatteryChargeColor;
updateVisibility(setLeoStatusbarMainBatteryEnabled);
if (BATTERY_TAG.equals(getTag())) {
if (setBatteryCustomColor()) {
setColorFilter(mBatteryCharging ?
mBatteryChargeColor : mBatteryStandbyColor);
} else {
setColorFilter(mNonAdaptedColor,PorterDuff.Mode.SRC_ATOP);
}
}
}
private void updateVisibility(int leobatt){
if(leobatt== 0){
setVisibility(GONE);
}else if(leobatt== 1){
setVisibility(VISIBLE);
}else if(leobatt== 2){
setVisibility(GONE);
}
}
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mCustomBattery = null;
mCustomBatteryCharge = null;
mBatteryLevel= -1;
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_BATTERY);
filter.setPriority(1000);
getContext().registerReceiver( mBatteryReceiver, filter, null, getHandler());
Dependency.get(ConfigurationController.class).addCallback(this);
Dependency.get(DarkIconDispatcher.class).addDarkReceiver((DarkIconDispatcher.DarkReceiver) this);
updateSettings();
}
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mContext.unregisterReceiver(mBatteryReceiver);
Dependency.get(ConfigurationController.class).removeCallback(this);
Dependency.get(DarkIconDispatcher.class).removeDarkReceiver((DarkIconDispatcher.DarkReceiver) this);
}
public boolean setBatteryCustomColor() {
LeoSysUiManages(mContext);
return setLeoStatusBarMainBatteryCustomColorEnabled==1;
}
public void onDarkChanged(Rect area, float darkIntensity, int tint) {
if (BATTERY_TAG.equals(getTag())) {
mNonAdaptedColor = DarkIconDispatcher.getTint(area, this, tint);
if (setBatteryCustomColor()) {
setColorFilter(mBatteryCharging ?
mBatteryChargeColor : mBatteryStandbyColor);
} else {
setColorFilter(mNonAdaptedColor,PorterDuff.Mode.SRC_ATOP);
}
}else if (Values17 .equals(getTag())) {
qsIntColor(area,darkIntensity);
}
}
private boolean mIsForceTintColor = false;
private boolean mShouldUseQsTintColor = false;
private int mNonAdaptedForegroundColor;
private void qsIntColor(Rect area,float f){
boolean isInArea = DarkIconDispatcher.isInArea(area, this);
float f3 = this.mIsForceTintColor ? 1.0f : isInArea ? f : 0.0f;
if (this.mShouldUseQsTintColor) {
f3 = this.mQsTintIntensity;
}
if (((QSColoringServiceManager) Dependency.get(QSColoringServiceManager.class)).isQSColoringEnabled() && this.mShouldUseQsTintColor) {
this.mNonAdaptedForegroundColor = ((QSColoringServiceManager) Dependency.get(QSColoringServiceManager.class)).getQSColoringColor(31);
} else {
this.mNonAdaptedForegroundColor = getColorForDarkIntensity(f3, mDarkModeFillColor, mLightModeFillColor);
}
setColorFilter(mNonAdaptedForegroundColor,PorterDuff.Mode.SRC_ATOP);
}
private int getColorForDarkIntensity(float f, int i, int i2) {
return ((Integer) ArgbEvaluator.getInstance().evaluate(f, Integer.valueOf(i), Integer.valueOf(i2))).intValue();
}
private float mQsTintIntensity;
public void setForceQsTintColor(boolean z, float f) {
this.mShouldUseQsTintColor = z;
this.mQsTintIntensity = f;
onDarkChanged(new Rect(), 0.0f, -1107296257);
}
}
| [
"1249014784@qq.com"
] | 1249014784@qq.com |
1b68cb76df5057ab60073a203f05ba48ce69697c | 48751f7cf14f9770a80845f3048605967a06f859 | /src/com/cuentadao/dao/Test.java | 80f56aa8c6bbe564092ae3c2ce1c15e438480aac | [] | no_license | oscar20/CuentaDAOJava | edcea42e6553d6a112d171cf51a966fddb40f8ac | 3436e5d4122593a384e79304bd1388504a66af4f | refs/heads/master | 2020-12-02T17:51:21.492162 | 2017-07-06T15:56:06 | 2017-07-06T15:56:06 | 96,440,222 | 0 | 0 | null | null | null | null | ISO-8859-1 | Java | false | false | 3,569 | java | package com.cuentadao.dao;
import java.util.Scanner;
import com.cuentadao.factory.CuentaDAOFactory;
import com.cuentadao.inter.CuentaDAO;
import com.cuentadao.modelos.Banco;
import com.cuentadao.modelos.Cliente;
import com.cuentadao.modelos.Cuenta;
public class Test {
static final Scanner text_in = new Scanner(System.in);
static int select = -1;
public static void main(String[] args) {
Banco bank = new Banco();
String nombre_cliente = "" ;
String apellido_cliente = "";
String balance_cuenta = "";
double int_balance_cuenta = 0;
String v_tipo_cuenta = "";
while(select != 0 ){
System.out.println("Ingresa la opcion que desees\n"
+ "1.- Agregar cliente\n"
+ "2.- Consultar numero de clientes\n"
+ "3.- Realizar deposito\n"
+ "0.- Salir");
String valor_seleccionado = text_in.nextLine();
select = Integer.parseInt(valor_seleccionado);
switch(select){
case 1:
System.out.println("Ingrese nombre: ");
nombre_cliente = text_in.nextLine();
System.out.println("Ingrese apellido: ");
apellido_cliente = text_in.nextLine();
Cuenta cuenta_de_cliente = new Cuenta();
System.out.println("Ingrese el balance de su cuenta: ");
balance_cuenta = text_in.nextLine();
int_balance_cuenta = Double.parseDouble(balance_cuenta);
cuenta_de_cliente.setbalance(int_balance_cuenta);
System.out.println("Ingrese el tipo de cuenta (cheques/ahorro): ");
v_tipo_cuenta = text_in.nextLine();
cuenta_de_cliente.setTipo(v_tipo_cuenta);
Cliente cliente1 = new Cliente(nombre_cliente,apellido_cliente,cuenta_de_cliente);
bank.addCliente(cliente1);
break;
case 2:
System.out.println("El número de clientes es de: " + bank.getNCliente());
break;
case 3:
System.out.println("Ingrese el nombre del cliente a buscar: ");
nombre_cliente = text_in.nextLine();
Cliente cliente_encontrado = bank.getCliente(nombre_cliente);
System.out.println("Nombre: " + cliente_encontrado.getNombre() + "\n" +
"Apellido: " + cliente_encontrado.getApellido() + "\n" +
"Balance de cuenta: " + cliente_encontrado.getCuenta().getbalance() + "\n");
/*System.out.println("Cliente encontrado: \n" +
"Nombre: " + cliente_encontrado.getNombre() + "\n" +
"Apellido: " + cliente_encontrado.getApellido() + "\n" +
"Balance de cuenta: " + cliente_encontrado.getCuenta().getbalance() + "\n");
*/
break;
default:
break;
}
}
Cuenta account = new Cuenta();
account.setbalance(6000.0);
Cliente nuevo_cliente = new Cliente();
nuevo_cliente.setNombre("Arturo");
nuevo_cliente.setApellido("Soto");
nuevo_cliente.setCuenta(account);
nuevo_cliente.getCuenta().setTipo("cheques");
bank.addCliente(nuevo_cliente);
System.out.println("El numero de clientes en el arreglo es de: " + bank.getNCliente());
Cliente cliente_encontrado = bank.getCliente("Arturo");
System.out.println("Cliente encontrado: " + cliente_encontrado.getApellido());
CuentaDAOFactory factory = new CuentaDAOFactory();
CuentaDAO accountdao = factory.getImplementacion(account);
System.out.println(nuevo_cliente.getNombre() + " " + nuevo_cliente.getApellido() + " realizando un retiro....\n");
accountdao.retiro(nuevo_cliente,300.0);
System.out.println("El cliente " + nuevo_cliente.getNombre() + " " + nuevo_cliente.getApellido() + " tiene "
+ " una cuenta con un balance de: " + nuevo_cliente.getCuenta().getbalance());
}
}
| [
"oscar_almazan@outlook.com"
] | oscar_almazan@outlook.com |
6880ebd5b75cedcf91c7eadaa5d2cec9ee08155d | 76bdcb2d1501295672ac11d001a08996951bca24 | /com.kumana.iotp.lite/src/main/java/com/kumana/iotp/lite/util/TLSUtil.java | 5397d62ca2961f0afa63b0cc31cbfc30e9f9dcac | [] | no_license | KumanaIoT/kumana-device-agent | e72311b3c20f96759fef85bf3e3bc2dc4713e2fd | 48c96cc95e9bb11d75181e9c61aa01c1a6f7b978 | refs/heads/master | 2021-09-19T12:15:38.680851 | 2019-08-23T12:42:23 | 2019-08-23T12:42:23 | 203,993,247 | 1 | 1 | null | 2021-08-13T15:33:50 | 2019-08-23T12:21:52 | Java | UTF-8 | Java | false | false | 6,423 | java | package com.kumana.iotp.lite.util;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.util.io.pem.PemReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.net.ssl.*;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
@Component
public class TLSUtil {
private static final String TEMPORARY_KEY_PASSWORD = "changeit";
private static final String BEGIN_CERTIFICATE = "-----BEGIN CERTIFICATE-----";
private static final String END_CERTIFICATE = "-----END CERTIFICATE-----";
private static final String JKS = "JKS";
private static final String CA_CERT_ALIAS = "caCert";
private static final String CONCERT_IOTHUB_CERT_LOCATION = "concert.iothub.cert.location";
private static final String TLS = "TLS";
private static final String CONCERT_IOTHUB_CERT_PASSWORD = "concert.iothub.cert.password";
private String certFileLocation = null;
private static final Logger logger = LoggerFactory.getLogger(TLSUtil.class);
private String iotHubeCertPassword = "abc123";
private KeyStore keyStore = null;
@Autowired
private Environment env;
@PostConstruct
public void initialize(){
final String iotHubCertLocation = env.getProperty(CONCERT_IOTHUB_CERT_LOCATION);
if(iotHubCertLocation != null && !iotHubCertLocation.isEmpty()){
File certFile = new File(iotHubCertLocation);
if(certFile.exists() && certFile.isFile()){
this.certFileLocation = iotHubCertLocation;
logger.info("Using Cert file located in : {} for IOT Hub communications", iotHubCertLocation);
}else {
logger.error("Concert IOT Hub's Cert file cannot be found at location : {}", iotHubCertLocation);
throw new RuntimeException("Concert IOT Hub's Cert file cannot be found");
}
}else{
throw new IllegalArgumentException("Concert IOT Hub's certificate location entry cannot be null");
}
final String iotHubCertPWFromFile = env.getProperty(CONCERT_IOTHUB_CERT_PASSWORD);
if(iotHubCertPWFromFile != null && !iotHubCertPWFromFile.isEmpty()){
logger.debug("External password value for IOT Hub Cert detected. Using value : {}", iotHubCertPWFromFile);
iotHubeCertPassword = iotHubCertPWFromFile;
}else{
logger.debug("Using default value of : {} for IOT Hub Cert password", iotHubeCertPassword);
}
generateKeyStore();
}
public KeyStore getKeyStore() {
return keyStore;
}
public void generateKeyStore(){
try{
final String extractedCertEntry = extractCertEntry(certFileLocation);
Certificate caCertificate = loadCertificate(extractedCertEntry);
this.keyStore = KeyStore.getInstance(JKS);
this.keyStore.load(null, TEMPORARY_KEY_PASSWORD.toCharArray());
this.keyStore.setCertificateEntry(CA_CERT_ALIAS, caCertificate);
}catch (GeneralSecurityException | IOException e){
logger.error("Cannot generate JKS with provided Cert entry, error was : {}", e.getMessage());
throw new RuntimeException("Cannot generate JKS with provided Cert entry", e);
}
}
private Certificate loadCertificate(String certificatePem) throws IOException, GeneralSecurityException {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
final byte[] content = readPemContent(certificatePem);
return certificateFactory.generateCertificate(new ByteArrayInputStream(content));
}
private byte[] readPemContent(String pem) throws IOException {
final byte[] content;
try (PemReader pemReader = new PemReader(new StringReader(pem))) {
final PemObject pemObject = pemReader.readPemObject();
content = pemObject.getContent();
}
return content;
}
private String readCertFile(final String certFileLocation) throws IOException {
final byte[] certFileBytes = Files.readAllBytes(Paths.get(certFileLocation));
final String certFileContent = new String(certFileBytes, StandardCharsets.UTF_8.name());
return certFileContent;
}
private String extractCertEntry(final String certFileLocation) throws IOException {
String certificateEntry = null;
final String certFileContent = readCertFile(certFileLocation);
final int beginCertificateIndex = certFileContent.indexOf(BEGIN_CERTIFICATE);
final int endCertificateIndex = certFileContent.indexOf(END_CERTIFICATE);
if(beginCertificateIndex != -1 && endCertificateIndex != -1){
certificateEntry = certFileContent.substring(beginCertificateIndex, endCertificateIndex + END_CERTIFICATE.length());
}else{
logger.error("Invalid Cert file content has been detected");
throw new IOException("Invalid Cert file content");
}
return certificateEntry;
}
public SSLSocketFactory getSocketFactoryWithX509Cert() {
SSLSocketFactory ssf = null;
try {
final KeyStore ks = getKeyStore();
final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, TEMPORARY_KEY_PASSWORD.toCharArray());
final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
final SSLContext sc = SSLContext.getInstance(TLS);
final TrustManager[] trustManagers = tmf.getTrustManagers();
sc.init(kmf.getKeyManagers(), trustManagers, null);
ssf = sc.getSocketFactory();
} catch (Exception ex){
throw new RuntimeException("Cannot create SSL Socket Factory", ex);
}
return ssf;
}
}
| [
"54438281+ChamKumana@users.noreply.github.com"
] | 54438281+ChamKumana@users.noreply.github.com |
bade4fd491e6499263f2c3a3557eb035963908dd | 1ba3afc8a7cb3fa3ea17597d7c370e140683fd15 | /src/main/java/com/jboss/user/process/login/service/UserServiceImpl.java | 9b037477edcfbdea3aef4770c6341b82916709d1 | [] | no_license | gomkwc/JBossAS7-Demo | 3efe42a030b1ae5bfdba7a704e81f9255cd403cf | d0165a1acb10d416f58e4308ee26bb5226ae22d0 | refs/heads/master | 2020-05-22T14:26:22.585969 | 2013-11-08T05:04:09 | 2013-11-08T05:04:09 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 615 | java | package com.jboss.user.process.login.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jboss.user.process.login.dao.UserDAO;
import com.jboss.user.process.login.domain.User;
import com.jboss.user.process.login.service.UserService;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserDAO userDAO;
/**
*
* 테스트
*
*/
public List<User> getUserInfo() throws Exception {
List<User> list = (List<User>) userDAO.getUserInfo();
return list;
}
} | [
"gomkwc@gmail.com"
] | gomkwc@gmail.com |
e2e7e6c03eecdb50fb79252fc3c7d8cbebb9200e | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/30/30_191d3026a40435d22f30dc565ec8909c0937e9f0/RestRequestFilter/30_191d3026a40435d22f30dc565ec8909c0937e9f0_RestRequestFilter_t.java | f44a78262c2ca13d863d22d4a9e2ded1487aab2c | [] | 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 | 13,185 | java | /*
* soapUI, copyright (C) 2004-2008 eviware.com
*
* soapUI is free software; you can redistribute it and/or modify it under the
* terms of version 2.1 of the GNU Lesser General Public License as published by
* the Free Software Foundation.
*
* soapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details at gnu.org.
*/
package com.eviware.soapui.impl.wsdl.submit.filters;
import com.eviware.soapui.SoapUI;
import com.eviware.soapui.impl.rest.RestRequest;
import com.eviware.soapui.impl.rest.support.XmlBeansRestParamsTestPropertyHolder;
import com.eviware.soapui.impl.rest.support.XmlBeansRestParamsTestPropertyHolder.RestParamProperty;
import com.eviware.soapui.impl.wsdl.submit.transports.http.BaseHttpRequestTransport;
import com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentDataSource;
import com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentUtils;
import com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.RestRequestDataSource;
import com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.RestRequestMimeMessageRequestEntity;
import com.eviware.soapui.impl.wsdl.support.PathUtils;
import com.eviware.soapui.model.iface.Attachment;
import com.eviware.soapui.model.iface.SubmitContext;
import com.eviware.soapui.model.propertyexpansion.PropertyExpansionUtils;
import com.eviware.soapui.support.StringUtils;
import com.eviware.soapui.support.editor.inspectors.attachments.ContentTypeHandler;
import com.eviware.soapui.support.types.StringToStringMap;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.xmlbeans.XmlBoolean;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.PreencodedMimeBodyPart;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
/**
* RequestFilter that adds SOAP specific headers
*
* @author Ole.Matzura
*/
public class RestRequestFilter extends AbstractRequestFilter
{
@SuppressWarnings( "deprecation" )
@Override
public void filterRestRequest( SubmitContext context, RestRequest request )
{
HttpMethod httpMethod = (HttpMethod) context.getProperty( BaseHttpRequestTransport.HTTP_METHOD );
String path = request.getPath();
StringBuffer query = new StringBuffer();
StringToStringMap responseProperties = (StringToStringMap) context.getProperty( BaseHttpRequestTransport.RESPONSE_PROPERTIES );
MimeMultipart formMp = "multipart/form-data".equals( request.getMediaType() ) ? new MimeMultipart() : null;
XmlBeansRestParamsTestPropertyHolder params = request.getParams();
for( int c = 0; c < params.getPropertyCount(); c++ )
{
RestParamProperty param = params.getPropertyAt( c );
String value = PropertyExpansionUtils.expandProperties( context, param.getValue() );
responseProperties.put( param.getName(), value );
if( value != null && formMp == null && !param.isDisableUrlEncoding() )
value = URLEncoder.encode( value );
if( !StringUtils.hasContent( value ) && !param.getRequired() )
continue;
switch( param.getStyle() )
{
case HEADER:
httpMethod.setRequestHeader( param.getName(), value );
break;
case QUERY:
if( formMp == null )
{
if( query.length() > 0 )
query.append( '&' );
query.append( URLEncoder.encode( param.getName() ) );
query.append( '=' );
if( StringUtils.hasContent( value ) )
query.append( value );
}
else
{
try
{
addFormMultipart( request, formMp, param.getName(), value );
}
catch( MessagingException e )
{
e.printStackTrace();
}
}
break;
case TEMPLATE:
path = path.replaceAll( "\\{" + param.getName() + "\\}", value );
break;
case MATRIX:
if( param.getType().equals( XmlBoolean.type.getName() ) )
{
if( value.toUpperCase().equals( "TRUE" ) || value.equals( "1" ) )
{
path += ";" + param.getName();
}
}
else
{
path += ";" + param.getName();
if( StringUtils.hasContent( value ) )
{
path += "=" + value;
}
}
case PLAIN:
break;
}
}
if( PathUtils.isHttpPath( path ) )
{
try
{
httpMethod.setURI( new URI( path ) );
}
catch( Exception e )
{
e.printStackTrace();
}
}
else
{
httpMethod.setPath( path );
}
if( query.length() > 0 && !request.isPostQueryString() )
{
httpMethod.setQueryString( query.toString() );
}
String acceptEncoding = request.getAccept();
if( StringUtils.hasContent( acceptEncoding ) )
{
httpMethod.setRequestHeader( "Accept", acceptEncoding );
}
String encoding = StringUtils.unquote( request.getEncoding() );
if( formMp != null )
{
// create request message
try
{
if( request.hasRequestBody() && httpMethod instanceof EntityEnclosingMethod )
{
String requestContent = PropertyExpansionUtils.expandProperties( context, request.getRequestContent() );
if( StringUtils.hasContent( requestContent ) )
{
initRootPart( request, requestContent, formMp );
}
}
for( Attachment attachment : request.getAttachments() )
{
MimeBodyPart part = new MimeBodyPart();
part.setDisposition( "form-data; name=\"" + attachment.getName() + "\"" );
part.setDataHandler( new DataHandler( new AttachmentDataSource( attachment ) ) );
formMp.addBodyPart( part );
}
MimeMessage message = new MimeMessage( AttachmentUtils.JAVAMAIL_SESSION );
message.setContent( formMp );
message.saveChanges();
RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity( message, request );
( (EntityEnclosingMethod) httpMethod ).setRequestEntity( mimeMessageRequestEntity );
httpMethod.setRequestHeader( "Content-Type", mimeMessageRequestEntity.getContentType() );
httpMethod.setRequestHeader( "MIME-Version", "1.0" );
}
catch( Throwable e )
{
SoapUI.logError( e );
}
}
else if( request.hasRequestBody() && httpMethod instanceof EntityEnclosingMethod )
{
httpMethod.setRequestHeader( "Content-Type", request.getMediaType() );
if( request.isPostQueryString() )
{
( (EntityEnclosingMethod) httpMethod ).setRequestEntity( new StringRequestEntity( query.toString() ) );
}
else
{
String requestContent = PropertyExpansionUtils.expandProperties( context, request.getRequestContent() );
List<Attachment> attachments = new ArrayList<Attachment>();
for( Attachment attachment : request.getAttachments() )
{
if( attachment.getContentType().equals( request.getMediaType() ) )
{
attachments.add( attachment );
}
}
if( StringUtils.hasContent( requestContent ) && attachments.isEmpty() )
{
try
{
byte[] content = encoding == null ? requestContent.getBytes() : requestContent.getBytes( encoding );
( (EntityEnclosingMethod) httpMethod ).setRequestEntity( new ByteArrayRequestEntity( content ) );
}
catch( UnsupportedEncodingException e )
{
( (EntityEnclosingMethod) httpMethod ).setRequestEntity( new ByteArrayRequestEntity( requestContent.getBytes() ) );
}
}
else if( attachments.size() > 0 )
{
try
{
MimeMultipart mp = null;
if( StringUtils.hasContent( requestContent ) )
{
mp = new MimeMultipart();
initRootPart( request, requestContent, mp );
}
else if( attachments.size() == 1 )
{
( (EntityEnclosingMethod) httpMethod ).setRequestEntity( new InputStreamRequestEntity(
attachments.get( 0 ).getInputStream() ) );
httpMethod.setRequestHeader( "Content-Type", request.getMediaType() );
}
if( ( (EntityEnclosingMethod) httpMethod ).getRequestEntity() == null )
{
if( mp == null )
mp = new MimeMultipart();
// init mimeparts
AttachmentUtils.addMimeParts( request, attachments, mp, new StringToStringMap() );
// create request message
MimeMessage message = new MimeMessage( AttachmentUtils.JAVAMAIL_SESSION );
message.setContent( mp );
message.saveChanges();
RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity( message, request );
( (EntityEnclosingMethod) httpMethod ).setRequestEntity( mimeMessageRequestEntity );
httpMethod.setRequestHeader( "Content-Type", mimeMessageRequestEntity.getContentType() );
httpMethod.setRequestHeader( "MIME-Version", "1.0" );
}
}
catch( Exception e )
{
e.printStackTrace();
}
}
}
}
}
private void addFormMultipart( RestRequest request, MimeMultipart formMp, String name, String value ) throws MessagingException
{
MimeBodyPart part = new MimeBodyPart();
if( value.startsWith( "file:" ) )
{
File file = new File( value.substring( 5 ) );
part.setDisposition( "form-data; name=\"" + name + "\"; filename=\"" + file.getName() + "\"" );
if( file.exists() )
{
part.setDataHandler( new DataHandler( new FileDataSource( file ) ) );
}
part.setHeader( "Content-Type", ContentTypeHandler.getContentTypeFromFilename( file.getName() ) );
}
else
{
part.setDisposition( "form-data; name=\"" + name + "\"" );
part.setText( URLEncoder.encode( value ), request.getEncoding() );
}
if( part != null )
{
formMp.addBodyPart( part );
}
}
protected void initRootPart( RestRequest wsdlRequest, String requestContent, MimeMultipart mp ) throws MessagingException
{
MimeBodyPart rootPart = new PreencodedMimeBodyPart( "8bit" );
// rootPart.setContentID( AttachmentUtils.ROOTPART_SOAPUI_ORG );
mp.addBodyPart( rootPart, 0 );
DataHandler dataHandler = new DataHandler( new RestRequestDataSource( wsdlRequest, requestContent ) );
rootPart.setDataHandler( dataHandler );
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
be214bb4e5188576d3c1250cc258d4294fd4fcc9 | 27edea829820fbf8020621d33f803e6a81050419 | /src/main/java/me/logx/Main.java | a687b35334cafbec3e0630cbda370c234664e510 | [] | no_license | logx0576/my-test | a33ebfb2627810232dd02924a0ea47535c72b2b9 | 248b50c683a37693195fe2d910a9d73d187074c9 | refs/heads/master | 2021-01-21T13:48:07.515730 | 2016-05-17T14:42:42 | 2016-05-17T14:42:42 | 44,781,617 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 194 | java | package me.logx;
import java.io.File;
public class Main {
public static void main(String[] args) {
File f = new File("a.txt");
System.out.println(f.getAbsoluteFile());
}
}
| [
"logx0576@163.com"
] | logx0576@163.com |
a8404d99839616b8feebd8e88a243e2d935b23b4 | dbe8664661a6e5adcd9b848856eb6cc6234a546e | /src/cn/wedfrend/util/PageUtil.java | 933a6c6279045fa1beab85360a68801bf89a313d | [
"Apache-2.0"
] | permissive | wedfrendwang/PersonInfo | a61c32df476e10d9462c5645c6ba790fe074811c | 399154af1a8d3ec73ea1fa272cc0fbbf317a5b36 | refs/heads/master | 2021-01-22T17:58:36.733038 | 2017-04-13T15:24:14 | 2017-04-13T15:24:14 | 85,048,949 | 0 | 0 | null | null | null | null | GB18030 | Java | false | false | 825 | java | package cn.wedfrend.util;
public class PageUtil {
private int pageSize;//每一页显示的个数
private int totalCount;//总的数量
private int totalPage;//总页数
private int currentPage;//当前页
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalPage() {//总的页数
return totalPage = (totalCount%pageSize==0)?totalCount/pageSize:totalCount/pageSize+1;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
}
| [
"wedfrend@163.com"
] | wedfrend@163.com |
e1b8e972a9ddd78aaeeae2ba33490408fa3a2a16 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/20/20_1a2d5cfccb622af88f14d7ac4a891502ee8be446/SpriteSheet/20_1a2d5cfccb622af88f14d7ac4a891502ee8be446_SpriteSheet_s.java | 661b659e2a90efdb6692c0e1314a8631486a9ed3 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 5,311 | java | package org.newdawn.slick;
import java.io.InputStream;
/**
* A sheet of sprites that can be drawn individually
*
* @author Kevin Glass
*/
public class SpriteSheet extends Image {
/** The width of a single element in pixels */
private int tw;
/** The height of a single element in pixels */
private int th;
/** Subimages */
private Image[][] subImages;
/** The spacing between tiles */
private int spacing;
/** The target image for this sheet */
private Image target;
/**
* Create a new sprite sheet based on a image location
*
* @param image The image to based the sheet of
* @param tw The width of the tiles on the sheet
* @param th The height of the tiles on the sheet
*/
public SpriteSheet(Image image,int tw,int th) {
super(image);
this.target = image;
this.tw = tw;
this.th = th;
// call init manually since constructing from an image will have previously initialised
// from incorrect values
initImpl();
}
/**
* Create a new sprite sheet based on a image location
*
* @param image The image to based the sheet of
* @param tw The width of the tiles on the sheet
* @param th The height of the tiles on the sheet
* @param spacing The spacing between tiles
*/
public SpriteSheet(Image image,int tw,int th,int spacing) {
super(image);
this.target = image;
this.tw = tw;
this.th = th;
this.spacing = spacing;
// call init manually since constructing from an image will have previously initialised
// from incorrect values
initImpl();
}
/**
* Create a new sprite sheet based on a image location
*
* @param ref The location of the sprite sheet to load
* @param tw The width of the tiles on the sheet
* @param th The height of the tiles on the sheet
* @throws SlickException Indicates a failure to load the image
*/
public SpriteSheet(String ref,int tw,int th) throws SlickException {
this(ref,tw,th,null);
}
/**
* Create a new sprite sheet based on a image location
*
* @param ref The location of the sprite sheet to load
* @param tw The width of the tiles on the sheet
* @param th The height of the tiles on the sheet
* @param col The colour to treat as transparent
* @throws SlickException Indicates a failure to load the image
*/
public SpriteSheet(String ref,int tw,int th, Color col) throws SlickException {
super(ref, false, FILTER_NEAREST, col);
this.target = this;
this.tw = tw;
this.th = th;
}
/**
* Create a new sprite sheet based on a image location
*
* @param name The name to give to the image in the image cache
* @param ref The stream from which we can load the image
* @param tw The width of the tiles on the sheet
* @param th The height of the tiles on the sheet
* @throws SlickException Indicates a failure to load the image
*/
public SpriteSheet(String name, InputStream ref,int tw,int th) throws SlickException {
super(ref,name,false);
this.target = this;
this.tw = tw;
this.th = th;
}
/**
* @see org.newdawn.slick.Image#initImpl()
*/
protected void initImpl() {
if (subImages != null) {
return;
}
subImages = new Image[(getWidth()/(tw+spacing))][(getHeight()/(th+spacing))];
for (int x=0;x<getWidth()/(tw+spacing);x++) {
for (int y=0;y<getHeight()/(th+spacing);y++) {
subImages[x][y] = getSprite(x,y);
}
}
}
/**
* Get a sprite at a particular cell on the sprite sheet
*
* @param x The x position of the cell on the sprite sheet
* @param y The y position of the cell on the sprite sheet
* @return The single image from the sprite sheet
*/
public Image getSprite(int x, int y) {
target.init();
initImpl();
return target.getSubImage(x*(tw+spacing),y*(th+spacing),tw,th);
}
/**
* Get the number of sprites across the sheet
*
* @return The number of sprites across the sheet
*/
public int getHorizontalCount() {
target.init();
initImpl();
return subImages.length;
}
/**
* Get the number of sprites down the sheet
*
* @return The number of sprite down the sheet
*/
public int getVerticalCount() {
target.init();
initImpl();
return subImages[0].length;
}
/**
* Render a sprite when this sprite sheet is in use.
*
* @see #startUse()
* @see #endUse()
*
* @param x The x position to render the sprite at
* @param y The y position to render the sprite at
* @param sx The x location of the cell to render
* @param sy The y location of the cell to render
*/
public void renderInUse(int x,int y,int sx,int sy) {
subImages[sx][sy].drawEmbedded(x, y, tw, th);
}
/**
* @see org.newdawn.slick.Image#endUse()
*/
public void endUse() {
if (target == this) {
super.endUse();
return;
}
target.endUse();
}
/**
* @see org.newdawn.slick.Image#startUse()
*/
public void startUse() {
if (target == this) {
super.startUse();
return;
}
target.startUse();
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
491aab6cee85948a683f0a27fabaa402a5751875 | 84b3b214f67a72595a58b2d20112b56e5a0c28f5 | /VirtModel4/src/at/ac/tuwien/big/vmod/impl/SimpleGenerator.java | ee020a507d98ffa5f02ebcf9b711fd31b8bdec7f | [] | no_license | rbill/virtualedit | 383fa512414ba72feb934cb96fb59e1370fc23a4 | b54e0c7247f2d4e53f488d8ef13df1b962f9bb87 | refs/heads/master | 2021-01-21T07:01:01.551062 | 2018-10-29T08:03:00 | 2018-10-29T08:03:00 | 83,294,659 | 1 | 1 | null | 2017-10-31T18:08:13 | 2017-02-27T09:53:05 | Java | UTF-8 | Java | false | false | 2,369 | java | package at.ac.tuwien.big.vmod.impl;
import at.ac.tuwien.big.vmod.Counter;
import at.ac.tuwien.big.vmod.Function;
import at.ac.tuwien.big.vmod.GeneralElement;
import at.ac.tuwien.big.vmod.ModelResource;
import at.ac.tuwien.big.vmod.ParentLocation;
import at.ac.tuwien.big.vmod.generator.Generator;
import at.ac.tuwien.big.vmod.type.CountType;
import at.ac.tuwien.big.vmod.type.FunctionType;
import at.ac.tuwien.big.vmod.type.GeneralType;
import at.ac.tuwien.big.vmod.type.ModelProviderType;
import at.ac.tuwien.big.vmod.type.ModelResourceType;
import at.ac.tuwien.big.vmod.type.Symbol;
import at.ac.tuwien.big.vmod.type.ValueType;
public class SimpleGenerator<T,U> implements Generator<GeneralElement,T,U>{
public Object generateOfType(GeneralType rangeType) {
Object ret = null;
if (rangeType instanceof FunctionType) {
Function retFunc = new SimpleFunction<>((FunctionType)rangeType, this);
ret = retFunc;
} else if (rangeType instanceof CountType) {
Counter retCount = new SimpleCounter((CountType)rangeType);
ret = retCount;
} else {
System.err.println("Don't know how to create "+rangeType);
}
return ret;
}
public static String getMetainfo(Object key) {
if (key instanceof Symbol) {
return ((Symbol) key).getName();
}
return String.valueOf(key);
}
@Override
public U generate(GeneralElement self, T key) {
U ret = null;
if (self instanceof Function) {
Function selfF = (Function)self;
FunctionType type = selfF.getType();
GeneralType rangeType = type.getType(getMetainfo(key));
if (rangeType == null || rangeType == GeneralType.NO_TYPE) {
rangeType = type.getRange();
}
//Generate something of that type
ret = (U)generateOfType(rangeType);
} else if (self instanceof ModelResource) {
ModelResource mr = (ModelResource)self;
ModelResourceType type = (ModelResourceType)mr.getType();
String keyV = String.valueOf(key);
if (key instanceof Symbol) {
keyV = ((Symbol)key).getName();
}
GeneralType rangeType = type.getType(keyV);
ret = (U)generateOfType(rangeType);
}
if (ret == null) {
System.err.println("Don't know how to create "+key+" for "+self);
}
if (ret instanceof GeneralElement) {
GeneralElement ge = (GeneralElement)ret;
ParentLocation pl = new ParentLocationImpl(self,key,ge);
ge.setParentLoc(pl);
}
return ret;
}
}
| [
"bill@big.tuwien.ac.at"
] | bill@big.tuwien.ac.at |
d5691d3f0dcaed043279c38f9ce1e9d5bef29104 | 8798fb8506033b539dbbe7976ea7beff7ab5370b | /src/com/example/list48/MainActivity.java | b07f42c41dd7947460d3bcf1b3126f8fe262b747 | [] | no_license | ionjanu/list48 | 8a4d8c3e426f74e981179932ecc7ef808ea12949 | f2781c1f87ae0dee8d24ea5e6b611584d669cfb8 | refs/heads/master | 2021-01-05T03:31:00.134124 | 2020-02-16T09:32:35 | 2020-02-16T09:32:35 | 240,862,605 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,069 | java | package com.example.list48;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class MainActivity extends Activity {
// denumiri atribute pentru Map
final String ATTRIBUTE_NAME_TEXT = "text";
final String ATTRIBUTE_NAME_CHECKED = "checked";
final String ATTRIBUTE_NAME_IMAGE = "image";
ListView lvSimple;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// tablouri de date
String[] texts = { "inserare tex", "sometext 2", "sometext 3",
"sometext 4", "sometext 5" };
boolean[] checked = { false, false, false, true, false };
int img = R.drawable.ic_launcher;
// accesati linkul de mai jos pentru a studia ceva reveritor la Map
// https://developer.android.com/reference/java/util/Map.html
// impachetam datele intr-0 structura specifica adaptorului
ArrayList<Map<String, Object>> data = new ArrayList<Map<String, Object>>(
texts.length);
Map<String, Object> m;
for (int i = 0; i < texts.length; i++) {
m = new HashMap<String, Object>();
m.put(ATTRIBUTE_NAME_TEXT, texts[i]);
m.put(ATTRIBUTE_NAME_CHECKED, checked[i]);
m.put(ATTRIBUTE_NAME_IMAGE, img);
data.add(m);
}
// tablourile denumirilor atributelor de unde vor fi citite datele
String[] from = { ATTRIBUTE_NAME_TEXT, ATTRIBUTE_NAME_CHECKED,
ATTRIBUTE_NAME_IMAGE };
// tabloul ID al componentelor View in care vor fi inserate datele
int[] to = { R.id.tvText, R.id.cbChecked, R.id.ivImg };
// cfeam adaptorul
SimpleAdapter sAdapter = new SimpleAdapter(this, data, R.layout.item,
from, to);
// definim lista si atribuim listei adaptorul respectiv creat
lvSimple = (ListView) findViewById(R.id.lvSimple);
lvSimple.setAdapter(sAdapter);
}
}
| [
"ion.janu@gmail.com"
] | ion.janu@gmail.com |
c26e56ff2c72c7f07a689e7a4c8462e40137e372 | b855f10be49ac03dcd83c3113f92b714291a9036 | /abstract_factory/listfactory/ListTray.java | 62293679d0d6074333af17ee3a3917f94e35c547 | [] | no_license | shchun/dp_java | 67f96fc5ac6df9fc524de080969367fab1d9f93a | 27623f2acb7ccf8c04616c26f34e5c62a1f8f7a0 | refs/heads/master | 2021-01-20T05:58:15.065673 | 2013-09-16T05:52:06 | 2013-09-16T05:52:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 545 | java |
package listfactory;
import factory.*;
import java.util.Iterator;
public class ListTray extends Tray {
public ListTray(String caption) {
super(caption);
}
public String makeHTML() {
StringBuffer buffer = new StringBuffer();
buffer.append("<li>\n");
buffer.append(caption + "\n");
buffer.append("<ul>\n");
Iterator it = tray.iterator();
while (it.hasNext()) {
Item item = (Item)it.next();
buffer.append(item.makeHTML());
}
buffer.append("</ul>\n");
buffer.append("</li>\n");
return buffer.toString();
}
}
| [
"seunghyo.chun@gmail.com"
] | seunghyo.chun@gmail.com |
95f8b5b6fa58e8b8c949b624afc1a854d8ddb1c9 | 98e53f3932ecce2a232d0c314527efe49f62e827 | /com.vedana.camelia.generators/src/com/vedana/camelia/generator/js/parser/processor/MergeIfReturns.java | 729bc907b71c98198de3c647992d6fb98cee41cd | [] | no_license | Vedana/rcfaces-2 | f053a4ebb8bbadd02455d89a5f1cb870deade6da | 4112cfe1117c4bfcaf42f67fe5af32a84cf52d41 | refs/heads/master | 2020-04-02T15:03:08.653984 | 2014-04-18T09:36:54 | 2014-04-18T09:36:54 | 11,175,963 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,123 | java | /*
* $Id: MergeIfReturns.java,v 1.2 2013/11/14 14:08:48 oeuillot Exp $
*/
package com.vedana.camelia.generator.js.parser.processor;
import com.vedana.camelia.generator.js.parser.IJsFile;
import com.vedana.camelia.generator.js.parser.JsStats;
import com.vedana.camelia.generator.js.parser.Tools;
import com.vedana.js.Operation;
import com.vedana.js.Visitors;
import com.vedana.js.dom.ASTNode;
import com.vedana.js.dom.Expression;
import com.vedana.js.dom.HookExpression;
import com.vedana.js.dom.IfStatement;
import com.vedana.js.dom.ParenthesizedExpression;
import com.vedana.js.dom.PrefixExpression;
import com.vedana.js.dom.ReturnStatement;
import com.vedana.js.dom.UndefinedLiteral;
public class MergeIfReturns implements IJsFileProcessor {
public boolean process(JsStats stats, IJsFile jsFile) {
boolean modified = false;
IfStatement rs[] = Visitors.visitIfs(jsFile.getDocument()
.getStatements(), false);
for (IfStatement i : rs) {
ASTNode next = i.getNextSibling();
boolean returnNext = next instanceof ReturnStatement;
if (verifiyIf(i, returnNext) == false) {
continue;
}
Expression ifTrue = ((ReturnStatement) i.getIfTrue())
.getExpression();
Expression ifFalse = null;
if ((ReturnStatement) i.getIfFalse() != null) {
ifFalse = ((ReturnStatement) i.getIfFalse()).getExpression();
}
if (returnNext && ifFalse == null) {
ifFalse = ((ReturnStatement) next).getExpression();
}
if (ifFalse == null) {
ifFalse = new UndefinedLiteral(null);
System.err.println("WARNING: not define FALSE expression ! "
+ i);
}
if (ifTrue == null) {
ifTrue = new UndefinedLiteral(null);
// System.err.println("WARNING: not define TRUE expression ! " +
// i);
// Ca peut etre normal !
}
Expression newExpression;
if (Tools.isTrueLiteral(ifTrue) && Tools.isFalseLiteral(ifFalse)) {
newExpression = new PrefixExpression(Operation.NOT,
new PrefixExpression(Operation.NOT,
new ParenthesizedExpression(i.getCondition(),
null), null), null);
} else if (Tools.isFalseLiteral(ifTrue)
&& Tools.isTrueLiteral(ifFalse)) {
newExpression = new PrefixExpression(Operation.NOT,
new ParenthesizedExpression(i.getCondition(), null),
null);
} else {
newExpression = new HookExpression(new ParenthesizedExpression(
i.getCondition(), null), new ParenthesizedExpression(
ifTrue, null), new ParenthesizedExpression(ifFalse,
null), null);
}
ReturnStatement returnStatement = new ReturnStatement(
newExpression, i.getRegion());
i.replaceBy(returnStatement);
if (returnNext) {
next.replaceBy(null);
}
System.out.println("Optimize: Merge if returns " + returnStatement);
}
return modified;
}
private boolean verifiyIf(IfStatement i, boolean nextReturn) {
if (i.getIfTrue() instanceof IfStatement) {
// if (verifiyIf((IfStatement) i.getIfTrue(), false) == false) {
return false;
// }
} else if ((i.getIfTrue() instanceof ReturnStatement) == false) {
return false;
}
if (i.getIfFalse() instanceof ReturnStatement) {
return true;
}
if (i.getIfFalse() == null) {
return nextReturn;
}
if (i.getIfFalse() instanceof IfStatement) {
// return verifiyIf((IfStatement) i.getIfFalse(), false);
}
return false;
}
}
| [
"jbmeslin@vedana.com"
] | jbmeslin@vedana.com |
62ca2dc292d4be730b839820d32f9d830a1c32fd | bb95f2468162259e756986817991c2cdfa70f3b3 | /app/src/main/java/com/xmartlabs/scasas/doapp/helper/ui/DatePickerDialogHelper.java | a5231d75b830bfea625f7f638f35b61e2031322d | [
"Apache-2.0"
] | permissive | chacaa/DoApp | 95a4a216bfd70cd01823463be939ffb2772bd258 | ddb69729e5815e8fee33f0a9977d5cc06069dbbc | refs/heads/master | 2020-05-18T13:03:52.746477 | 2017-03-20T15:36:54 | 2017-03-20T15:36:55 | 84,237,474 | 2 | 0 | Apache-2.0 | 2018-01-28T08:19:31 | 2017-03-07T19:25:15 | Java | UTF-8 | Java | false | false | 1,994 | java | package com.xmartlabs.scasas.doapp.helper.ui;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import org.threeten.bp.Clock;
import org.threeten.bp.LocalDate;
/**
* Created by medina on 19/09/2016.
*/
@SuppressWarnings("unused")
public class DatePickerDialogHelper {
/**
* Creates a <code>DatePickerDialog</code> instance
* @param listener to be triggered when the user selects a date
* @param clock to get the <code>Calendar</code> from
* @return the <code>DatePickerDialog</code> created instance
*/
@SuppressWarnings("unused")
@NonNull
public static DatePickerDialog createDialog(@Nullable OnLocalDateSetListener listener, @NonNull Clock clock) {
return createDialog(null, listener, clock);
}
/**
* Creates a <code>DatePickerDialog</code> instance with the <code>localDate</code> selected
* @param localDate the selected start localDate
* @param listener to be triggered when the user selects a localDate
* @param clock to get the <code>Calendar</code> from
* @return the <code>DatePickerDialog</code> created instance
*/
@NonNull
public static DatePickerDialog createDialog(@Nullable LocalDate localDate, @Nullable OnLocalDateSetListener listener,
@NonNull Clock clock) {
if (localDate == null) {
localDate = LocalDate.now(clock);
}
DatePickerDialog.OnDateSetListener dialogCallBack = (view, year, monthOfYear, dayOfMonth) -> {
LocalDate date = LocalDate.of(year, monthOfYear + 1, dayOfMonth);
if (listener != null) {
listener.onDateSet(date);
}
};
DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(
dialogCallBack,
localDate.getYear(),
localDate.getMonthValue() - 1,
localDate.getDayOfMonth()
);
datePickerDialog.dismissOnPause(true);
return datePickerDialog;
}
}
| [
"scacas@xmartlabs.com"
] | scacas@xmartlabs.com |
25ff7a803986848903537e768f6c496e6d38a61b | b6a7eb7b85a09e5d8468e72a38fbc832bef3ad47 | /app/src/main/java/com/x_mega/oculator/motion_picture/filter/BackToBackFilter.java | 01cf5856f0b6502adf619003235048e7bb0784ae | [] | no_license | toomask/oculator | 0704915bdfd71c8710d4ba2adabd11fc85270ada | 569a6d76d1153876b58a8ac235625a8e879629e7 | refs/heads/master | 2021-01-13T01:36:52.725684 | 2014-11-04T07:20:12 | 2014-11-04T07:20:12 | 25,860,414 | 3 | 1 | null | null | null | null | UTF-8 | Java | false | false | 534 | java | package com.x_mega.oculator.motion_picture.filter;
import com.x_mega.oculator.motion_picture.BasicMotionPicture;
import com.x_mega.oculator.motion_picture.MotionPicture;
/**
* Created by toomas on 11.10.2014.
*/
public class BackToBackFilter implements Filter {
@Override
public MotionPicture applyTo(MotionPicture motionPicture) {
BasicMotionPicture newPicture = new BasicMotionPicture(motionPicture);
newPicture.addFrames(new ReverseFilter().applyTo(motionPicture));
return newPicture;
}
}
| [
"toomas@mooncascade.com"
] | toomas@mooncascade.com |
c0ded01fb50e68fc04d06160a2a0aed1b89866e1 | 0a8fb73ddfc132c4b8a3b7720d37fb6779cdcf49 | /src/sqlPublication/SQLReadTradeLogByCode.java | 3a62daba83b131ed9725fc332f135c0240187ce3 | [] | no_license | KentaTabuchi/TradeLogManagerByJavaFX | c5bbd51332263de5bb3d9dd1d9d601408a0456ea | a6482a8c9f1fdf6f93d38e022c88d274ad3f3afb | refs/heads/master | 2022-10-04T05:44:31.984459 | 2019-05-14T11:58:20 | 2019-05-14T11:58:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,261 | java | /**
*
*/
package sqlPublication;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import application.ISQLExecutable;
import propertyBeans.TradeLogRecord;
/**
* @author misskabu
* TRADE_LOG TABLE から 読み出したデータを表に表示するためのSQL
*/
public class SQLReadTradeLogByCode implements ISQLExecutable {
/* (非 Javadoc)
* @see application.ISQLExcutable#excuteQuery()
*/
private int code;
public List<TradeLogRecord> recordList;
public SQLReadTradeLogByCode(int code){
this.code = code;
}
final String SQL = "SELECT * FROM TRADE_LOG LEFT JOIN BOOK_INFO ON TRADE_LOG.SECURITIES_CODE ="
+ " BOOK_INFO.SECURITIES_CODE WHERE BOOK_INFO.SECURITIES_CODE = ? ORDER BY TRADE_DATE";
@Override
public void executeQuery(Connection con) {
this.recordList = new ArrayList<TradeLogRecord>();
System.out.println("executeQuery");
PreparedStatement ps = null;
try {
ps = con.prepareStatement(this.SQL);
} catch (SQLException e) {
e.printStackTrace();
}
ResultSet rs = null;
try {
ps.setInt(1,this.code);
rs = ps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
try {
while(rs.next()){
Integer id=rs.getInt("ID");
Date date=rs.getDate("TRADE_DATE");
Integer code=rs.getInt("SECURITIES_CODE");
String name=rs.getString("BOOK_NAME");
String marcket = rs.getString("MARCKET");
Integer purchasePrice=rs.getInt("PURCHASE_PRICE");
Integer purchaseNum=rs.getInt("PURCHASE_NUMBER");
Integer sellingPrice=rs.getInt("SELLING_PRICE");
Integer sellingNum=rs.getInt("SELLING_NUMBER");
Integer pl = rs.getInt("PL");
String memo = rs.getString("MEMO");
System.out.println(id+date.toString()+code+name+purchasePrice+purchaseNum+sellingPrice+sellingNum);
TradeLogRecord record = new TradeLogRecord(
id,
date,
code,
name,
marcket,
purchasePrice,
purchaseNum,
sellingPrice,
sellingNum,
pl,
memo);
recordList.add(record);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| [
"tabuchikenta@tabuchikenta.local"
] | tabuchikenta@tabuchikenta.local |
f7ea1413166b396b6f26c34a178a1abebcaf97af | 81b584c6fc70c85907f3f7209389fb6f7aadd46f | /PaxosHandoutLite/server/StateEntry.java | 4da1c8e3a391e90d53acd08d0b6a8fc49902dab7 | [] | no_license | tylermcdonnell/Paxos | 98255a63fa57a27302e725baa79f9a15d288696e | 183f0c965c563892480f0a1cd12056f88a1fa51e | refs/heads/master | 2021-01-10T02:27:19.212005 | 2015-11-11T00:15:28 | 2015-11-11T00:15:28 | 44,932,225 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,430 | java | package server;
import java.io.Serializable;
import client.Command;
/**
* A set of state entries comprise a state.
* @author Mike Feilbach
*
*/
public class StateEntry implements Serializable, Comparable<StateEntry>
{
private static final long serialVersionUID = 1L;
private Command command;
private int slotNumber;
public StateEntry(Command command, int slotNumber)
{
this.command = command;
this.slotNumber = slotNumber;
}
public Command getCommand()
{
return this.command;
}
public int getSlotNumber()
{
return this.slotNumber;
}
@Override
public String toString()
{
String retVal = "";
retVal += "StateEntry: <slotNum: " + this.slotNumber + ", " + this.command + ">";
return retVal;
}
@Override
public boolean equals(Object o)
{
if (o == null)
{
return false;
}
if (o == this)
{
return true;
}
if (o instanceof StateEntry)
{
StateEntry s = (StateEntry) o;
boolean slotNumEqual = this.getSlotNumber() == s.getSlotNumber();
boolean cmdEqual = this.getCommand().equals(s.getCommand());
if (slotNumEqual && cmdEqual)
{
return true;
}
}
return false;
}
public int compareTo(StateEntry otherEntry)
{
if (this.getSlotNumber() < otherEntry.getSlotNumber())
{
return -1;
}
else if (this.getSlotNumber() > otherEntry.getSlotNumber())
{
return 1;
}
else
{
// Equal.
return 0;
}
}
}
| [
"mikefeilbach@gmail.com"
] | mikefeilbach@gmail.com |
67b52312e155bec784eb5e94578f7e19e2e56c1d | 245238ff034cdc55f991dc8e37ae09cd9ff3ab41 | /reading-content-domain/src/main/java/com/jingqingyun/reading/domain/model/event/BookUpdatedEvent.java | b73947b5d28577b2b7e980344c9cdb5a94e942fe | [] | no_license | jingqingyun/reading-content | 6507f0c082dba6d678db3def1e6d31f7b323e1a0 | 9ce12f0f7afd573b9f777d82908b5fed7321d2e0 | refs/heads/master | 2023-05-30T23:11:46.758514 | 2021-06-25T02:22:57 | 2021-06-25T02:22:57 | 303,935,875 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 528 | java | package com.jingqingyun.reading.domain.model.event;
import ddd.Event;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* UpdateBookEvent
*
* @author jingqingyun
* @date 2020/10/14
*/
@Data
@NoArgsConstructor
public class BookUpdatedEvent implements Event {
private final String tag = "com.jingqingyun.reading.content.book.updated";
private Long bookId;
public BookUpdatedEvent(long bookId) {
this.bookId = bookId;
}
@Override
public String tag() {
return tag;
}
}
| [
"jingqingyun@baijiahulian.com"
] | jingqingyun@baijiahulian.com |
1d5c976c5751e8b435addcb8daae89ebf82ad7a0 | f5ec00c81a2cadb06ed089f06e47a6ad0c1cda49 | /softwareCoding/src/HW4/calendar1.java | 12176cffdbf24369cba48b2627e7888ba6324969 | [] | no_license | lee0507/javaProject | 4312a6883b70ec4583089c95e81dcd82bb2dd251 | 773a8d570a9ad6fdfbe59da4fe98826d1bec4412 | refs/heads/main | 2023-04-21T06:05:22.414191 | 2021-04-29T05:08:35 | 2021-04-29T05:08:35 | 353,230,502 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 4,551 | java | package HW4;
public class calendar1 {// 클래스 선언
public static void main(String[] args) {//메인으로부터 프로그램 시작
// TODO Auto-generated method stub
for (int k30_i = 1; k30_i < 13; k30_i++) {//for반복문을 k30_i는 1부터 k30_i가 13보다 작을 때까지 k30_i를 1씩 증가시키면서 수행한다.
System.out.printf(" %d월 =>", k30_i);//변수 k30_i를 화면에 출력한다.
for (int k30_j =1; k30_j < 32; k30_j++) {//for반복문을 k30_j는 1부터 k30_j가 32보다 작을 때까지 k30_j를 1씩 증가시키면서 수행한다.
if(k30_i == 1 && k30_j == 31) {//만약 k30_i가 1이고 k30_j가 31이면 break문을 수행한다.
System.out.printf("%d", k30_j);//변수 k30_j를 화면에 출력한다.
break;//마지막은 ,를 안찍기 위해서 조건이 만족될때 ,가 없는 내용을 출력하게 한다.
}
if(k30_i == 2 && k30_j == 28) {//만약 k30_i가 2이고 k30_j가 28이면 break문을 수행한다.
System.out.printf("%d", k30_j);//변수 k30_j를 화면에 출력한다.
break;//마지막은 ,를 안찍기 위해서 조건이 만족될때 ,가 없는 내용을 출력하게 한다.
}
if(k30_i == 3 && k30_j == 31) {//만약 k30_i가 3이고 k30_j가 31이면 break문을 수행한다.
System.out.printf("%d", k30_j);//변수 k30_j를 화면에 출력한다.
break;//마지막은 ,를 안찍기 위해서 조건이 만족될때 ,가 없는 내용을 출력하게 한다.
}
if(k30_i == 4 && k30_j == 30) {//만약 k30_i가 4이고 k30_j가 30이면 break문을 수행한다.
System.out.printf("%d", k30_j);//변수 k30_j를 화면에 출력한다.
break;//마지막은 ,를 안찍기 위해서 조건이 만족될때 ,가 없는 내용을 출력하게 한다.
}
if(k30_i == 5 && k30_j == 31) {//만약 k30_i가 5이고 k30_j가 31이면 break문을 수행한다.
System.out.printf("%d", k30_j);//변수 k30_j를 화면에 출력한다.
break;//마지막은 ,를 안찍기 위해서 조건이 만족될때 ,가 없는 내용을 출력하게 한다.
}
if(k30_i == 6 && k30_j == 30) {//만약 k30_i가 6이고 k30_j가 30이면 break문을 수행한다.
System.out.printf("%d", k30_j);//변수 k30_j를 화면에 출력한다.
break;//마지막은 ,를 안찍기 위해서 조건이 만족될때 ,가 없는 내용을 출력하게 한다.
}
if(k30_i == 7 && k30_j == 31) {//만약 k30_i가 7이고 k30_j가 31이면 break문을 수행한다.
System.out.printf("%d", k30_j);//변수 k30_j를 화면에 출력한다.
break;//마지막은 ,를 안찍기 위해서 조건이 만족될때 ,가 없는 내용을 출력하게 한다.
}
if(k30_i == 8 && k30_j == 31) {//만약 k30_i가 8이고 k30_j가 31이면 break문을 수행한다.
System.out.printf("%d", k30_j);//변수 k30_j를 화면에 출력한다.
break;//마지막은 ,를 안찍기 위해서 조건이 만족될때 ,가 없는 내용을 출력하게 한다.
}
if(k30_i == 9 && k30_j == 30) {//만약 k30_i가 9이고 k30_j가 30이면 break문을 수행한다.
System.out.printf("%d", k30_j);//변수 k30_j를 화면에 출력한다.
break;//마지막은 ,를 안찍기 위해서 조건이 만족될때 ,가 없는 내용을 출력하게 한다.
}
if(k30_i == 10 && k30_j == 31) {//만약 k30_i가 10이고 k30_j가 31이면 break문을 수행한다.
System.out.printf("%d", k30_j);//변수 k30_j를 화면에 출력한다.
break;//마지막은 ,를 안찍기 위해서 조건이 만족될때 ,가 없는 내용을 출력하게 한다.
}
if(k30_i == 11 && k30_j == 30) {//만약 k30_i가 11이고 k30_j가 30이면 break문을 수행한다.
System.out.printf("%d", k30_j);//변수 k30_j를 화면에 출력한다.
break;//마지막은 ,를 안찍기 위해서 조건이 만족될때 ,가 없는 내용을 출력하게 한다.
}
if(k30_i == 12 && k30_j == 31) {//만약 k30_i가 12이고 k30_j가 31이면 break문을 수행한다.
System.out.printf("%d", k30_j);//변수 k30_j를 화면에 출력한다.
break;//마지막은 ,를 안찍기 위해서 조건이 만족될때 ,가 없는 내용을 출력하게 한다.
}
System.out.printf("%d,", k30_j);//조건이 만족되지 않을 경우에는 계속해서 for문이 돌아 1월부터 12월까지의 날짜를 화면에 출력한다.
}
System.out.printf("\n");//월별로 출력을 다했을때는 줄바꿈을 출력한다.
}
}
}
| [
"2eastbow@gmail.com"
] | 2eastbow@gmail.com |
86b9f8a4a08b3a909c762e816089d07e5ae58b1d | 429116960d5f5bb9f09d9f2de9c48daf6603752f | /core/src/main/java/core/designpattern/creation/prototype/Vegetables.java | 7bd6c6f1ec247ef6f686775e887766448bf46a3a | [] | no_license | rogeryumnam/jse-examples | 7f8840441632fe112727bf1ce40f395bfecacaa9 | 604fd924818c492a0690858c28ca39711b43ec16 | refs/heads/master | 2021-01-13T02:30:48.313243 | 2016-12-05T14:34:46 | 2016-12-05T14:34:46 | 81,535,442 | 0 | 2 | null | 2017-02-10T06:43:15 | 2017-02-10T06:43:15 | null | UTF-8 | Java | false | false | 344 | java | package core.designpattern.creation.prototype;
public class Vegetables implements Prototype {
@Override
public Prototype clone() throws CloneNotSupportedException {
return (Vegetables) super.clone();
}
@Override
public boolean equals(Object object) {
return this.getClass() == object.getClass();
}
}
| [
"himansu.h.nayak@ericsson.com"
] | himansu.h.nayak@ericsson.com |
7fc7a7e6e8aa11c09dbb273e1af21f08d9984404 | 1dfcbff54bd4c60f0babf22366de904b8a8e1f6b | /app/src/main/java/com/demo/isabellebidou/movies/ServiceHandler.java | b244acf93675b4b109a6c94f027f351020f854e7 | [] | no_license | isabellebidou/movies | 24b712faa172a65ab05d3611cdc5da68976ac319 | fac18bfa9e858fe51bf212f94ab5fab2affcdc15 | refs/heads/master | 2020-03-29T23:48:33.466070 | 2018-09-26T21:06:48 | 2018-09-26T21:06:48 | 150,490,024 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,677 | java | package com.demo.isabellebidou.movies;
/**
* Created by isabelle on 14/09/16.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
*/
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
/**
* Making service call
* @url - url to make request
* @method - http request method
* */
public String getDataMovies(URL url) throws IOException {
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 100000;
try {
//URL url = new URL(url);
HttpURLConnection conn;
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(200000 /* milliseconds */);
conn.setConnectTimeout(300000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
// Log.d("debug", "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readStream(is);
// Log.d("content",contentAsString );
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
private static String readStream(InputStream in) {
StringBuilder sb = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(in));) {
String nextLine = "";
while ((nextLine = reader.readLine()) != null) {
sb.append(nextLine);
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
} | [
"isa.bidou@gmail.com"
] | isa.bidou@gmail.com |
5a0e4b97d400eba60f80cbe27728e31e41d85157 | 0eea21636d8a0304902669479aab35232f6c415a | /gen/com/android/eatemupgame/BuildConfig.java | ab0c5963ae8bd68c14b27fe3801536b466a9a011 | [] | no_license | MaXvanHeLL/EatEmUp | 98d7c5008e5a4e89b84b93a14678c1b6550be14d | fa4aafed9c71ec6faf7a007204f579ea24bcd201 | refs/heads/master | 2021-03-22T04:56:15.356329 | 2013-06-19T08:27:35 | 2013-06-19T08:27:35 | 10,745,360 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 165 | java | /** Automatically generated file. DO NOT MODIFY */
package com.android.eatemupgame;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | [
"mhoell@student.tugraz.at"
] | mhoell@student.tugraz.at |
5f838aca588d376ff9fb202166a89eb93457be1f | d459fe4d08627f2a16befb00adcb63ba0d252fbe | /src/Number.java | c54902a08b633b091b699dc4a3aee2b06f4ed90d | [] | no_license | ceilingcranes/Suduko | 0f8aae52e6688f0c7e4250cbcc00a0dfc25ddcd2 | f3c1a599eb496b7516097772f1fce5bed31efec8 | refs/heads/master | 2021-01-10T13:28:53.005774 | 2015-11-06T20:46:37 | 2015-11-06T20:46:37 | 45,706,460 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,079 | java | /**
* Number.java 01/27/07
*
* @author - Robert Glen Martin
* @author - School for the Talented and Gifted
* @author - Dallas ISD
*
* Copyright(c) 2008 Robert Glen Martin
* (http://martin.apluscomputerscience.com/)
*
* This code 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.
*
* This code 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.
*/
import info.gridworld.grid.Location;
import java.awt.Color;
public class Number
{
/** Original value for <code>type</code> */
public static final int ORIGINAL = 1;
/** Player value for <code>type</code> */
public static final int PLAYER = 2;
/** Cheat value for <code>type</code> */
public static final int CHEAT = 3;
/** Value for this number (0-9).<br>
* 0 is a special value meanging no value */
private int value;
/** The location for this number */
private Location location;
/** The type of this object. Possible values are
* Number.ORIGINAL, Number.PLAYER, and Number.CHEAT. */
private int type;
/**
* Constructs a number.
* @param val the value for this number (0-9).
* 0 is a special value meanging that this
* cell has not had a value chosen.
* @param loc the location for this number.
* @param t the type of this object. Possible values are
* Number.ORIGINAL, Number.PLAYER, and Number.CHEAT.
*/
public Number(int val, Location loc, int t)
{
value = val;
location = loc;
type = t;
}
/**
* Gets the text to be displayed in the grid.
* @return the text string.
*/
public String getText()
{
if (value != 0)
return "" + value;
else
return "";
}
/**
* Gets the value of the number.
* @return the value.
*/
public int getValue()
{
return value;
}
/**
* Gets the type of the number.
* @return the type.
*/
public int getType()
{
return type;
}
/**
* Gets the color used to display the number in the grid.
* The color depends on the type:<br>
* ORIGINAL values are colored BLACK<br>
* PLAYER values are colored BLUE<br>
* CHEAT values are colored RED
* @return the color for the text
*/
public Color getTextColor()
{
if (type == ORIGINAL)
return Color.BLACK;
else if (type == PLAYER)
return Color.BLUE;
else
return Color.RED;
}
/**
* Gets the background color for the number. This color
* is based on a alternating 3x3 boxes. Boxes are colored
* GRAY or WHITE with the upper left box being WHITE.
* @return the background color
*/
public Color getColor()
{
int locNumber = location.getRow() / 3 + location.getCol() / 3;
if (locNumber % 2 == 1)
return Color.GRAY;
else
return Color.WHITE;
}
}
| [
"maxine.hartnett@colorado.edu"
] | maxine.hartnett@colorado.edu |
a827e04b5da223baa9befe7d1b5117129b435907 | a4fe69f976b48f166b670a7e855540ab6fe92a08 | /app/src/main/java/com/guyaning/media/mediaplayer01/activity/AudioPlayerActivity.java | 1b94a7e0de7c191519021a6b53d37f6058af187e | [] | no_license | deyson-Gu/readBoy | cc770ddd1a19d23136a4404025bfbdd6e708f6a0 | 0bcb87a49e0c7e7a3b6ac9a29da3788d5250b37c | refs/heads/master | 2021-06-20T14:12:07.665330 | 2017-08-08T00:16:47 | 2017-08-08T00:16:47 | 52,066,081 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 14,818 | java | package com.guyaning.media.mediaplayer01.activity;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.media.audiofx.Visualizer;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.guyaning.media.mediaplayer01.IMusicService;
import com.guyaning.media.mediaplayer01.R;
import com.guyaning.media.mediaplayer01.bean.MediaItem;
import com.guyaning.media.mediaplayer01.service.MusicPlayService;
import com.guyaning.media.mediaplayer01.utils.LyricUtils;
import com.guyaning.media.mediaplayer01.utils.Utils;
import com.guyaning.media.mediaplayer01.view.BaseVisualizerView;
import com.guyaning.media.mediaplayer01.view.ShowLyricView;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.io.File;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class AudioPlayerActivity extends Activity {
@BindView(R.id.tv_artist)
TextView tvArtist;
@BindView(R.id.tv_name)
TextView tvName;
@BindView(R.id.rl_top)
RelativeLayout rlTop;
@BindView(R.id.tv_time)
TextView tvTime;
@BindView(R.id.seekbar_audio)
SeekBar seekbarAudio;
@BindView(R.id.btn_audio_playmode)
Button btnAudioPlaymode;
@BindView(R.id.btn_audio_pre)
Button btnAudioPre;
@BindView(R.id.btn_audio_start_pause)
Button btnAudioStartPause;
@BindView(R.id.btn_audio_next)
Button btnAudioNext;
@BindView(R.id.btn_lyrc)
Button btnLyrc;
@BindView(R.id.ll_bottom)
LinearLayout llBottom;
//频谱跳动的自定义view
@BindView(R.id.baseVisualizerView)
BaseVisualizerView baseVisualizerView;
//展示歌词的自定义view
@BindView(R.id.ShowLyricView)
com.guyaning.media.mediaplayer01.view.ShowLyricView ShowLyricView;
private int position;
private IMusicService iMusicService;
private BroadcastReceiver MyReveiver;
private Utils utils;
public static final int PROGRESS = 100;
private static final int SHOW_LYRIC = 101;
private boolean notification;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case SHOW_LYRIC:
//将当前播放的进度传递给歌词控件
try {
int currentPosition = iMusicService.getDurationPosition();
ShowLyricView.setCurrentTime(currentPosition);
handler.removeMessages(SHOW_LYRIC);
handler.sendEmptyMessage(SHOW_LYRIC);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
case PROGRESS:
try {
int currentPosition = iMusicService.getDurationPosition();
tvTime.setText(utils.stringForTime(currentPosition) + "/" + utils.stringForTime(iMusicService.getDuration()));
seekbarAudio.setProgress(currentPosition);
//先移动消息在更新
handler.removeMessages(PROGRESS);
handler.sendEmptyMessageDelayed(PROGRESS, 1000);
} catch (RemoteException e) {
e.printStackTrace();
}
break;
}
}
};
/**
* 服务连接绑定的回调
*/
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder iBinder) {
iMusicService = IMusicService.Stub.asInterface(iBinder);
if (iMusicService != null) {
try {
if (!notification) {
iMusicService.openAudio(position);
} else {
setViewData();
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
if (iMusicService != null) {
try {
iMusicService.stop();
iMusicService = null;
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initView();
initData();
getData();
bingAndStartService();
setListener();
}
private void setListener() {
seekbarAudio.setOnSeekBarChangeListener(new MySeekChangeListener());
}
class MySeekChangeListener implements SeekBar.OnSeekBarChangeListener {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
try {
iMusicService.seekTo(progress);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
private void initData() {
utils = new Utils();
EventBus.getDefault().register(this);
// MyReveiver = new MyReveiver();
////
// IntentFilter intentFilter = new IntentFilter(MusicPlayService.OPEN_AUDIO);
////
// registerReceiver(MyReveiver, intentFilter);
}
// class MyReveiver extends BroadcastReceiver {
//
// @Override
// public void onReceive(Context context, Intent intent) {
// showLyric();
// //为控件设置数据
// setViewData();
//
// checkModeState();
//
// setupVisualizerFxAndUi();
// }
//}
private Visualizer mVisualizer;
/**
* 生成一个VisualizerView对象,使音频频谱的波段能够反映到 VisualizerView上
*/
private void setupVisualizerFxAndUi()
{
int audioSessionid = 0;
try {
audioSessionid = iMusicService.getAudioSessionId();
} catch (RemoteException e) {
e.printStackTrace();
}
System.out.println("audioSessionid=="+audioSessionid);
mVisualizer = new Visualizer(audioSessionid);
// 参数内必须是2的位数
mVisualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);
// 设置允许波形表示,并且捕获它
baseVisualizerView.setVisualizer(mVisualizer);
mVisualizer.setEnabled(true);
}
@Override
protected void onPause() {
super.onPause();
if(isFinishing()){
mVisualizer.release();
}
}
//展示歌词
private void showLyric() {
LyricUtils lyricUtils = new LyricUtils();
try {
String path = iMusicService.getAudioPath();
path = path.substring(0, path.lastIndexOf("."));
File file = new File(path + ".lrc");
// if(!file.exists()){
// file = new File(name +".txt");
// }
lyricUtils.readLyricFile(file);
ShowLyricView.setLyrics(lyricUtils.getLyrics());
} catch (RemoteException e) {
e.printStackTrace();
}
if (lyricUtils.isExistsLyric()) {
handler.sendEmptyMessage(SHOW_LYRIC);
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void showViewData(MediaItem mediaItem) {
showLyric();
//为控件设置数据
setViewData();
checkModeState();
setupVisualizerFxAndUi();
}
/**
* 给控件设置数据
*/
private void setViewData() {
//为控件设置数据
try {
Toast.makeText(getBaseContext(), "收到广播了", Toast.LENGTH_SHORT).show();
tvArtist.setText(iMusicService.getArtist());
tvName.setText(iMusicService.getName());
handler.sendEmptyMessage(PROGRESS);
seekbarAudio.setMax(iMusicService.getDuration());
} catch (RemoteException e) {
e.printStackTrace();
}
}
/**
* 绑定和开启服务
*/
private void bingAndStartService() {
Intent intent = new Intent(this, MusicPlayService.class);
intent.setAction("com.guyaning.media.mediaPlayer01");
bindService(intent, serviceConnection, MusicPlayService.BIND_AUTO_CREATE);
//防止重复创建service
startService(intent);
}
private void getData() {
notification = getIntent().getBooleanExtra("Notification", false);
if (!notification) {
position = getIntent().getIntExtra("position", 0);
}
}
private void initView() {
setContentView(R.layout.activity_audio_player);
ButterKnife.bind(this);
ShowLyricView = (ShowLyricView) findViewById(R.id.ShowLyricView);
// ImageView rocketImage = (ImageView) findViewById(R.id.iv_icon);
// rocketImage.setBackgroundResource(R.drawable.animation_list);
// AnimationDrawable animationDrawable = (AnimationDrawable) rocketImage.getBackground();
// animationDrawable.start();
}
@OnClick({R.id.btn_audio_playmode, R.id.btn_audio_pre, R.id.btn_audio_start_pause, R.id.btn_audio_next, R.id.btn_lyrc})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.btn_audio_playmode:
//控制播放模式的改变
try {
int playMode = iMusicService.getPlayMode();
if (playMode == MusicPlayService.PLAYMODE_NORMAL) {
playMode = MusicPlayService.PLAYMODE_SINGLE;
} else if (playMode == MusicPlayService.PLAYMODE_SINGLE) {
playMode = MusicPlayService.PLAYMODE_ALL;
} else if (playMode == MusicPlayService.PLAYMODE_ALL) {
playMode = MusicPlayService.PLAYMODE_NORMAL;
} else {
playMode = MusicPlayService.PLAYMODE_NORMAL;
}
iMusicService.setPlayMode(playMode);
showModeState();
} catch (RemoteException e) {
e.printStackTrace();
}
break;
case R.id.btn_audio_pre:
try {
if (iMusicService != null) {
iMusicService.pre();
}
} catch (RemoteException e) {
e.printStackTrace();
}
break;
case R.id.btn_audio_start_pause:
//控制音频的暂停和播放
if (iMusicService != null) {
try {
if (iMusicService.isPlaying()) {
//设置为暂停,改变按钮的状态为播放状态
iMusicService.pause();
btnAudioStartPause.setBackgroundResource(R.drawable.btn_audio_start_selector);
} else {
//设置成相反的状态
iMusicService.start();
btnAudioStartPause.setBackgroundResource(R.drawable.btn_audio_pause_selector);
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
break;
case R.id.btn_audio_next:
try {
if (iMusicService != null) {
iMusicService.next();
}
} catch (RemoteException e) {
e.printStackTrace();
}
break;
case R.id.btn_lyrc:
break;
}
}
//模式的状态
private void showModeState() {
//控制播放模式的改变
try {
int playMode = iMusicService.getPlayMode();
if (playMode == MusicPlayService.PLAYMODE_NORMAL) {
btnAudioPlaymode.setBackgroundResource(R.drawable.btn_audio_playmode_normal_selector);
} else if (playMode == MusicPlayService.PLAYMODE_ALL) {
btnAudioPlaymode.setBackgroundResource(R.drawable.btn_audio_playmode_all_selector);
} else if (playMode == MusicPlayService.PLAYMODE_SINGLE) {
btnAudioPlaymode.setBackgroundResource(R.drawable.btn_audio_playmode_single_selector);
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
//模式的状态
private void checkModeState() {
//控制播放模式的改变
try {
int playMode = iMusicService.getPlayMode();
if (playMode == MusicPlayService.PLAYMODE_NORMAL) {
btnAudioPlaymode.setBackgroundResource(R.drawable.btn_audio_playmode_normal_selector);
} else if (playMode == MusicPlayService.PLAYMODE_ALL) {
btnAudioPlaymode.setBackgroundResource(R.drawable.btn_audio_playmode_all_selector);
} else if (playMode == MusicPlayService.PLAYMODE_SINGLE) {
btnAudioPlaymode.setBackgroundResource(R.drawable.btn_audio_playmode_single_selector);
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
handler.removeCallbacksAndMessages(null);
if (MyReveiver != null) {
unregisterReceiver(MyReveiver);
MyReveiver = null;
}
//取消注册
EventBus.getDefault().unregister(this);
if (serviceConnection != null) {
unbindService(serviceConnection);
serviceConnection = null;
}
super.onDestroy();
}
}
| [
"940917911@qq.com"
] | 940917911@qq.com |
0ea41b8aaf774ba3887b3e549815a8bf9d631985 | a2fe34ceac2f18d01b8db976e640dad153ea3143 | /RegularExpression/src/RegularExpressonnn/Token2.java | e3b281ccbf91a36e8b11498a40825ac83def3e03 | [] | no_license | sahunikash/Copy2 | 017cd9d60252b09c02c79df21c26db38efab2307 | b3b3a49481f7a52e4ff34dd6c853e628ee12a366 | refs/heads/master | 2020-04-08T11:46:52.095442 | 2018-11-27T10:56:35 | 2018-11-27T10:56:35 | 159,319,840 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 287 | java | package RegularExpressonnn;
import java.util.StringTokenizer;
public class Token2
{
public static void main(String[] args)
{
StringTokenizer st = new StringTokenizer("helloo mheieb hdeiek,hgeh,khsd","h");
while(st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
| [
"sahunikash@gmail.com"
] | sahunikash@gmail.com |
1be8248de60b076cee39bb7953cb1923c8722511 | 2a0eeb92aab91bd5ae6521cdf7f757429b238399 | /src/main/java/io/ehdev/android/drivingtime/adapter/EntryAdapter.java | 76fef047157bff395d1bb6b7352e4ce2b0f8ef0a | [
"MIT"
] | permissive | sudhi001/driving-time-tracker | a6afae638bc70ee360496f35c78bc3a8cf924d37 | 0a0e8abea73c2adfd23727f348a340d9650c566a | refs/heads/master | 2021-01-17T07:39:58.471360 | 2014-12-12T01:42:49 | 2014-12-12T01:42:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 699 | java | package io.ehdev.android.drivingtime.adapter;
import android.widget.BaseAdapter;
public abstract class EntryAdapter<T> extends BaseAdapter implements ReplaceDataSetAdapter<T> {
static final public int NO_VALUE_SELECTED = -1;
private int selected = -1;
abstract public T getItem(int position);
public void setSelected(int index){
this.selected = index;
notifyDataSetChanged();
}
public int getSelectedIndex(){
return selected;
}
public boolean isIndexSelected(int index){
return index == selected;
}
public void clearSelected(){
setSelected(NO_VALUE_SELECTED);
}
abstract public Class getClassName();
}
| [
"ethan@ehdev.io"
] | ethan@ehdev.io |
6c59984d4df677bb1fbcbed05c2b3692c2156ab0 | 6b884fe9e3edbbf550c39db5717241085dcbcfd0 | /control-base/src/main/java/fi/nls/oskari/control/data/DeleteUserLayerHandler.java | a3d751ef65e8b6844b1da7609c495802bc6263c6 | [
"MIT"
] | permissive | uhef/Oskari-Routing | 4265354c94f98e0fdb9fb561497c38b71bbaa906 | fcf55772e75416ae5ac435b58029f67dadafbece | refs/heads/master | 2021-01-20T02:05:26.872784 | 2015-05-18T12:47:47 | 2015-05-18T12:47:47 | 30,122,185 | 0 | 1 | null | 2016-03-09T21:34:14 | 2015-01-31T18:46:25 | Java | UTF-8 | Java | false | false | 2,685 | java | package fi.nls.oskari.control.data;
import fi.mml.portti.service.db.permissions.PermissionsService;
import fi.nls.oskari.annotation.OskariActionRoute;
import fi.nls.oskari.control.*;
import fi.nls.oskari.domain.map.userlayer.UserLayer;
import fi.nls.oskari.map.userlayer.service.UserLayerDbService;
import fi.nls.oskari.map.userlayer.service.UserLayerDbServiceIbatisImpl;
import fi.nls.oskari.permission.domain.Resource;
import fi.nls.oskari.service.ServiceException;
import fi.nls.oskari.util.ConversionHelper;
import fi.nls.oskari.util.JSONHelper;
import fi.nls.oskari.util.ResponseHelper;
import fi.nls.oskari.util.ServiceFactory;
/**
* Deletes user layer and its style if it belongs to current user.
* Expects to get layer id as http parameter "id".
*/
@OskariActionRoute("DeleteUserLayer")
public class DeleteUserLayerHandler extends ActionHandler {
private final static String PARAM_ID = "id";
//private final static Logger log = LogFactory.getLogger(DeleteAnalysisDataHandler.class);
private UserLayerDbService userLayerDbService = null;
public void setUserLayerDbService(final UserLayerDbService service) {
userLayerDbService = service;
}
@Override
public void init() {
super.init();
if(userLayerDbService == null) {
setUserLayerDbService(new UserLayerDbServiceIbatisImpl());
}
}
@Override
public void handleAction(ActionParameters params) throws ActionException {
if(params.getUser().isGuest()) {
throw new ActionDeniedException("Session expired");
}
final long id = ConversionHelper.getLong(params.getHttpParam(PARAM_ID), -1);
if(id == -1) {
throw new ActionParamsException("Parameter missing or non-numeric: " + PARAM_ID + "=" + params.getHttpParam(PARAM_ID));
}
final UserLayer userLayer = userLayerDbService.getUserLayerById(id);
if(userLayer == null) {
throw new ActionParamsException("User layer id didn't match any user layer: " + id);
}
if(!userLayer.isOwnedBy(params.getUser().getUuid())) {
throw new ActionDeniedException("User layer belongs to another user");
}
try {
// remove userLayer
userLayerDbService.deleteUserLayer(userLayer);
// write static response to notify success {"result" : "success"}
ResponseHelper.writeResponse(params, JSONHelper.createJSONObject("result", "success"));
} catch (ServiceException ex) {
throw new ActionException("Error deleting userLayer", ex);
}
}
} | [
"timo.mikkolainen@nls.fi"
] | timo.mikkolainen@nls.fi |
29e791542d7828a26d1e91fcb033d5279cc30859 | 06885acf1340469c3696e5f83a1d7c7a820fa076 | /src/main/java/tri/ComparatorHabitant.java | f2f648c82a8cfb8fe2012e7c8a68e23469b7d84d | [] | no_license | zhannasan/approche-objet | 9c70f30133696704fc3cf12792e048ada1d021a7 | 2588153fe80b7a116f76a80e644b559ffbc741a3 | refs/heads/master | 2021-06-25T17:48:50.513775 | 2019-12-01T14:51:09 | 2019-12-01T14:51:09 | 221,424,413 | 0 | 0 | null | 2021-04-26T19:42:41 | 2019-11-13T09:43:13 | Java | UTF-8 | Java | false | false | 300 | java | package tri;
import java.util.Comparator;
import sets.Pays;
public class ComparatorHabitant implements Comparator<Pays>{
@Override
public int compare(Pays p, Pays q) {
if(q.getnHabit()>p.getnHabit()){
return 1;
}else if (q.getnHabit()<p.getnHabit()){
return -1;
}
return 0;
}
}
| [
"j.santybay@gmail.com"
] | j.santybay@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.