text
stringlengths 10
2.72M
|
|---|
package com.espendwise.manta.web.controllers;
import com.espendwise.manta.model.view.GroupReportListView;
import com.espendwise.manta.service.GroupService;
import com.espendwise.manta.spi.AutoClean;
import com.espendwise.manta.spi.SuccessMessage;
import com.espendwise.manta.util.AppComparator;
import com.espendwise.manta.util.RefCodeNames;
import com.espendwise.manta.util.SelectableObjects;
import com.espendwise.manta.util.Utility;
import com.espendwise.manta.util.alert.ArgumentedMessage;
import com.espendwise.manta.util.criteria.ReportSearchCriteria;
import com.espendwise.manta.web.forms.GroupReportFilterForm;
import com.espendwise.manta.web.forms.GroupReportFilterResultForm;
import com.espendwise.manta.web.util.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
@RequestMapping(UrlPathKey.GROUP.REPORT)
@SessionAttributes({SessionKey.GROUP_REPORT_FILTER_RESULT, SessionKey.GROUP_REPORT_FILTER})
@AutoClean(SessionKey.GROUP_REPORT_FILTER_RESULT)
public class GroupReportFilterController extends BaseController {
private static final Logger logger = Logger.getLogger(GroupReportFilterController.class);
private GroupService groupService;
@Autowired
public GroupReportFilterController(GroupService reportService) {
this.groupService = reportService;
}
@RequestMapping(value = "", method = RequestMethod.GET)
public String filter(@ModelAttribute(SessionKey.GROUP_REPORT_FILTER) GroupReportFilterForm filterForm) {
return "group/report";
}
@RequestMapping(value = "/filter", method = RequestMethod.GET)
public String findGroup(WebRequest request,
@ModelAttribute(SessionKey.GROUP_REPORT_FILTER_RESULT) GroupReportFilterResultForm resultForm,
@ModelAttribute(SessionKey.GROUP_REPORT_FILTER) GroupReportFilterForm filterForm) throws Exception {
WebErrors webErrors = new WebErrors(request);
List<? extends ArgumentedMessage> validationErrors = WebAction.validate(filterForm);
if (!validationErrors.isEmpty()) {
webErrors.putErrors(validationErrors);
return "group/report";
}
doSearch(filterForm, resultForm);
return "group/report";
}
@RequestMapping(value = "/filter/sortby/{field}", method = RequestMethod.GET)
public String sort(@ModelAttribute(SessionKey.GROUP_REPORT_FILTER_RESULT) GroupReportFilterResultForm form, @PathVariable String field) throws Exception {
WebSort.sort(form, field);
return "group/report";
}
@ModelAttribute(SessionKey.GROUP_REPORT_FILTER_RESULT)
public GroupReportFilterResultForm init(HttpSession session) {
GroupReportFilterResultForm groupReportFilterResult = (GroupReportFilterResultForm) session.getAttribute(SessionKey.GROUP_REPORT_FILTER_RESULT);
if (groupReportFilterResult == null) {
groupReportFilterResult = new GroupReportFilterResultForm();
}
return groupReportFilterResult;
}
@ModelAttribute(SessionKey.GROUP_REPORT_FILTER)
public GroupReportFilterForm initFilter(HttpSession session, @PathVariable Long groupId) {
GroupReportFilterForm groupReportFilter = (GroupReportFilterForm) session.getAttribute(SessionKey.GROUP_REPORT_FILTER);
if (groupReportFilter == null || !groupReportFilter.isInitialized()) {
groupReportFilter = new GroupReportFilterForm(groupId);
groupReportFilter.initialize();
}
return groupReportFilter;
}
@SuccessMessage
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(@PathVariable(IdPathKey.GROUP_ID) Long groupId,
@ModelAttribute(SessionKey.GROUP_REPORT_FILTER) GroupReportFilterForm filterForm,
@ModelAttribute(SessionKey.GROUP_REPORT_FILTER_RESULT) GroupReportFilterResultForm resultForm) throws Exception {
logger.info("update()=> BEGIN");
logger.info("update()=> groupId: " + groupId);
List<GroupReportListView> selected = resultForm.getGroupReports().getNewlySelected();
List<GroupReportListView> deSelected = resultForm.getGroupReports().getNewlyDeselected();
if (!selected.isEmpty() || !deSelected.isEmpty()){
groupService.configureGroupAssocioation(groupId, Utility.toIds(selected), Utility.toIds(deSelected), RefCodeNames.GROUP_ASSOC_CD.REPORT_OF_GROUP);
}
doSearch(filterForm, resultForm);
logger.info("update()=> END.");
return "group/report";
}
private void doSearch (GroupReportFilterForm filterForm, GroupReportFilterResultForm resultForm) {
resultForm.reset();
ReportSearchCriteria criteria = new ReportSearchCriteria();
criteria.setGroupId(filterForm.getGroupId());
criteria.setUserId(getUserId());
criteria.setReportId(parseNumberNN(filterForm.getReportId()));
criteria.setReportName(filterForm.getReportName());
criteria.setReportNameMatchType(filterForm.getReportNameFilterType());
criteria.setShowConfiguredOnly(filterForm.getShowConfiguredOnly());
List<GroupReportListView> reports = groupService.findGroupReportViewsByCriteria(criteria);
if (!filterForm.getShowConfiguredOnly()){
criteria.setShowConfiguredOnly(true);
}
List<GroupReportListView> configuredReports = groupService.findGroupReportViewsByCriteria(criteria);
SelectableObjects<GroupReportListView> selableobj = new SelectableObjects<GroupReportListView>(
reports,
configuredReports,
AppComparator.GROUP_REPORT_LIST_VIEW_COMPARATOR
);
resultForm.setGroupReports(selableobj);
WebSort.sort(resultForm, GroupReportListView.REPORT_NAME);
}
}
|
package com.filiereticsa.arc.augmentepf.models;
import android.support.annotation.NonNull;
import android.support.design.widget.BaseTransientBottomBar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.filiereticsa.arc.augmentepf.R;
/**
* Created by Cécile on 09/06/2017.
*/
public class CustomSnackBar extends BaseTransientBottomBar<CustomSnackBar> {
/**
* Constructor for the transient bottom bar.
*
* @param parent The parent for this transient bottom bar.
* @param content The content view for this transient bottom bar.
* @param contentViewCallback The content view callback for this transient bottom bar.
*/
protected CustomSnackBar(@NonNull ViewGroup parent, @NonNull View content, @NonNull BaseTransientBottomBar.ContentViewCallback contentViewCallback) {
super(parent, content, contentViewCallback);
}
public static CustomSnackBar make(ViewGroup parent, int duration) {
// inflate custom layout
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.snackbar_guidance, parent, false);
// create with custom view
CustomSnackBar.ContentViewCallback callback= new CustomSnackBar.ContentViewCallback(view);
CustomSnackBar customSnackBar = new CustomSnackBar(parent, view, callback);
customSnackBar.setDuration(duration);
customSnackBar.getView().setBackgroundResource(R.color.colorPrimary);
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)view.getLayoutParams();
params.gravity = Gravity.TOP;
customSnackBar.getView().setLayoutParams(params);
return customSnackBar;
}
public void setText(String text){
TextView guideText = (TextView) getView().findViewById(R.id.guidance_text);
guideText.setText(text);
}
private static class ContentViewCallback
implements BaseTransientBottomBar.ContentViewCallback {
// view inflated from custom layout
private View view;
public ContentViewCallback(View view) {
this.view = view;
}
@Override
public void animateContentIn(int delay, int duration) {
// TODO: handle enter animation
}
@Override
public void animateContentOut(int delay, int duration) {
// TODO: handle exit animation
}
}
}
|
package uk.gov.companieshouse.reconciliation.company;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
/**
* Trigger a comparison of corporate body counts in Oracle and MongoDB.
*/
@Component
public class CompanyCountTrigger extends RouteBuilder {
@Override
public void configure() throws Exception {
from("{{endpoint.company_count.cron.tab}}")
.setBody(constant("{{query.oracle.corporate_body_count}}"))
.setHeader("Src", simple("{{endpoint.oracle.corporate_body_count}}"))
.setHeader("SrcName", simple("Oracle"))
.setHeader("Target", simple("{{endpoint.mongodb.company_profile_count}}"))
.setHeader("TargetName", simple("MongoDB"))
.setHeader("Comparison", simple("company profiles"))
.setHeader("Destination", simple("{{endpoint.output}}"))
.to("{{function.name.compare_count}}");
}
}
|
package com.oocl.ita.yapo.day3.exercise6;
public class Tank {
public static String state = "";
public Tank() {
// TODO Auto-generated constructor stub
}
public void fillTheTank(Tank tank) {
System.out.println("Fill: The tank has been filled up!");
state = "Filled";
}
public void emptyTheTank(Tank tank) {
System.out.println("Empty: The tank has been emptied!");
state = "Emptied";
}
public void finalize() {
if (state.equalsIgnoreCase("Filled")) {
System.out.println("Object: Tank is not empty!");
} else {
System.out.println("Object: Tank is empty!");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Tank tank = new Tank();
tank.fillTheTank(tank);
tank.emptyTheTank(tank);
System.gc();
}
}
|
package com.app.gnometown.View.Splash;
/**
* Created by andreinasarda on 17/4/16.
*
* Interface to hable SplashActivity View
*/
public interface SplashView {
void showLoader();
void hideLoader();
void showMessage(String message);
void goToMain();
}
|
package ro.ase.cts.tests.mocks;
import org.junit.experimental.categories.Categories;
import org.junit.runner.RunWith;
import ro.ase.cts.tests.*;
import ro.ase.cts.tests.categorii.GetPromovabilitateCategory;
@RunWith(Categories.class)
@Suite.SuiteClasses({TestGrupaMock.class, TestGrupa.class,TestGrupaSeparat.class})
@Categories.IncludeCategory(GetPromovabilitateCategory.class)
@Categories.ExcludeCategory(TesteUrgenteCategory.class)
public class SuitaCustom {
}
|
package newgame;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import matches.BracketMatchOpponents;
import matches.MatchOpponents;
import java.io.FileInputStream;
public class ButtonHandlerSimulateGame extends ButtonHandlerNewGame {
private Stage primaryStage;
void buttonSimulateObject() {
try {
ButtonHandlerNewGame bnw = new ButtonHandlerNewGame();
GroupSimulated groupSimulated = new GroupSimulated();
bnw.button6();
bnw.groupStyle();
bnw.raffleStyle();
bnw.setScene(primaryStage);
// when button is pressed
bnw.button6.setOnAction(eventPrevious);
bnw.groups.setOnAction(eventBrackets);
bnw.raffle.setOnAction(eventRaffle);
Pane root = new Pane();
root.getChildren().addAll(bnw.button6, bnw.groups, bnw.raffle,
groupSimulated.printGroup(),groupSimulated.printGroupSecond(),groupSimulated.printGroupThird(),
groupSimulated.printGroupFourth(),groupSimulated.printGroupFivth(),groupSimulated.printGroupSixth(),
groupSimulated.printGroupSeventh(),groupSimulated.printGroupEighth());
// create a scene
Scene scene = new Scene(root, 1650, 928);
FileInputStream inputBackground = new FileInputStream("C:\\Users\\Asus\\WorldCupSimulator\\src\\main\\resources\\groupsSimulated.jpg");
// create a image
Image image = new Image(inputBackground);
// create a background image
BackgroundImage backgroundimage = new BackgroundImage(image,
BackgroundRepeat.NO_REPEAT,
BackgroundRepeat.NO_REPEAT,
BackgroundPosition.CENTER,
BackgroundSize.DEFAULT);
// create Background
Background background = new Background(backgroundimage);
// set background
root.setBackground(background);
//set the scene
primaryStage.setScene(scene);
primaryStage.show();
} catch (Exception r) {
r.printStackTrace();
}
}
private EventHandler<ActionEvent> eventBrackets = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e)
{
BracketMatchOpponents bracketMatchOpponents = new BracketMatchOpponents();
bracketMatchOpponents.setArrayList(GroupSimulated.teamsMainList);
bracketMatchOpponents.chooseWinner();
ButtonHandlerBracketsGame bhbg = new ButtonHandlerBracketsGame();
bhbg.setScene(primaryStage);
bhbg.buttonBracketsObject();
}
};
private EventHandler<ActionEvent> eventRaffle = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e)
{
MatchOpponents matchOpponents = new MatchOpponents();
matchOpponents.setArrayList(GroupStageRand.teamsMainList);
matchOpponents.chooseWinner();
GroupSimulated.teamsMainList = matchOpponents.teamsMainList;
ButtonHandlerSimulateGame bhsg = new ButtonHandlerSimulateGame();
bhsg.setScene(primaryStage);
bhsg.buttonSimulateObject();
}
};
private EventHandler<ActionEvent> eventPrevious = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e)
{
PreviousGroup.teamsMainList = GroupSimulated.teamsMainList;
ButtonHandlerPreviousGame bhpg = new ButtonHandlerPreviousGame();
bhpg.setScene(primaryStage);
bhpg.buttonNewPreviousGame();
}
};
public void setScene(Stage primaryStage){
this.primaryStage = primaryStage;
}
}
|
package netease_music_test;
import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* Description:
*
* @author Baltan
* @date 2019-11-27 15:07
*/
public class MusicPlayer {
private Player player;
/**
* 开始播放
*
* @param filePath
*/
public void play(String filePath) {
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(new FileInputStream(filePath));
player = new Player(bis);
player.play();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JavaLayerException e) {
e.printStackTrace();
} finally {
stop();
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 停止播放
*/
public void stop() {
player.close();
}
}
|
/**
* Class MyJava2 extends Homework2 and implements Processing
*
* @author C. Thurston
* @version 5/7/2014
*/
public class MyJava2 extends Homework2 implements Processing
{
MyJava2()
{
}
public void createAssignment(int pages)
{
setPagesRead(pages);
setTypeHomework("Java");
}
public void doReading()
{
this.pagesRead -= 4; // subtract 4 from the current page count.
}
public String toString()
{
return getTypeHomework() + " - must read " + getPagesRead() + " pages.";
}
}
|
package net.optifine.entity.model;
import net.minecraft.client.model.ModelBase;
public class CustomEntityModel extends ModelBase {}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\optifine\entity\model\CustomEntityModel.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package com.note.databasehandler;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.note.model.Notes;
import java.util.ArrayList;
/**
* Created by nguyenlinh on 22/02/2017.
* class use to handle model and create db for app
* tyoe database : SQLite
* create CRUD
*/
public class DabaseHandler extends SQLiteOpenHelper {
Context context;
Notes note;
// db version
public static final int DATABASE_VERSION = 1;
// db name
public static final String DATABASE_NAME = "NoteDB";
//tbl name
public static final String TABLE_NOTES = "NewNotes";
public static final String TABLE_NEW_NOTES = "NewNotes";
// all column of table mNotes
public static final String KEY_ID = "Id";
public static final String KEY_TITLE = "Title";
public static final String KEY_CONTENT = "Content";
public static final String KEY_CREATED_DATE = "CreatedDate";
public static final String KEY_ALARM = "Alarm";
public static final String KEY_BACGROUND = "Backround";
public static final String KEY_IMAGES = "Images";
// string query create table mNotes
public static final String CREATE_TABLE_NOTES = "CREATE TABLE " + TABLE_NOTES + "("
+ KEY_ID + " INTEGER IDENTITY(1,1) PRIMARY KEY ,"
+ KEY_TITLE + " TEXT,"
+ KEY_CONTENT + " TEXT,"
+ KEY_CREATED_DATE + " TEXT,"
+ KEY_ALARM + " TEXT,"
+ KEY_BACGROUND + " TEXT,"
+ KEY_IMAGES + " TEXT" + ")";
public void delDB(Context context) {
context.deleteDatabase(DATABASE_NAME);
}
public DabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(CREATE_TABLE_NOTES);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);
onCreate(sqLiteDatabase);
}
public void CreateTable() {
SQLiteDatabase db = getWritableDatabase();
onCreate(db);
Log.d("Create table ", TABLE_NOTES);
}
public void dropTable() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);
onCreate(db);
Log.d("drop table ", TABLE_NOTES);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
public void addNote(Notes note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID,note.getID());
values.put(KEY_TITLE, note.getTitle());
values.put(KEY_CONTENT, note.getContent());
values.put(KEY_CREATED_DATE, note.getCreatedDate());
values.put(KEY_ALARM, note.getAlarm());
values.put(KEY_BACGROUND, note.getBackground());
values.put(KEY_IMAGES, note.getImages());
// insert row
db.insert(TABLE_NOTES, null, values);
db.close();
Log.d("Add Insert NOTE", note.toString() + " Id :" + (idMax() + 1));
}
//get note --------------
public Notes getNote(int Id) {
Notes notes = new Notes();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NOTES, new String[]{KEY_ID, KEY_TITLE, KEY_CONTENT, KEY_CREATED_DATE, KEY_ALARM, KEY_BACGROUND, KEY_IMAGES}, KEY_ID + "=?", new String[] { String.valueOf(Id) }, null, null, null, null);
if (cursor.moveToFirst()) {
notes.setID(cursor.getInt(0));
notes.setTitle(cursor.getString(1));
notes.setContent(cursor.getString(2));
notes.setCreatedDate(cursor.getString(3));
notes.setAlarm(cursor.getString(4));
notes.setBackground(cursor.getString(5));
notes.setImages(cursor.getString(6));
}
Log.d("Get Note", ""+notes.getID());
return notes;
}
// get allnote
public ArrayList<Notes> getAllNotes() {
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<Notes> arrNotes = new ArrayList<Notes>();
String selectQuery = "SELECT * FROM " + TABLE_NOTES;
Cursor cursor = db.rawQuery(selectQuery, null);
Log.d("Get all nots", "Note size :" + cursor.getCount());
if (cursor.moveToFirst()) {
Log.d("GetAll NOTE", "MoveToFirst");
do {
Notes notes = new Notes();
notes.setID(cursor.getInt(0));
notes.setTitle(cursor.getString(1));
notes.setContent(cursor.getString(2));
notes.setCreatedDate(cursor.getString(3));
notes.setAlarm(cursor.getString(4));
notes.setBackground(cursor.getString(5));
notes.setImages(cursor.getString(6));
arrNotes.add(notes);
Log.d("GetAll NOTE", notes.toString());
} while (cursor.moveToNext());
}
return arrNotes;
}
public ArrayList<Notes> getAllNotesDESC() {
SQLiteDatabase db = this.getWritableDatabase();
ArrayList<Notes> arrNotes = new ArrayList<Notes>();
String selectQuery = "SELECT * FROM " + TABLE_NOTES;
Cursor cursor = db.rawQuery(selectQuery, null);
Log.d("Get all nots", "Note size :" + cursor.getCount());
if (cursor.moveToLast()) {
Log.d("GetAll NOTE", "MoveToFirst");
do {
Notes notes = new Notes();
notes.setID(cursor.getInt(0));
notes.setTitle(cursor.getString(1));
notes.setContent(cursor.getString(2));
notes.setCreatedDate(cursor.getString(3));
notes.setAlarm(cursor.getString(4));
notes.setBackground(cursor.getString(5));
notes.setImages(cursor.getString(6));
arrNotes.add(notes);
Log.d("GetAll NOTE", notes.toString());
} while (cursor.moveToPrevious());
}
return arrNotes;
}
// count note
public int countNotes() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_NOTES;
Cursor cursor = db.rawQuery(selectQuery, null);
//cursor.close();
return cursor.getCount();
}
// get id mNotes max
public int idMax() {
SQLiteDatabase db = this.getReadableDatabase();
String select = "SELECT MAX(" + KEY_ID + ")" + " FROM " + TABLE_NOTES;
Cursor cursor = db.rawQuery(select, null);
int id = 0;
if (cursor.getCount() > 0) {
Log.d("item note count() :", "" +cursor.getCount());
cursor.moveToFirst();
id = cursor.getInt(0);
Log.d("item note id :", "" +id);
}
Log.d("Id max :", "" + id);
return id;
}
public int updateNotes(Notes notes) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, notes.getTitle());
values.put(KEY_CONTENT, notes.getContent());
values.put(KEY_CREATED_DATE, notes.getCreatedDate());
values.put(KEY_ALARM, notes.getAlarm());
values.put(KEY_BACGROUND, notes.getBackground());
values.put(KEY_IMAGES, notes.getImages());
int i = db.update(TABLE_NOTES, values, KEY_ID + "=?", new String[]{String.valueOf(notes.getID())});
db.close();
Log.d("UPDATE NOTE", notes.toString());
return i;
}
// delete note selected
public void deleteNotes(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NOTES, KEY_ID + "=?", new String[]{String.valueOf(id)});
db.close();
Log.d("DELETE NOTE", ""+id);
}
// del table mNotes if need
public void deleteAllNotes() {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("DELETE FROM " + TABLE_NOTES);
db.close();
Log.d("DELETE NOTE", "delete all mNotes");
}
}
|
import lejos.nxt.Button;
import lejos.nxt.Motor;
public class MoveForward
{
public static void main(String[] args)
{
System.out.println("Program 1");
Button.waitForAnyPress();
Motor.B.forward();
Motor.C.forward();
Button.waitForAnyPress();
Motor.B.stop();
Motor.C.stop();
}
}
|
package com.plumnix.cloud.config;
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.boot.actuate.context.ShutdownEndpoint;
import org.springframework.boot.actuate.health.HealthEndpoint;
import org.springframework.boot.actuate.info.InfoEndpoint;
import org.springframework.context.annotation.Configuration;
//import org.springframework.security.config.annotation.web.builders.HttpSecurity;
//import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
//@Configuration
public class ActuatorSecurityConfiguration /*extends WebSecurityConfigurerAdapter*/ {
/*@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.requestMatchers(EndpointRequest.to(ShutdownEndpoint.class)).hasRole("ADMIN")
.requestMatchers(EndpointRequest.to(HealthEndpoint.class, InfoEndpoint.class)).permitAll()
.requestMatchers(EndpointRequest.toAnyEndpoint()).fullyAuthenticated()
.and().httpBasic();
}*/
/*@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/").permitAll();
}*/
}
|
package in.swapnilsingh;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> integerArrayList = new ArrayList<Integer>();
// Here we can't use primitive types like int, double, float, char in the diamond operator
// We need to supply it Object like String.
// So wrapper classes like Integer, Double, Float comes in to the rescue of primitive data type.
// And this is where the concept of autoboxing and unboxing comes.
// ----------------- AUTOBOXING ---------------------
integerArrayList.add(Integer.valueOf(1));
// Here autoboxing is happening ... We're providing "primitive int" to it's wrapper class
// Integer.valueOf(primitive int)
integerArrayList.add(2);
// This syntax is also correct as java on compile time is converting the above statement to
// integerArrayList.add(Integer.valueOf(2)) ... basically java is doing autoboxing for us.
// ----------------- UNBOXING ---------------------
System.out.println(integerArrayList.get(0).intValue());
// Here unboxing is happening ... We're getting the 0th index of the ArrayList and then we're
// getting it's primitive integer value by using intValue() method ... basically unboxing.
System.out.println(integerArrayList.get(1));
// This syntax is also correct as java on compile time is converting the above statement to
// integerArrayList.get(1).intValue() ... basically java is doing unboxing for us.
}
}
|
package cn.itcast.demo03;
import java.util.ArrayList;
public class ArrayListPersonDemo {
public static void main(String[] args) {
ArrayList<Person> arr = new ArrayList<Person>();
arr.add(new Person("zhangsan","20"));
arr.add(new Person("lisi","22"));
arr.add(new Person("wangwu","25"));
for(int i = 0;i < arr.size();i++)
{
// Person a = arr.get(i);
System.out.println(arr.get(i));
// System.out.println(a.getName()+"...."+a.getAge());
}
}
}
|
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/*
* 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.
*/
/**
*
* @author rushi
*/
public class Bought extends javax.swing.JFrame {
/**
* Creates new form Items
*/
public Bought() {
initComponents();
String sql="Select * from signup;";
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/Unico","root","admin");
Statement st=con.createStatement();
ResultSet rs = st.executeQuery(sql);
int tmp=0;
while(rs.next())
{
String User=rs.getString("Username");
String Pwd=rs.getString("Password");
if ((Login.Uname.equals(User)) && (Login.Pass.equals(Pwd))){
try {
Class.forName("java.sql.DriverManager");
Connection con1 = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/unico","root","admin");
Statement st1 = (Statement) con1.createStatement();
String qu = "Select * from buy where Username = '"+Login.Uname+"';";
ResultSet rs1 = st1.executeQuery(qu);
while(rs1.next()){
String username = rs1.getString("Username");
String song = rs1.getString("Song");
String price = rs1.getString("Price");
String date = rs1.getString("Date");
model.addRow (new Object[]{username,song,price,date});
}
}catch (Exception e){
}
tmp++;
}
}
}catch (Exception e){
}
}
/**
* 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() {
jPanel6 = new javax.swing.JPanel();
Music = new javax.swing.JLabel();
Logout = new javax.swing.JLabel();
User = new javax.swing.JLabel();
Home = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
Background = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jPanel6.setBackground(new java.awt.Color(102, 102, 102));
jPanel6.setForeground(new java.awt.Color(102, 102, 102));
jPanel6.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
jPanel6MouseMoved(evt);
}
});
jPanel6.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
Music.setForeground(new java.awt.Color(255, 255, 255));
Music.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Background/Music.png"))); // NOI18N
Music.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
Music.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
MusicMouseMoved(evt);
}
});
Music.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
MusicMouseClicked(evt);
}
});
jPanel6.add(Music, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 90, -1, -1));
Logout.setForeground(new java.awt.Color(255, 255, 255));
Logout.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Background/Logout.png"))); // NOI18N
Logout.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
Logout.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
LogoutMouseMoved(evt);
}
});
Logout.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
LogoutMouseClicked(evt);
}
});
jPanel6.add(Logout, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 190, -1, -1));
User.setForeground(new java.awt.Color(255, 255, 255));
User.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Background/User.png"))); // NOI18N
User.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
User.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
UserMouseMoved(evt);
}
});
User.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
UserMouseClicked(evt);
}
});
jPanel6.add(User, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 140, -1, -1));
Home.setForeground(new java.awt.Color(255, 255, 255));
Home.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Background/Home.png"))); // NOI18N
Home.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
Home.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
HomeMouseMoved(evt);
}
});
Home.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
HomeMouseClicked(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
HomeMouseEntered(evt);
}
});
jPanel6.add(Home, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 40, 20, 20));
getContentPane().add(jPanel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 40, 500));
jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jTable1.setBackground(new java.awt.Color(0, 0, 0));
jTable1.setFont(new java.awt.Font("Microsoft JhengHei UI Light", 1, 12)); // NOI18N
jTable1.setForeground(new java.awt.Color(255, 255, 255));
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Username", "Song", "Price", "Date"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
});
jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
jTable1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jTable1.setGridColor(new java.awt.Color(102, 102, 102));
jTable1.setOpaque(false);
jTable1.setSelectionBackground(new java.awt.Color(153, 153, 153));
jTable1.setSelectionForeground(new java.awt.Color(0, 0, 0));
jScrollPane1.setViewportView(jTable1);
jPanel1.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 40, 660, 230));
Background.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Background/ede8db99397b584cb6d5d2be3809a3a2.jpg"))); // NOI18N
Background.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
BackgroundMouseMoved(evt);
}
});
jPanel1.add(Background, new org.netbeans.lib.awtextra.AbsoluteConstraints(-60, 0, 840, 740));
getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 0, 740, 500));
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void MusicMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_MusicMouseMoved
// TODO add your handling code here:
}//GEN-LAST:event_MusicMouseMoved
private void MusicMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_MusicMouseClicked
// TODO add your handling code here:
this.setVisible(false);
new Main().setVisible(true);
}//GEN-LAST:event_MusicMouseClicked
private void LogoutMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_LogoutMouseMoved
// TODO add your handling code here:
}//GEN-LAST:event_LogoutMouseMoved
private void LogoutMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_LogoutMouseClicked
// TODO add your handling code here:
this.setVisible(false);
new Login().setVisible(true);
}//GEN-LAST:event_LogoutMouseClicked
private void UserMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_UserMouseMoved
// TODO add your handling code here:
}//GEN-LAST:event_UserMouseMoved
private void UserMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_UserMouseClicked
// TODO add your handling code here:
this.setVisible(false);
new Personalize().setVisible(true);
}//GEN-LAST:event_UserMouseClicked
private void HomeMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_HomeMouseMoved
// TODO add your handling code here:
}//GEN-LAST:event_HomeMouseMoved
private void HomeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_HomeMouseClicked
// TODO add your handling code here:
this.setVisible(false);
new Home().setVisible(true);
}//GEN-LAST:event_HomeMouseClicked
private void HomeMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_HomeMouseEntered
// TODO add your handling code here:
}//GEN-LAST:event_HomeMouseEntered
private void jPanel6MouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel6MouseMoved
// TODO add your handling code here:
}//GEN-LAST:event_jPanel6MouseMoved
private void BackgroundMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_BackgroundMouseMoved
// TODO add your handling code here:
}//GEN-LAST:event_BackgroundMouseMoved
/**
* @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(Bought.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Bought.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Bought.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Bought.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 Bought().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel Background;
private javax.swing.JLabel Home;
private javax.swing.JLabel Logout;
private javax.swing.JLabel Music;
private javax.swing.JLabel User;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel6;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration//GEN-END:variables
}
|
package com.springstory.controller;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.springstory.service.MemberService;
import com.springstory.vo.Member;
@Controller
public class MemberController {
@Autowired
private MemberService memberService;
@RequestMapping(value = "/member.do", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
String name = memberService.getMemberName(1);
model.addAttribute("name", name);
return "member";
}
@RequestMapping(value = "/register.do", method = RequestMethod.GET)
public String registerForm() {
return "register";
}
@RequestMapping(value = "/login.do", method = RequestMethod.GET)
public String loginForm() {
return "login";
}
@RequestMapping(value = "/login.do", method = RequestMethod.POST)
public String login(Member member, Model model) {
Member memberInfo = memberService.login(member);
if (memberInfo == null) {
return "login";
} else {
model.addAttribute("username", memberInfo.getName());
return "index";
}
}
}
|
package net.asurovenko.netexam.events;
import net.asurovenko.netexam.network.models.Exam;
public class OpenExamResultEvent {
private Exam exam;
public OpenExamResultEvent(Exam exam) {
this.exam = exam;
}
public Exam getExam() {
return exam;
}
}
|
package member.desktop.pages.account;
import base.PageObject;
import global.Global;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class Member_Forget_Pass_PC_Page extends PageObject {
public static String page_url = Global.getConfig().getString("member.url") + "/user/forget-password";
@FindBy(css = "div > input[type='text']") private WebElement email_txtField;
@FindBy(css = ".next-btn-large") private WebElement submit_btn;
@FindBy(className = "buttons") private WebElement verifyEmail_btn;
@FindBy(css = ".mod-input-sms") private WebElement smsCode_txtField;
@FindBy(className = "primary") private WebElement verifyCode_btn;
@FindBy(className = "mod-sendcode-btn") private WebElement sendCode_btn;
public void inputEmail(String email) {
waitUntilPageReady();
waitUntilVisible(email_txtField);
this.email_txtField.sendKeys(email);
this.submit_btn.click();
}
public void clickVerifyEmailBtn() {
waitUntilPageReady();
waitUntilVisible(verifyEmail_btn);
this.verifyEmail_btn.click();
}
}
|
/*
* Copyright (C) 2019-2023 Hedera Hashgraph, LLC
*
* 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.hedera.mirror.common.domain.addressbook;
import com.hedera.mirror.common.domain.entity.EntityId;
import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.FetchType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.OneToMany;
import java.util.ArrayList;
import java.util.List;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Builder(toBuilder = true)
@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor(access = AccessLevel.PRIVATE) // For builder
public class AddressBook {
// consensusTimestamp + 1ns of transaction containing final fileAppend operation
@Id
private Long startConsensusTimestamp;
// consensusTimestamp of transaction containing final fileAppend operation of next address book
private Long endConsensusTimestamp;
@EqualsAndHashCode.Exclude
@Builder.Default
@OneToMany(
cascade = {CascadeType.ALL},
orphanRemoval = true,
fetch = FetchType.EAGER)
@JoinColumn(name = "consensusTimestamp")
private List<AddressBookEntry> entries = new ArrayList<>();
@ToString.Exclude
private byte[] fileData;
private EntityId fileId;
private Integer nodeCount;
}
|
package com.aprendoz_test.data.output;
import java.util.Date;
/**
* Generated for query "last_accessHQL" on 01/19/2015 07:59:26
*
*/
public class Last_accessHQLRtnType {
private String date;
private Date timeLoged;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Date getTimeLoged() {
return timeLoged;
}
public void setTimeLoged(Date timeLoged) {
this.timeLoged = timeLoged;
}
}
|
package jp.co.tau.web7.admin.supplier.mappers;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.ResultType;
import org.apache.ibatis.annotations.SelectProvider;
import jp.co.tau.web7.admin.supplier.dto.SelectItemDTO;
import jp.co.tau.web7.admin.supplier.mappers.common.provider.BaseProvider;
/**
* <p>ファイル名 : CommonMapper</p>
* <p>説明 : CommonMapper</p>
* @author nv-manh
* @since 2018/5/31
*/
@Mapper
public interface CommonMapper {
/**
* <p>説明 : getSelectItem</p> .
*
* @author truong.dx
* @since 2017/12/23
* @param tableNm Table name
* @param colCd Column code
* @param colNm Column name
* @return List<SelectItemDTO>
*/
@SelectProvider(type = BaseProvider.class, method = "getSelectItem")
List<SelectItemDTO> getSelectItem(String tableNm, String colCd, String colNm);
/**
*
* <p>説明 : getSelectItemWithCondition</p>
* @author nv-manh
* @since 2018/02/08
* @param tableNm Table name
* @param colCd Column code
* @param colNm Column name
* @param where Where condition
* @return List selected item
*/
@SelectProvider(type = BaseProvider.class, method = "getSelectItemWithCondition")
List<SelectItemDTO> getSelectItemWithCondition(String tableNm, String colCd, String colNm, String where);
/**
*
* <p>説明 : getColValue</p>
* @author nv-manh
* @since 2018/02/08
* @param tableNm Table name
* @param colNm Column name
* @return List column value
*/
@SelectProvider(type = BaseProvider.class, method = "getColValue")
List<String> getColValue(String tableNm, String colNm);
/**
*
* <p>説明 : getColValue</p>
* @author nv-manh
* @since 2018/02/08
* @param tableNm Table name
* @param colNm Column name
* @param where Where condition
* @return List column value
*/
@SelectProvider(type = BaseProvider.class, method = "getColValueWithCondition")
List<String> getColValueWithCondition(String tableNm, String colNm, String where);
/**
*
* <p>説明 : selectAll</p>
* @author hung.pd
* @since 2018/02/26
* @param tableNm Table name
* @return List column name
*/
@SelectProvider(type = BaseProvider.class, method = "selectAllWithoutAnotation")
@ResultType(Map.class)
List<Map<String, Object>> selectAllWithoutAnotation(String tableNm);
}
|
package interfaz;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.JScrollPane;
public class PanelInvitar extends JDialog {
private JPanel contentPane;
private JTable table;
public PanelInvitar() {
setBounds(100, 100, 571, 398);
setLocationRelativeTo(null);
setModal(true);
setTitle("Invitar Jugadores");
setResizable(false);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnCancelar = new JButton("Cancelar");
btnCancelar.setIcon(new ImageIcon(this.getClass().getResource("src/imagenes/cancelar20.png")));
btnCancelar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cancelar();
}
});
btnCancelar.setBounds(10, 339, 115, 23);
contentPane.add(btnCancelar);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(44, 67, 477, 227);
contentPane.add(scrollPane);
DefaultTableModel tableModel = new DefaultTableModel();
table = new JTable(tableModel);
table.setBounds(47, 55, 473, 250);
tableModel.addColumn("Nombre");
scrollPane.setViewportView(table);
JButton btnInvitar = new JButton("Invitar");
btnInvitar.setIcon(new ImageIcon(this.getClass().getResource("src/imagenes/invitar20.png")));
btnInvitar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
invitar();
}
});
btnInvitar.setBounds(440, 339, 115, 23);
contentPane.add(btnInvitar);
Vector<String> nombres = new Vector<String>();
//nombres.add("asd");
tableModel.addRow(nombres);
}
private void invitar() {
}
private void cancelar() {
this.dispose();
}
}
|
package com.youthchina.dto;
/**
* Created by zhongyangwu on 12/2/18.
*/
public interface HasStatus {
}
|
package org.movilforum.net.media;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public abstract class StreamManager {
protected String basePath;
protected String remotePort;
protected DatagramSocket socket;
protected DatagramSocket controlSocket;
protected FileOutputStream currentFile = null;
protected boolean ended = false;
public StreamManager(String basePath, String remotePort, DatagramSocket socket, DatagramSocket controlSocket) {
this.basePath = basePath;
this.remotePort = remotePort;
this.socket = socket;
this.controlSocket = controlSocket;
}
public abstract void startTransMission(String from) throws IOException;
protected void startTransMission(String from, String fileExtension) throws IOException{
if (this.currentFile != null) throw new RuntimeException("A call is being processed, cannot process incoming call yet ");
this.currentFile = new FileOutputStream(this.basePath + '/' + "call_from_" + from + "at" + System.currentTimeMillis() + "." + fileExtension);
}
public void saveContent(String from, byte[] content, int offset, int length) throws IOException{
this.currentFile.write(content, offset, length);
}
protected void sendData(byte[] data, int port) throws IOException{
DatagramPacket dataPacket = new DatagramPacket(data,data.length);
dataPacket.setPort(port);
dataPacket.setAddress(InetAddress.getByName("telefonica"));
if (!this.socket.isClosed()) this.socket.send(dataPacket);
}
protected byte[] receiveData(DatagramSocket socket) throws IOException{
byte [] buffer = new byte[1024]; //max is 16384
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
if (!this.socket.isClosed()){
this.socket.receive(packet);
//Data is saved
byte []receivedData = transformDataToBeConverted(packet.getData(), packet.getLength());
this.saveContent("",receivedData, 0, receivedData.length);
return packet.getData();
}
return new byte[0];
}
/**
* Used to perform data conversions from received previously to be stored on the file
* @param data
* @param length
* @return
*/
protected abstract byte[] transformDataToBeConverted(byte[] data, int length);
public void endTransmission(String from) throws IOException{
//Ends transmission
this.ended = true;
//from is not used because currently only one concurrent tr can be made
if (this.currentFile == null) throw new RuntimeException("No call is currently being made");
this.currentFile.flush();
this.currentFile.close();
this.currentFile = null;
this.socket.close();
this.controlSocket.close();
}
protected abstract void terminate() throws IOException;
}
|
package pacman.ghost;
/**
* GhostType contains all the valid ghosts;
* the current list of ghosts are:
* "BLINKY", "CLYDE", "INKY", "PINKY".
*/
public enum GhostType {
BLINKY,
CLYDE,
INKY,
PINKY;
}
|
package org.mge.ds.arrays;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PairsWithSumClosestToZero {
public static void main(String[] args) {
int[] arr = {-3, -4, -1, -2};
printResult(getPairs(arr));
}
public static void printResult(List<Pair> pairs){
for(Pair pair : pairs){
System.out.println(pair.getX() + " " + pair.getY());
}
}
public static List<Pair> getPairs(int[] arr){
Arrays.sort(arr);
List<Pair> pairs = new ArrayList<>();
int min = Integer.MAX_VALUE;
int i = 0, j = arr.length - 1;
while(i < j){
int s = Math.abs(arr[i] + arr[j]);
if(s < min){
min = s;
pairs.clear();
pairs.add(new Pair(arr[i], arr[j]));
} else if(s == min){
pairs.add(new Pair(arr[i], arr[j]));
}
if(arr[i] + arr[j] < 0) {
i++;
} else {
j--;
}
}
return pairs;
}
public static class Pair {
int x, y;
public Pair(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
// @Test
// public void listOfPairsWithMinSumTest() {
// assertEquals(Arrays.asList(Pair.of(-3, 3), Pair.of(-2, 2)), listOfPairsWithMinSum(new int[]{-3, 5, 4, 3, -2, 1, 2}));
// assertEquals(Collections.singletonList(Pair.of(1, 2)), listOfPairsWithMinSum(new int[]{3, 4, 1, 2}));
// assertEquals(Collections.singletonList(Pair.of(-2, -1)), listOfPairsWithMinSum(new int[]{-3, -4, -1, -2}));
// }
}
|
/*
* 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.wicket_sapporo.workshop01.page.session;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.StatelessForm;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.wicket_sapporo.workshop01.WS01Session;
import org.wicket_sapporo.workshop01.page.WS01TemplatePage;
/**
* サインイン画面の体で.
*
* @author Hiroto Yamakawa
*
*/
public class SimpleSignInPage extends WS01TemplatePage {
private static final long serialVersionUID = -8371810037545557093L;
private String userId;
private String passphrase;
/**
* Construct.
*/
public SimpleSignInPage() {
// 自分のページのフィールド変数とコンポーネントを関連づける様に CompoundPropertyModel を用意.
IModel<SimpleSignInPage> formModel = new CompoundPropertyModel<>(this);
// ログイン・ログアウトなどのステートフルにしたくない部分には Stateless コンポーネントを利用.
StatelessForm<SimpleSignInPage> form = new StatelessForm<SimpleSignInPage>("form", formModel) {
private static final long serialVersionUID = -4915291457682594278L;
@Override
protected void onSubmit() {
super.onSubmit();
if (WS01Session.get().signIn(userId, passphrase)) {
setResponsePage(SignedPage.class);
}
// 失敗したら FeedBackPanel がエラーメッセージを表示する様に、メッセージをセット.
error("サインイン失敗.");
}
};
add(form);
form.add(new FeedbackPanel("feedback"));
form.add(new RequiredTextField<String>("userId") {
private static final long serialVersionUID = 1651429085939866494L;
@Override
protected void onInitialize() {
super.onInitialize();
// コンポーネントの名称をセット
setLabel(Model.of("ユーザID"));
}
});
form.add(new PasswordTextField("passphrase") {
private static final long serialVersionUID = 5908552907006076177L;
@Override
protected void onInitialize() {
super.onInitialize();
// コンポーネントの名称をセット
setLabel(Model.of("パスフレーズ"));
}
});
}
}
|
package com.imwj.tmall.comparator;
import com.imwj.tmall.pojo.Product;
import java.util.Comparator;
/**
* @author langao_q
* @create 2019-12-14 11:55
* 销量排序(高 > 低)销量
*/
public class ProductSaleCountComparator implements Comparator<Product> {
@Override
public int compare(Product p1, Product p2) {
return p2.getReviewCount() - p1.getReviewCount();
}
}
|
package com.sporsimdi.action.home;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedProperty;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import com.sporsimdi.action.facade.EntityManagerDao;
import com.sporsimdi.action.service.MenuService;
import com.sporsimdi.model.base.ExtendedModel;
public class HomeBean<T extends ExtendedModel> implements Serializable {
private static final long serialVersionUID = 1957601917746764088L;
@EJB
private EntityManagerDao entityManagerDao;
private Long id;
@ManagedProperty(value="#{menuService}")
private MenuService menuService;
public MenuService getMenuService() {
return menuService;
}
public void setMenuService(MenuService menuService) {
this.menuService = menuService;
}
protected T instance;
public T getInstance() {
if (instance == null) {
if (getId() != null) {
instance = loadInstance();
} else {
instance = createInstance();
}
}
return instance;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public T loadInstance() {
return entityManagerDao.find(getClassType(), getId());
}
public T createInstance() {
try {
return getClassType().newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
@SuppressWarnings("unchecked")
private Class<T> getClassType() {
ParameterizedType parameterizedType = (ParameterizedType) getClass()
.getGenericSuperclass();
return (Class<T>) parameterizedType.getActualTypeArguments()[0];
}
public boolean isManaged() {
return getInstance().getId() != null;
}
@SuppressWarnings("unchecked")
public String save() {
if (isManaged()) {
setInstance((T) entityManagerDao.updateObject(getInstance()));
} else {
entityManagerDao.createObject(getInstance());
}
return menuService.goToLastScreen();
//return "saved";
}
@SuppressWarnings("unchecked")
public String saveWithoutNavigation() throws Exception {
try {
if (isManaged()) {
setInstance((T) entityManagerDao.updateObject(getInstance()));
} else {
entityManagerDao.createObject(getInstance());
}
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Hata", this.getClass().toString()));
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Hata", e.getLocalizedMessage()));
}
return "saved";
}
public String delete() throws Exception {
entityManagerDao.deleteObject(getInstance());
createInstance();
return "deleted";
}
public String cancel() {
return "cancelled";
}
public EntityManagerDao getEntityManagerDao() {
return entityManagerDao;
}
public void setEntityManagerDao(EntityManagerDao entityManagerDao) {
this.entityManagerDao = entityManagerDao;
}
public String delete(T t){
entityManagerDao.deleteObject(t);
return "deleted";
}
public void setInstance(T instance) {
this.instance = instance;
}
public void clearInstance() {
setInstance(null);
setId(null);
}
public void sayfaLoad() {
FacesContext fc = FacesContext.getCurrentInstance();
Map<String, String> pMap = fc.getExternalContext().getRequestParameterMap();
Iterator<Entry<String, String>> pIter = pMap.entrySet().iterator();
Map<String, String> parameterMap = new HashMap<String, String>();
while (pIter.hasNext()) {
Entry<String, String> entry = pIter.next();
parameterMap.put(entry.getKey(), entry.getValue());
}
HttpServletRequest servletRequest = (HttpServletRequest) fc.getExternalContext().getRequest();
String uri = servletRequest.getRequestURI();
menuService.getParameterStack().put(uri, parameterMap);
}
}
|
package com.shared.RTPpaket;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
public class RTPPacket implements Serializable {
int sequence;
int totalseq;
String data;
long timestamp;
String dataName;
private static final long serialVersionUID = 0656555L;
public void set(int seq, byte[] data) {
this.sequence = seq;
// this.data = new byte[data.length];
// System.arraycopy(this.data,0,data,0,this.data.length);
this.data = Base64.getEncoder().encodeToString(data);
timestamp = System.currentTimeMillis();
}
public void set(int seq, byte[] data, String dataName,int totalSquence) {
this.sequence = seq;
// this.data = new byte[data.length];
// System.arraycopy(this.data,0,data,0,this.data.length);
this.data = Base64.getEncoder().encodeToString(data);
timestamp = System.currentTimeMillis();
this.dataName = dataName;
}
// public void set(int seq) {
// this.sequence = seq;
// timestamp = System.currentTimeMillis();
// }
public byte[] getData() {
//return this.data.getBytes(StandardCharsets.UTF_8);
return Base64.getDecoder().decode(this.data);
}
public int getTotalseq() {
return totalseq;
}
// public String getData() {
// return data;
// }
public String getDataName() {
return dataName;
}
public int getSequence() {
return sequence;
}
public long getTimestamp() {
return timestamp;
}
}
|
package com.lyx.pattern.factory.abstractfactory;
public class ChangChengZhongQi implements IZhongQi {
}
|
package com.fnsvalue.skillshare.boimpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fnsvalue.skillshare.bo.ReportNotifyBO;
import com.fnsvalue.skillshare.dao.ReportNotifyDAO;
@Service
public class ReportNotifyBOImpl implements ReportNotifyBO {
@Autowired
private ReportNotifyDAO reportNotifyDAO;
@Override
public int reportnotifyadd(String REPORTNOTIFY_TO, String REPORTNOTIFY_BOARD_NO, String REPORTNOTIFY_BOARD_USER,
int REPORTNOTIFY_CNT, String REPORTNOTIFY_DT) {
// TODO Auto-generated method stub
return 0;
}
}
|
package com.goldgov.dygl.module.jijianinfo.service.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.goldgov.dygl.module.jijianinfo.domain.InnerPunishBean;
import com.goldgov.dygl.module.jijianinfo.service.IInnerPunishService;
import com.goldgov.dygl.module.partymemberrated.rated.services.PartyMemberRated;
import com.goldgov.portal.infomanage.service.InfoManage;
import com.goldgov.portal.infomanage.service.InfoQuery;
@Service("innerPunishServiceImpl")
public class InnerPunishServiceImpl implements IInnerPunishService {
@Autowired
@Qualifier("dataSourceJIJIAN")
private DataSource dataSource;
@Override
public List<InnerPunishBean> getInnerPunishBeanList(String userID,
PartyMemberRated rated,Integer year) {
Connection conn = null;
PreparedStatement stmt=null;
ResultSet rs=null;
List<InnerPunishBean> list = new ArrayList<InnerPunishBean>();
try {
conn = dataSource.getConnection();
String sql = "select AA_ID as \"innerPunishId\",AA1 as \"punishTime\",AA4 as \"punishDept\",AA5 as \"punishType\",AA7 as \"loginId\","
+ "AA8 as \"remark\",AA2 as \"punishAuthorizeDept\",AA3 as \"punishAuthorizeLevel\" from JJ_AA t "
+ " where t.AA7 = "+userID;
if(rated!=null){
Date startTime = rated.getRatedTimeStart();
Date endTime = rated.getRatedTimeEnd();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String startTimeStr = sdf.format(startTime);
String endTimeStr = sdf.format(endTime);
sql += " and t.AA1 >=to_date('"+startTimeStr+"','yyyy-mm-dd') and t.AA1 <=to_date('"+endTimeStr+"','yyyy-mm-dd')";
}
if(year!=null){
sql += " and to_char(t.AA1,'yyyy') = '"+year+"'";
}
sql += " order by t.AA1 desc";
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
while (rs.next()) {
InnerPunishBean bean = new InnerPunishBean();
bean.setInnerPunishId(rs.getString(1));
bean.setPunishTime(rs.getDate(2));
bean.setPunishDept(rs.getString(3));
bean.setPunishType(rs.getInt(4));
bean.setLoginId(rs.getString(5));
bean.setRemark(rs.getString(6));
bean.setPunishAuthorizeDept(rs.getString(7));
bean.setPunishAuthorizeLevel(rs.getString(8));
list.add(bean);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if(rs!=null)rs.close();
if(stmt!=null)stmt.close();
if(conn!=null)conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return list;
}
@Override
public List<InfoManage> findlist(InfoQuery query) throws Exception {
List<InfoManage> list=new ArrayList<InfoManage>();
//从连接池中获取出一个连接
Connection conn = dataSource.getConnection();
PreparedStatement stmt=null;
ResultSet rs=null;
try {
//需要分页
String sql="";
if(query.getPageSize()!=-1){
//计算分页信息
stmt = conn.prepareStatement(getSql(false,query));
stmt.setInt(1, query.getSearchInfoType());
rs = stmt.executeQuery();
rs.next();
Long count=rs.getLong(1);
query.calculate(count);
rs.close();
stmt.close();
sql=getSql(true,query)+" LIMIT ?,?";
}else{
sql=getSql(true,query);
}
stmt = conn.prepareStatement(sql);
stmt.setInt(1, query.getSearchInfoType());
if(query.getPageSize()!=-1){
stmt.setInt(2, query.getFirstResult());
stmt.setInt(3, query.getPageSize());
}
rs = stmt.executeQuery();
while (rs.next()) {
InfoManage ue=new InfoManage();
ue.setInfoId(rs.getString(1));
ue.setInfoTitle(rs.getString(2));
ue.setPublishId(rs.getString(3));
ue.setPublishName(rs.getString(4));
ue.setPublishTime(rs.getDate(5));
ue.setPublishStatus(rs.getInt(6));
ue.setInfoType(rs.getInt(7));
ue.setInfoSummary(rs.getString(8));
ue.setInfoContent(rs.getString(9));
ue.setGroupId(rs.getString(10));
ue.setOriginType(rs.getInt(11));
ue.setFileGroupID(rs.getString(12));
ue.setVideoId(rs.getString(13));
ue.setOrderNum(rs.getInt(14));
ue.setIsTop(rs.getInt(15));
list.add(ue);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(rs!=null)rs.close();
if(stmt!=null)stmt.close();
if(conn!=null)conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return list;
}
public static String getSql(Boolean isList,InfoQuery query){
StringBuffer sql=new StringBuffer();
if(isList){
sql.append(" select INFO_ID , ");
sql.append(" INFO_TITLE , PUBLISH_ID , ");
sql.append(" PUBLISH_NAME , PUBLISH_TIME , ");
sql.append(" PUBLISH_STATUS , INFO_TYPE,");
sql.append(" INFO_SUMMARY, INFO_CONTENT,");
sql.append(" GROUP_ID, ORIGIN_TYPE,");
sql.append(" FILE_GROUP_ID, VIDEO_ID,");
sql.append(" ORDER_NUM, IS_TOP");
}else{
sql.append(" select count(INFO_ID) ");
}
sql.append(" from SH_INFO_MANAGE where INFO_TYPE = ? and PUBLISH_STATUS = 1");
if(query.getSearchInfoTitle()!=null&&!query.getSearchInfoTitle().equals("")){
sql.append(" and info_title like '%"+query.getSearchInfoTitle()+"%'");
}
if(isList){
sql.append(" order by IS_TOP desc nulls last,PUBLISH_TIME desc nulls last,ORDER_NUM desc nulls last ");
}
return sql.toString();
}
}
|
package edu.cmu.lti.oaqa.openqa.test.team10.passage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.solr.client.solrj.SolrServerException;
import org.jsoup.Jsoup;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import edu.cmu.lti.oaqa.framework.data.Keyterm;
import edu.cmu.lti.oaqa.framework.data.PassageCandidate;
import edu.cmu.lti.oaqa.framework.data.RetrievalResult;
import edu.cmu.lti.oaqa.openqa.hello.passage.SimplePassageExtractor;
/**
* This class returned a list of passage candidates based on bm25 scoring algirthom
* The candidate passage windows are all spans between two keywords
* @author Yifei
*
*/
public class Bm25BioPassageExtractor extends SimplePassageExtractor {
@Override
protected List<PassageCandidate> extractPassages(String question, List<Keyterm> keyterms,
List<RetrievalResult> documents) {
Map<String,Double> KeyIdf = new HashMap<String,Double>();
List<String> keys = Lists.transform(keyterms, new Function<Keyterm, String>() {
public String apply(Keyterm keyterm) {
return keyterm.getText();
}
});
for ( String keyterm : keys ) {
KeyIdf.put(keyterm, (double) 0);
}
for (RetrievalResult document : documents) {
String id = document.getDocID();
String htmlText = null;
try {
htmlText = wrapper.getDocText(id);
} catch (SolrServerException e) {
e.printStackTrace();
}
String text = Jsoup.parse(htmlText).text().replaceAll("([\177-\377\0-\32]*)", "")/* .trim() */;
text = text.substring(0, Math.min(5000, text.length()));
for ( String keyterm : keys ) {
Pattern p = Pattern.compile( keyterm );
Matcher m = p.matcher( text );
if ( m.find() ) {
double tmp = KeyIdf.get(keyterm);
tmp++;
KeyIdf.put(keyterm, tmp);
}
}
}
for ( String keyterm : keys ) {
double tmp = KeyIdf.get(keyterm);
tmp = Math.log((documents.size()+1)/(tmp+0.5));
KeyIdf.put(keyterm, (double) tmp);
}
List<PassageCandidate> result = new ArrayList<PassageCandidate>();
for (RetrievalResult document : documents) {
System.out.println("RetrievalResult: " + document.toString());
String id = document.getDocID();
try {
String htmlText = wrapper.getDocText(id);
String text = Jsoup.parse(htmlText).text().replaceAll("([\177-\377\0-\32]*)", "");
text = text.substring(0, Math.min(5000, text.length()));
System.out.println(text);
Bm25PassageCandidateFinder finder = new Bm25PassageCandidateFinder(id, text,
new KeytermWindowScorerSum());
List<String> keytermStrings = Lists.transform(keyterms, new Function<Keyterm, String>() {
public String apply(Keyterm keyterm) {
return keyterm.getText();
}
});
List<PassageCandidate> passageSpans = finder.extractPassages(keytermStrings
.toArray(new String[0]),KeyIdf);
for (PassageCandidate passageSpan : passageSpans)
result.add(passageSpan);
} catch (SolrServerException e) {
e.printStackTrace();
}
}
return result;
}
}
|
package com.goodhealth.comm.util.encrypt;
import java.security.MessageDigest;
/**
* @ClassName MD5Util
* @Description 使用MessageDigest 计算MD5摘要 摘要算法是不可逆的
* @Author WDH
* @Date 2019/8/14 11:10
* @Version 1.0
**/
public class MD5Util {
public static void main(String[] args){
String origin = "1234567890";
// 默认MD5计算得到128 bit的摘要,即32个 16进制位
String result_32 = MD5_32(origin, "utf-8");
// 默认MD5计算得到即16个 16进制位
String result_16 = MD5_16(origin, "utf-8");
}
private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
/**
* MD5算法,统一返回大写形式的摘要结果,默认固定长度是 128bit 即 32个16进制位
* String origin :需要进行MD5计算的字符串
* String charsetname :MD5算法的编码
*/
public static String MD5_32(String origin, String charsetname) {
String resultString = null;
try {
// 1,创建MessageDigest对象
MessageDigest md = MessageDigest.getInstance("MD5");
// 2,向MessageDigest传送要计算的数据;传入的数据需要转化为指定编码的字节数组并计算摘要
byte[] bytesResult = md.digest(origin.getBytes(charsetname));
// 3,将字节数组转换为16进制位
resultString = byteArrayToHexString( bytesResult );
} catch (Exception e) {
e.printStackTrace();
}
// 统一返回大写形式的字符串摘要
return resultString;
}
/**
* 获取 16位的MD5摘要,就是截取32位结果的中间部分
*/
public static String MD5_16(String origin, String charsetname) {
return MD5_32(origin, charsetname).substring(8,24);
}
/**
* 将1个字节(1 byte = 8 bit)转为 2个十六进制位
* 1个16进制位 = 4个二进制位 (即4 bit)
* 转换思路:最简单的办法就是先将byte转为10进制的int类型,然后将十进制数转十六进制
*/
private static String byteToHexString(byte b) {
// byte类型赋值给int变量时,java会自动将byte类型转int类型,从低位类型到高位类型自动转换
int n = b;
// 将十进制数转十六进制
if (n < 0) {
n += 256;
}
int d1 = n / 16;
int d2 = n % 16;
// d1和d2通过访问数组变量的方式转成16进制字符串;比如 d1 为12 ,那么就转为"c"; 因为int类型不会有a,b,c,d,e,f等表示16进制的字符
return hexDigits[d1] + hexDigits[d2];
}
/**
* 将字节数组里每个字节转成2个16进制位的字符串后拼接起来
*/
private static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++){
resultSb.append(byteToHexString(b[i]));
}
return resultSb.toString();
}
}
|
package com.qa.demo.ex5;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions(features = "src/test/resources/TeaTesting.feature")
public class Task5Test {
}
|
package edu.illinois.finalproject.PlayerProfile;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import net.rithms.riot.api.endpoints.match.dto.MatchReference;
import java.util.ArrayList;
import java.util.List;
import edu.illinois.finalproject.ExtendedSummoner;
import edu.illinois.finalproject.LolConstants;
import edu.illinois.finalproject.R;
/**
* Created by liam on 11/20/17.
*/
public class MatchAdapter extends RecyclerView.Adapter<MatchAdapter.ViewHolder> {
ExtendedSummoner extendedSummoner = null;
private List<MatchReference> MatchList = new ArrayList<>();
public MatchAdapter(ExtendedSummoner extendedSummoner) {
if (extendedSummoner.matches != null) {
MatchList.addAll(extendedSummoner.matches.getMatches());
this.extendedSummoner = extendedSummoner;
}
}
public MatchAdapter(java.util.List<MatchReference> matches) {
MatchList.addAll(matches);
}
public void addMatch(MatchReference givenMatch) {
MatchList.add(givenMatch);
}
@Override
public int getItemViewType(int position) {
MatchReference match = MatchList.get(position);
return R.layout.single_match_layout;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View singleMatch = LayoutInflater.from(parent.getContext()).
inflate(viewType, parent, false);
return new ViewHolder(singleMatch);
}
@Override
public void onBindViewHolder(MatchAdapter.ViewHolder holder, int position) {
final MatchReference currentMatch = MatchList.get(position);
String queueType = "";
if (currentMatch.getQueue() == 420) {
queueType = "5v5 Ranked Solo";
} else if (currentMatch.getQueue() == 440) {
queueType = "5v5 Ranked Flex";
} else if (currentMatch.getQueue() == 400) {
queueType = "5v5 Draft Pick";
} else if (currentMatch.getQueue() == 430) {
queueType = "5v5 Blind Pick";
}
holder.headerTextview.setText(String.valueOf(queueType));
holder.score.setText(String.valueOf(currentMatch.getLane()));
net.rithms.riot.api.endpoints.static_data.dto.Champion currentChampion =
LolConstants.championMap.get(currentMatch.getChampion());
String champName = currentChampion.getKey();
String summonerIconUrl = "http://ddragon.leagueoflegends.com/cdn/" +
extendedSummoner.relm.getDd() + "/img/champion/" +
champName + ".png";
final Context context = holder.itemView.getContext();
Picasso.with(context).load(summonerIconUrl).into(holder.champPicture);
}
@Override
public int getItemCount() {
return MatchList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public View itemView;
public TextView headerTextview;
public TextView score;
public ImageView champPicture;
public ViewHolder(View itemView) {
super(itemView);
this.itemView = itemView;
this.headerTextview = itemView.findViewById(R.id.MatchHeading);
this.score = itemView.findViewById(R.id.MatchScore);
this.champPicture = itemView.findViewById(R.id.MatchChampion);
}
}
}
|
package com.quiz.projectWilayah.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.quiz.projectWilayah.dto.ProvinsiDto;
import com.quiz.projectWilayah.entity.ProvinsiEntity;
import com.quiz.projectWilayah.repository.ProvinsiRepository;
@Service
@Transactional
public class ProvinsiServiceImpl implements ProvinsiService {
@Autowired
private ProvinsiRepository provinsiRepository;
@Override
public List<ProvinsiEntity> getProvinsi() {
// TODO Auto-generated method stub
List<ProvinsiEntity> provinsiEntities = provinsiRepository.findAll();
return provinsiEntities;
}
@Override
public List<ProvinsiEntity> getProvinsiActive() {
// TODO Auto-generated method stub
List<ProvinsiEntity> provinsiEntities = provinsiRepository.findAllProvinsiActive();
return provinsiEntities;
}
@Override
public ProvinsiEntity insertProvinsi(ProvinsiDto dto) {
// TODO Auto-generated method stub
ProvinsiEntity provinsiEntity = convertToProvinsiEntity(dto);
provinsiRepository.save(provinsiEntity);
return provinsiEntity;
}
@Override
public ProvinsiEntity updateProvinsi(Integer idProv, ProvinsiDto dto) {
// TODO Auto-generated method stub
ProvinsiEntity provinsiEntity = provinsiRepository.findById(idProv).get();
provinsiEntity.setProvinsiCode(dto.getProvinsiCode());
provinsiEntity.setProvinsiName(dto.getProvinsiName());
provinsiRepository.save(provinsiEntity);
return provinsiEntity;
}
@Override
public ProvinsiEntity deleteProvinsi(Integer idProv) {
// TODO Auto-generated method stub
ProvinsiEntity provinsiEntity = provinsiRepository.findById(idProv).get();
provinsiEntity.setStatus(2);
provinsiRepository.save(provinsiEntity);
return provinsiEntity;
}
@Override
public List<ProvinsiEntity> getProvinsiById(Integer idProv) {
// TODO Auto-generated method stub
List<ProvinsiEntity> provinsiEntity = provinsiRepository.findProvinsiActiveById(idProv);
return provinsiEntity;
}
@Override
public List<ProvinsiEntity> getProvinsiByCode(String codeProv) {
// TODO Auto-generated method stub
List<ProvinsiEntity> provinsiEntity = provinsiRepository.findProvinsiActiveByCode(codeProv);
return provinsiEntity;
}
public ProvinsiEntity convertToProvinsiEntity(ProvinsiDto dto) {
ProvinsiEntity provinsiEntity = new ProvinsiEntity();
provinsiEntity.setProvinsiCode(dto.getProvinsiCode());
provinsiEntity.setProvinsiName(dto.getProvinsiName());
provinsiEntity.setStatus(1);
return provinsiEntity;
}
}
|
/*
* FileName: SpringSerialNumberService.java
* Description:
* Company: 南宁超创信息工程有限公司
* Copyright: ChaoChuang (c) 2006
* History: 2006-12-16 (Jyb) 1.0 Create
*/
package com.spower.basesystem.serialnumber.service.spring;
import java.util.List;
import com.spower.basesystem.serialnumber.service.ISerialNumberService;
import com.spower.basesystem.serialnumber.service.dao.ISerialNumberDao;
import com.spower.basesystem.serialnumber.valueobject.SysSerialNumber;
/**
* @author Jyb
* @version 1.0, 2006-12-16
*/
public class SpringSerialNumberService implements ISerialNumberService {
private ISerialNumberDao serialNumberDao;
public String getSerialNumber(String classifyIdentifier, String prefixIdentifier, int length) {
List list = this.serialNumberDao.selectSysSerialNumber(
classifyIdentifier, prefixIdentifier);
SysSerialNumber sn;
if (list == null || list.size() <= 0) {
sn = new SysSerialNumber();
sn.setClassifyIdentifier(classifyIdentifier);
sn.setPrefixIdentifier(prefixIdentifier);
sn.setSerialNumber(new Integer(0));
} else {
sn = (SysSerialNumber) list.get(0);
}
Integer value = new Integer(sn.getSerialNumber().intValue() + 1);
String tmp = value.toString();
if (tmp.length() > length) {
sn.setSerialNumber(new Integer(1));
tmp = "1";
} else {
sn.setSerialNumber(value);
}
this.serialNumberDao.save(sn);
while (tmp.length() < length) {
tmp = "0" + tmp;
}
return prefixIdentifier + tmp;
}
/**
* @param serialNumberDao The serialNumberDao to set.
*/
public void setSerialNumberDao(ISerialNumberDao serialNumberDao) {
this.serialNumberDao = serialNumberDao;
}
}
|
package chatroom.client.gui;
import chatroom.client.Client;
import chatroom.model.message.LoginResponses;
import javafx.application.Platform;
import java.util.ArrayList;
public class Bridge {
Client model;
ClientGuiMain gui;
public Bridge(Client client, ClientGuiMain clientGuiMain) {
this.model = client;
this.gui = clientGuiMain;
}
//called by the gui to send the login data TODO: ---ERSETZEN------
public void sendLoginData(String username, String password) {
model.login(username, password);
}
//called by the model to let the gui know whether the login succeeded or not TODO: ---BENUTZEN im MODEL------
public void onServerLoginAnswer(LoginResponses answer) {
Platform.runLater(() -> gui.onLoginAnswer(answer));
}
//sends the message TODO: ---ERSETZEN------
public void SendMessage(String message) {
model.sendMessage(message);
}
//Adds new Message to the View... Attention!!! The Own message will not be displayed automaticly please add it to the view TODO: ---BENUTZEN im MODEL------
public void AddMessageToView(String username, String message) {
Platform.runLater(() -> gui.AddMessage(username, message));
}
//gets The username from the ModelTODO: TODO: ---ERSETZEN------
public String getUsername() {
return model.getUsername();
}
//gets the rooms from the Model TODO: ---ERSETZEN------
public ArrayList<String> getRooms() {
return model.getRooms();
}
//Updates the room view by adding or removing rooms TODO: ---BENUTZEN im MODEL------
public void onRoomUpdate(ArrayList<String> rooms) {
Platform.runLater(() -> gui.onRoomUpdate(rooms));
}
//requests all users TODO: ---ERSETZEN------
public ArrayList<String> getAllUsers() {
return (ArrayList<String>) model.getAllUsers();
}
//requests users from current room TODO: ---ERSETZEN------
public ArrayList<String> getUsersFromSelection(String room) {
return (ArrayList<String>) model.getAllUsers();
}
//connects to the input adress TODO: ---ERSETZEN------
public void ConnectToAdress(String adress) {
model.ConnectToAdress(adress);
}
//has to be triggered after succesfull connection TODO: ---BENUTZEN im MODEL------
public void onConnectionAttemtResponse(boolean b) {
Platform.runLater(() -> gui.onConnectionAttemtResponse(b));
}
//requests room change TODO: ---ERSETZEN------
public void requestRoomChange(String room) {
model.requestRoomChange(room);
}
//Has to be triggered after succesfull roomchange TODO: ---BENUTZEN im MODEL------
public void onRoomChangeRequestAccepted(String room) {
Platform.runLater(() -> gui.onRoomChange(room));
}
//updates the all users view TODO: ---BENUTZEN im MODEL------
public void allUsersUpdate(ArrayList<String> newAllUsers) {
Platform.runLater(() -> gui.homeGui.allUsersUpdate(newAllUsers));
}
//updates current room users view TODO: ---BENUTZEN im MODEL------
public void userRoomUpdate(ArrayList<String> newCurrentUsers) {
Platform.runLater(() -> gui.homeGui.userRoomUpdate(newCurrentUsers));
}
//this method is for alertboxes. Like kicked message, warning or banned TODO: ---BENUTZEN im MODEL------
public void issueBox(String message, boolean closeWindow) {
Platform.runLater(() -> gui.homeGui.showIssueAlert(message, closeWindow));
}
//this method is for operations that have to be run befor closing the window TODO: ---ERSETZEN------
public void runClosinOperations() {
model.stop();
}
public void sendPrivateMessage(String message, String targetUser) {
model.sendMessage(message, targetUser);
}
public void privateChatDisconnected(String endingUser, String userToBeInformed) {
model.sendPrivateChatEndRequest(endingUser,userToBeInformed);
}
public void privateChatStartet(String targetUser){
model.sendPrivateChatRequest(targetUser);
}
public void processStartRequestForPrivateChat(String username) {
Platform.runLater(() -> gui.homeGui.processStartRequest(username));
}
public void addPrivateMessage(String originUser, String message, boolean isServer) {
Platform.runLater(() -> gui.homeGui.addPrivateMessage(originUser, message, isServer));
}
public void changePrivateChatActiveStatus(String username) {
Platform.runLater(()->gui.homeGui.chatDisconnected(username));
}
public void chatClosed(String username){
Platform.runLater(()-> gui.homeGui.chatClosed(username));
}
}
|
package wyf.wpf;
import static wyf.wpf.ConstantUtil.SERVER_ADDRESS;
import static wyf.wpf.ConstantUtil.SERVER_PORT;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;
public class MyDiaryActivity extends Activity{
MyConnector mc = null;//
ArrayList<String []> diaryList = new ArrayList<String []>();
ListView lvDiary = null; //声明ListView对象
int positionToDelete = -1;
String uno = null; //记录用户ID
Handler myHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch(msg.what){
case 0:
lvDiary.setAdapter(ba);
break;
}
super.handleMessage(msg);
}
};
BaseAdapter ba = new BaseAdapter() {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout ll = new LinearLayout(MyDiaryActivity.this);
TextView tvTitle = new TextView(MyDiaryActivity.this);
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setGravity(Gravity.CENTER_VERTICAL); //设置子控件的对齐方式
LinearLayout llDiary = new LinearLayout(MyDiaryActivity.this);
llDiary.setOrientation(LinearLayout.VERTICAL);
tvTitle.setTextAppearance(MyDiaryActivity.this, R.style.title);
tvTitle.setGravity(Gravity.LEFT); //设置TextView的对齐方式
tvTitle.setText(diaryList.get(position)[1]);
TextView tvContent = new TextView(MyDiaryActivity.this);
tvContent.setTextAppearance(MyDiaryActivity.this, R.style.content);
tvContent.setGravity(Gravity.LEFT); //设置TextView的对齐方式
String content = diaryList.get(position)[2];
int i = (content.length()>8?8:content.length());
tvContent.setText(content.substring(0,i)+"..."); //设置显示的内容
llDiary.addView(tvTitle);
llDiary.addView(tvContent);
ll.addView(llDiary); //添加到总线性布局中
LinearLayout llButton = new LinearLayout(MyDiaryActivity.this);
llButton.setOrientation(LinearLayout.HORIZONTAL); //设置布局方式
llButton.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
llButton.setGravity(Gravity.RIGHT);
Button btnEditDiary = new Button(MyDiaryActivity.this); //创建编辑按钮
btnEditDiary.setTextAppearance(MyDiaryActivity.this, R.style.button);
btnEditDiary.setLayoutParams(new LinearLayout.LayoutParams(60, LayoutParams.WRAP_CONTENT));
btnEditDiary.setText(R.string.btnEdit);
btnEditDiary.setId(position); //设置Button的ID
btnEditDiary.setOnClickListener(listenerToEdit); //设置按钮的监听器
Button btnDeleteDiary = new Button(MyDiaryActivity.this); //创建删除按钮
btnDeleteDiary.setTextAppearance(MyDiaryActivity.this, R.style.button);
btnDeleteDiary.setLayoutParams(new LinearLayout.LayoutParams(60, LayoutParams.WRAP_CONTENT));
btnDeleteDiary.setText(R.string.btnDelete);
btnDeleteDiary.setId(position); //设置Button的ID
btnDeleteDiary.setOnClickListener(listenerToDelete); //设置按钮的监听器
llButton.addView(btnEditDiary);
llButton.addView(btnDeleteDiary);
ll.addView(llButton);
return ll;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public int getCount() {
return diaryList.size();
}
};
View.OnClickListener listenerToEdit = new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MyDiaryActivity.this,ModifyDiaryActivity.class);
int pos = v.getId();
String [] data = diaryList.get(pos);
intent.putExtra("diary_info", data);
intent.putExtra("uno", uno);
startActivity(intent);
}
};
View.OnClickListener listenerToDelete = new View.OnClickListener() {
@Override
public void onClick(View v) {
positionToDelete = v.getId(); //获得ID
new AlertDialog.Builder(MyDiaryActivity.this)
.setTitle("提示")
.setIcon(R.drawable.alert_icon)
.setMessage("确认删除该篇日志?")
.setPositiveButton(
"确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
deleteDiary();
}
})
.setNegativeButton(
"取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {}
}
).show();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
uno = intent.getStringExtra("uno");
setContentView(R.layout.diary); //设置当前屏幕
lvDiary = (ListView)findViewById(R.id.lvDiary);
getDiaryList();
}
public void deleteDiary(){
new Thread(){
public void run(){
Looper.prepare();
try{
if(mc == null){
mc = new MyConnector(SERVER_ADDRESS, SERVER_PORT);
}
String rid = diaryList.get(positionToDelete)[0];
String msg = "<#DELETE_DIARY#>"+rid;
mc.dout.writeUTF(msg);
String reply = mc.din.readUTF(); //读取返回信息
if(reply.equals("<#DELETE_DIARY_SUCCESS#>")){ //删除成功
Toast.makeText(MyDiaryActivity.this, "删除日志成功!", Toast.LENGTH_LONG).show();
getDiaryList();
Looper.loop();
}
else{ //删除失败
Toast.makeText(MyDiaryActivity.this, "删除失败,请重试!", Toast.LENGTH_LONG).show();
Looper.loop();
}
}catch(Exception e){
e.printStackTrace();
}
Looper.myLooper().quit();
}
}.start();
}
//方法:获取日志列表
public void getDiaryList(){
new Thread(){
public void run(){
try{
mc = new MyConnector(SERVER_ADDRESS, SERVER_PORT);
mc.dout.writeUTF("<#GET_DIARY#>"+uno+"|"+"1");
int size = mc.din.readInt(); //读取日志的长度
diaryList = null;
diaryList = new ArrayList<String []>(); //初始化diaryLsit
for(int i=0;i<size;i++){ //循环接受日志信息
String diaryInfo = mc.din.readUTF(); //读取日志信息
String [] sa = diaryInfo.split("\\|");
diaryList.add(sa); //将日志信息添加到列表中
}
myHandler.sendEmptyMessage(0);
}catch(Exception e){
e.printStackTrace();
}
}
}.start();
}
@Override
protected void onDestroy() {
if(mc != null){
mc.sayBye();
}
super.onDestroy();
}
}
|
package com.mygdx.game.components;
import com.scs.awt.RectF;
public class PositionComponent {
public RectF rect; // Note that this is NOT the screen co-ords!
public RectF prevPos;
public static PositionComponent ByBottomLeft(float x, float y, float w, float h) {
PositionComponent pos = new PositionComponent();
pos.rect = new RectF(x, y+h, x+(w), y);
return pos;
}
private PositionComponent() {
prevPos = new RectF();
}
}
|
/*
* 2012-3 Red Hat Inc. and/or its affiliates and other contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.overlord.rtgov.epn.validation;
import org.overlord.rtgov.epn.Network;
/**
* This interface is used to report validation issues
* for an Event Processor Network.
*
*/
public interface EPNValidationListener {
/**
* This method identifies an issue with a part of
* an Event Processor Network.
*
* @param epn The network
* @param target The object resulting in the error
* @param issue The description of the issue
*/
public void error(Network epn, Object target, String issue);
}
|
package problem_solve.dynamic_programming.baekjoon;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BaekJoon1463 {
static int[] min = new int[1000001];
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int X = Integer.parseInt(br.readLine());
// Top-Down 방식 풀이
System.out.println(topDown(X));
// Bottom-up 방식 풀이
System.out.println(bottomUp(X));
br.close();
}
private static int bottomUp(int x){
min[1] = 0;
for(int i=2; i <= x; i++){
min[i] = min[i-1] + 1;
if(i % 2 == 0 && min[i] > min[i/2] + 1){
min[i] = min[i/2] + 1;
}
if(i % 3 == 0 && min[i] > min[i/3] + 1){
min[i] = min[i/3] + 1;
}
}
return min[x];
}
private static int topDown(int x){
if(x == 1){
return 0;
} else if(min[x] > 0){
return min[x];
}
min[x] = topDown(x-1) + 1;
if(x % 3 == 0){
int temp = topDown(x / 3) + 1;
if(min[x] > temp) min[x] = temp;
}
if(x % 2 == 0){
int temp = topDown(x/2) + 1;
if(min[x] > temp) min[x] = temp;
}
return min[x];
}
}
|
package com.ebanking.master;
import java.net.URL;
import org.openqa.selenium.Platform;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import com.ebanking.master.pom.AdminHp;
import com.ebanking.master.pom.NewRole;
import com.ebanking.master.pom.Newbranch;
import com.ebanking.master.pom.RanfordHp;
public class GridSel {
DesiredCapabilities cap =null;
@Parameters("browser")
@Test
public void gd(String br) throws Throwable{
if(br.equalsIgnoreCase("firefox"))
{
cap=new DesiredCapabilities();
cap.setBrowserName("firefox");
cap.setPlatform(Platform.WINDOWS);
}else if(br.equalsIgnoreCase("chrome"))
{
cap=new DesiredCapabilities();
cap.setBrowserName("chrome");
cap.setPlatform(Platform.WINDOWS);
}
RemoteWebDriver driver= new RemoteWebDriver(new URL("http://192.168.43.214:4444/wd/hub"),cap);
driver.manage().window().maximize();
driver.get("http://183.82.100.55/ranford2");
RanfordHp Rhp=PageFactory.initElements(driver,RanfordHp.class);
Rhp.login();
AdminHp Ahp=PageFactory.initElements(driver, AdminHp.class);
Ahp.br();
Newbranch Nbr=PageFactory.initElements(driver, Newbranch.class);
Nbr.branchcre();
driver.switchTo().alert().accept();
Ahp.Hm();
Ahp.rol();
NewRole Nro=PageFactory.initElements(driver, NewRole.class);
Nro.Rolecre("clerk","vhkgv","E");
driver.switchTo().alert().accept();
}
}
|
package fr.laas.knxsimulator.view;
/**
*
* @author Guillaume Garzone
*
* Interface for the controler to print messages on the main view
*
*/
public interface PrintOnWindow {
public void printOutput(String message);
public void printIntput(String message);
}
|
package animatronics.client.gui;
import animatronics.api.energy.ITEHasEntropy;
import animatronics.client.gui.element.ElementEntropyStorage;
import net.minecraft.inventory.Container;
import net.minecraft.tileentity.TileEntity;
public class GuiEntropyCrusher extends GuiBase {
public GuiEntropyCrusher(Container container, TileEntity tile) {
super(container, tile);
elementList.add(new ElementEntropyStorage(7, 6, (ITEHasEntropy)tile));
}
}
|
package com.openkm.servlet.frontend;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.auxilii.msgparser.Message;
import com.auxilii.msgparser.MsgParser;
import com.google.gson.Gson;
import com.openkm.api.OKMAuth;
import com.openkm.api.OKMDocument;
import com.openkm.api.OKMFolder;
import com.openkm.api.OKMMail;
import com.openkm.api.OKMNotification;
import com.openkm.automation.AutomationException;
import com.openkm.bean.Document;
import com.openkm.bean.FileUploadResponse;
import com.openkm.bean.Folder;
import com.openkm.bean.Mail;
import com.openkm.core.AccessDeniedException;
import com.openkm.core.Config;
import com.openkm.core.ConversionException;
import com.openkm.core.DatabaseException;
import com.openkm.core.FileSizeExceededException;
import com.openkm.core.ItemExistsException;
import com.openkm.core.LockException;
import com.openkm.core.MimeTypeConfig;
import com.openkm.core.PathNotFoundException;
import com.openkm.core.Ref;
import com.openkm.core.RepositoryException;
import com.openkm.core.UnsupportedMimeTypeException;
import com.openkm.core.UserQuotaExceededException;
import com.openkm.core.VersionException;
import com.openkm.core.VirusDetectedException;
import com.openkm.extension.core.ExtensionException;
import com.openkm.frontend.client.constants.service.ErrorCode;
import com.openkm.frontend.client.constants.ui.UIFileUploadConstants;
import com.openkm.module.db.DbDocumentModule;
import com.openkm.module.jcr.JcrDocumentModule;
import com.openkm.spring.PrincipalUtils;
import com.openkm.util.DocConverter;
import com.openkm.util.FileUtils;
import com.openkm.util.FormatUtil;
import com.openkm.util.MailUtils;
import com.openkm.util.PathUtils;
import com.openkm.util.impexp.ImpExpStats;
import com.openkm.util.impexp.RepositoryImporter;
import com.openkm.util.impexp.TextInfoDecorator;
import de.schlichtherle.io.File;
import de.schlichtherle.io.FileOutputStream;
/**
* FileUploadServlet
*
* @author pavila
*/
public class FileUploadServlet extends OKMHttpServlet {
private static Logger log = LoggerFactory.getLogger(FileUploadServlet.class);
private static final long serialVersionUID = 1L;
public static final int INSERT = 0;
public static final int UPDATE = 1;
public static final String FILE_UPLOAD_STATUS = "file_upload_status";
@SuppressWarnings("unchecked")
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
log.debug("doPost({}, {})", request, response);
String fileName = null;
InputStream is = null;
String path = null;
int action = 0;
long size = 0;
boolean notify = false;
boolean importZip = false;
boolean autoCheckOut = false;
String users = null;
String mails = null;
String roles = null;
String message = null;
String comment = null;
String folder = null;
String rename = null;
PrintWriter out = null;
String uploadedUuid = null;
int increaseVersion = 0;
java.io.File tmp = null;
boolean redirect = false;
boolean convertToPdf = false;
String redirectURL = "";
updateSessionManager(request);
// JSON Stuff
Ref<FileUploadResponse> fuResponse = new Ref<FileUploadResponse>(new FileUploadResponse());
try {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType(MimeTypeConfig.MIME_TEXT);
out = response.getWriter();
log.debug("isMultipart: {}", isMultipart);
// Create a factory for disk-based file items
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
String contentLength = request.getHeader("Content-Length");
FileUploadListener listener = new FileUploadListener(Long.parseLong(contentLength));
// Saving listener to session
request.getSession().setAttribute(FILE_UPLOAD_STATUS, listener);
upload.setHeaderEncoding("UTF-8");
// upload servlet allows to set upload listener
upload.setProgressListener(listener);
List<FileItem> items = upload.parseRequest(request);
// Parse the request and get all parameters and the uploaded
// file
for (Iterator<FileItem> it = items.iterator(); it.hasNext();) {
FileItem item = it.next();
if (item.isFormField()) {
if (item.getFieldName().equals("path")) {
path = item.getString("UTF-8");
} else if (item.getFieldName().equals("action")) {
action = Integer.parseInt(item.getString("UTF-8"));
} else if (item.getFieldName().equals("users")) {
users = item.getString("UTF-8");
} else if (item.getFieldName().equals("mails")) {
mails = item.getString("UTF-8");
} else if (item.getFieldName().equals("roles")) {
roles = item.getString("UTF-8");
} else if (item.getFieldName().equals("notify")) {
notify = true;
} else if (item.getFieldName().equals("importZip")) {
importZip = true;
} else if (item.getFieldName().equals("autoCheckOut")) {
autoCheckOut = true;
} else if (item.getFieldName().equals("message")) {
message = item.getString("UTF-8");
} else if (item.getFieldName().equals("comment")) {
comment = item.getString("UTF-8");
} else if (item.getFieldName().equals("folder")) {
folder = item.getString("UTF-8");
} else if (item.getFieldName().equals("rename")) {
rename = item.getString("UTF-8");
} else if (item.getFieldName().equals("redirect")) {
redirect = true;
redirectURL = item.getString("UTF-8");
} else if (item.getFieldName().equals("convertToPdf")) {
convertToPdf = true;
} else if (item.getFieldName().equals("increaseVersion")) {
increaseVersion = Integer.parseInt(item.getString("UTF-8"));
}
} else {
fileName = item.getName();
is = item.getInputStream();
size = item.getSize();
}
}
// Save document with different name than uploaded
log.debug("Filename: '{}'", fileName);
if (rename != null && !rename.equals("")) {
log.debug("Rename: '{}'", rename);
if (FilenameUtils.indexOfExtension(rename) > -1) {
// The rename contains filename + extension
fileName = rename;
} else {
// The rename only contains filename, so get extension
// from uploaded file
String ext = FilenameUtils.getExtension(fileName);
if (ext.equals("")) {
fileName = rename;
} else {
fileName = rename + "." + ext;
}
}
log.debug("Filename: '{}'", fileName);
}
// Now, we have read all parameters and the uploaded file
if (action == UIFileUploadConstants.ACTION_INSERT) {
if (fileName != null && !fileName.equals("")) {
if (importZip && FilenameUtils.getExtension(fileName).equalsIgnoreCase("zip")) {
log.debug("Import ZIP file '{}' into '{}'", fileName, path);
String erroMsg = importZip(path, is);
if (erroMsg == null) {
sendResponse(out, action, fuResponse.get());
} else {
log.warn("erroMsg: {}", erroMsg);
fuResponse.get().setError(erroMsg);
sendResponse(out, action, fuResponse.get());
}
} else if (importZip && FilenameUtils.getExtension(fileName).equalsIgnoreCase("jar")) {
log.debug("Import JAR file '{}' into '{}'", fileName, path);
String erroMsg = importJar(path, is);
if (erroMsg == null) {
sendResponse(out, action, fuResponse.get());
} else {
fuResponse.get().setError(erroMsg);
sendResponse(out, action, fuResponse.get());
}
} else if (FilenameUtils.getExtension(fileName).equalsIgnoreCase("eml")) {
log.debug("import EML file '{}' into '{}'", fileName, path);
Mail mail = importEml(path, is);
fuResponse.get().setPath(mail.getPath());
sendResponse(out, action, fuResponse.get());
} else if (FilenameUtils.getExtension(fileName).equalsIgnoreCase("msg")) {
log.debug("import MSG file '{}' into '{}'", fileName, path);
Mail mail = importMsg(path, is);
fuResponse.get().setPath(mail.getPath());
sendResponse(out, action, fuResponse.get());
} else {
fileName = FilenameUtils.getName(fileName);
log.debug("Upload file '{}' into '{} ({})'", new Object[] { fileName, path, FormatUtil.formatSize(size) });
String mimeType = MimeTypeConfig.mimeTypes.getContentType(fileName.toLowerCase());
Document doc = new Document();
doc.setPath(path + "/" + fileName);
if (convertToPdf && !mimeType.equals(MimeTypeConfig.MIME_PDF)) {
DocConverter converter = DocConverter.getInstance();
if (converter.convertibleToPdf(mimeType)) {
// Changing path name
if (fileName.contains(".")) {
fileName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + "pdf";
} else {
fileName += ".pdf";
}
doc.setPath(path + "/" + fileName);
tmp = File.createTempFile("okm", ".tmp");
java.io.File tmpPdf = File.createTempFile("okm", ".pdf");
FileOutputStream fos = new FileOutputStream(tmp);
IOUtils.copy(is, fos);
converter.doc2pdf(tmp, mimeType, tmpPdf);
is = new FileInputStream(tmpPdf);
doc = OKMDocument.getInstance().create(null, doc, is);
fuResponse.get().setPath(doc.getPath());
uploadedUuid = doc.getUuid();
tmp.delete();
tmpPdf.delete();
tmp = null;
} else {
throw new ConversionException("Not convertible to pdf");
}
} else {
log.debug("Wizard: {}", fuResponse);
if (Config.REPOSITORY_NATIVE) {
doc = new DbDocumentModule().create(null, doc, is, size, null, fuResponse);
fuResponse.get().setPath(doc.getPath());
uploadedUuid = doc.getUuid();
} else {
doc = new JcrDocumentModule().create(null, doc, is);
fuResponse.get().setPath(doc.getPath());
uploadedUuid = doc.getUuid();
}
log.debug("Wizard: {}", fuResponse);
}
// Return the path of the inserted document in
// response
sendResponse(out, action, fuResponse.get());
}
}
} else if (action == UIFileUploadConstants.ACTION_UPDATE) {
log.debug("File updated: {}", path);
// http://en.wikipedia.org/wiki/Truth_table#Applications => ¬p ∨ q
if (!Config.SYSTEM_DOCUMENT_NAME_MISMATCH_CHECK || PathUtils.getName(path).equals(fileName)) {
Document doc = OKMDocument.getInstance().getProperties(null, path);
if (autoCheckOut) {
// This is set from the Uploader applet
OKMDocument.getInstance().checkout(null, path);
}
if (Config.REPOSITORY_NATIVE) {
new DbDocumentModule().checkin(null, path, is, size, comment, null, increaseVersion);
fuResponse.get().setPath(path);
uploadedUuid = doc.getUuid();
} else {
new JcrDocumentModule().checkin(null, path, is, comment);
fuResponse.get().setPath(path);
uploadedUuid = doc.getUuid();
}
// Return the path of the inserted document in response
sendResponse(out, action, fuResponse.get());
} else {
fuResponse.get().setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_DocumentNameMismatch));
sendResponse(out, action, fuResponse.get());
}
} else if (action == UIFileUploadConstants.ACTION_FOLDER) {
log.debug("Folder create: {}", path);
Folder fld = new Folder();
fld.setPath(path + "/" + folder);
fld = OKMFolder.getInstance().create(null, fld);
fuResponse.get().setPath(fld.getPath());
sendResponse(out, action, fuResponse.get());
}
// Mark uploading operation has finished
listener.setUploadFinish(true);
// If the document have been added to the repository, perform user notification if has no error
if ((action == UIFileUploadConstants.ACTION_INSERT || action == UIFileUploadConstants.ACTION_UPDATE) && notify
&& fuResponse.get().getError().equals("")) {
List<String> userNames = new ArrayList<String>(Arrays.asList(users.isEmpty() ? new String[0] : users.split(",")));
List<String> roleNames = new ArrayList<String>(Arrays.asList(roles.isEmpty() ? new String[0] : roles.split(",")));
for (String role : roleNames) {
List<String> usersInRole = OKMAuth.getInstance().getUsersByRole(null, role);
for (String user : usersInRole) {
if (!userNames.contains(user)) {
userNames.add(user);
}
}
}
String notifyPath = URLDecoder.decode(fuResponse.get().getPath(), "UTF-8");
List<String> mailList = MailUtils.parseMailList(mails);
OKMNotification.getInstance().notify(null, notifyPath, userNames, mailList, message, false);
}
// After uploading redirects to some URL
if (redirect) {
ServletContext sc = getServletContext();
request.setAttribute("docPath", fuResponse.get().getPath());
request.setAttribute("uuid", uploadedUuid);
sc.setAttribute("docPath", fuResponse.get().getPath());
sc.setAttribute("uuid", uploadedUuid);
sc.getRequestDispatcher(redirectURL).forward(request, response);
}
}
} catch (AccessDeniedException e) {
fuResponse.get().setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_AccessDenied));
sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
} catch (PathNotFoundException e) {
fuResponse.get().setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_PathNotFound));
sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
} catch (ItemExistsException e) {
fuResponse.get().setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_ItemExists));
sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
} catch (UnsupportedMimeTypeException e) {
fuResponse.get().setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_UnsupportedMimeType));
sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
} catch (FileSizeExceededException e) {
fuResponse.get().setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_FileSizeExceeded));
sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
} catch (LockException e) {
fuResponse.get().setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_Lock));
sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
} catch (VirusDetectedException e) {
fuResponse.get().setError(VirusDetectedException.class.getSimpleName() + " : " + e.getMessage());
sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
} catch (VersionException e) {
log.error(e.getMessage(), e);
fuResponse.get().setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_Version));
sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
} catch (RepositoryException e) {
log.error(e.getMessage(), e);
fuResponse.get().setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_Repository));
sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
} catch (DatabaseException e) {
log.error(e.getMessage(), e);
fuResponse.get().setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_Database));
sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
} catch (ExtensionException e) {
log.error(e.getMessage(), e);
fuResponse.get().setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_Extension));
sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
} catch (IOException e) {
log.error(e.getMessage(), e);
fuResponse.get().setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_IO));
sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
} catch (ConversionException e) {
fuResponse.get().setError(ErrorCode.get(ErrorCode.ORIGIN_OKMUploadService, ErrorCode.CAUSE_Conversion));
sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
} catch (Exception e) {
log.error(e.getMessage(), e);
fuResponse.get().setError(e.toString());
sendErrorResponse(out, action, fuResponse.get(), request, response, redirect, redirectURL);
} finally {
if (tmp != null) {
tmp.delete();
}
IOUtils.closeQuietly(is);
out.flush();
IOUtils.closeQuietly(out);
System.gc();
}
}
/**
* sendErrorResponse
*/
private void sendErrorResponse(PrintWriter out, int action, FileUploadResponse fur, HttpServletRequest request,
HttpServletResponse response, boolean redirect, String redirectURL) {
if (redirect) {
ServletContext sc = getServletContext();
try {
sc.getRequestDispatcher(redirectURL).forward(request, response);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
sendResponse(out, action, fur);
}
}
/**
* Send response back to browser.
*/
private void sendResponse(PrintWriter out, int action, FileUploadResponse fur) {
Gson gson = new Gson();
String json = gson.toJson(fur);
out.print(json);
log.debug("Action: {}, JSON Response: {}", action, json);
}
/**
* Import zipped documents
*
* @param path Where import into the repository.
* @param is The zip file to import.
*/
private synchronized String importZip(String path, InputStream is) throws PathNotFoundException, ItemExistsException,
AccessDeniedException, RepositoryException, IOException, DatabaseException, ExtensionException, AutomationException {
log.debug("importZip({}, {})", path, is);
java.io.File tmpIn = null;
java.io.File tmpOut = null;
String errorMsg = null;
try {
// Create temporal
tmpIn = File.createTempFile("okm", ".zip");
tmpOut = FileUtils.createTempDir();
FileOutputStream fos = new FileOutputStream(tmpIn);
IOUtils.copy(is, fos);
fos.close();
// Unzip files
File fileTmpIn = new File(tmpIn);
fileTmpIn.archiveCopyAllTo(tmpOut);
File.umount();
// Import files
StringWriter out = new StringWriter();
ImpExpStats stats = RepositoryImporter.importDocuments(null, tmpOut, path, false, false, false, out, new TextInfoDecorator(
tmpOut));
if (!stats.isOk()) {
errorMsg = out.toString();
}
out.close();
} catch (IOException e) {
log.error("Error importing zip", e);
throw e;
} finally {
IOUtils.closeQuietly(is);
if (tmpIn != null) {
org.apache.commons.io.FileUtils.deleteQuietly(tmpIn);
}
if (tmpOut != null) {
org.apache.commons.io.FileUtils.deleteQuietly(tmpOut);
}
}
log.debug("importZip: {}", errorMsg);
return errorMsg;
}
/**
* Import jarred documents
*
* @param path Where import into the repository.
* @param is The jar file to import.
*/
private synchronized String importJar(String path, InputStream is) throws PathNotFoundException, ItemExistsException,
AccessDeniedException, RepositoryException, IOException, DatabaseException, ExtensionException, AutomationException {
log.debug("importJar({}, {})", path, is);
java.io.File tmpIn = null;
java.io.File tmpOut = null;
String errorMsg = null;
try {
// Create temporal
tmpIn = File.createTempFile("okm", ".jar");
tmpOut = FileUtils.createTempDir();
FileOutputStream fos = new FileOutputStream(tmpIn);
IOUtils.copy(is, fos);
fos.close();
// Unzip files
File fileTmpIn = new File(tmpIn);
fileTmpIn.archiveCopyAllTo(tmpOut);
// Import files
StringWriter out = new StringWriter();
ImpExpStats stats = RepositoryImporter.importDocuments(null, tmpOut, path, false, false, false, out, new TextInfoDecorator(
tmpOut));
if (!stats.isOk()) {
errorMsg = out.toString();
}
out.close();
} catch (IOException e) {
log.error("Error importing jar", e);
throw e;
} finally {
IOUtils.closeQuietly(is);
if (tmpIn != null) {
File.umount();
org.apache.commons.io.FileUtils.deleteQuietly(tmpIn);
}
if (tmpOut != null) {
org.apache.commons.io.FileUtils.deleteQuietly(tmpOut);
}
}
log.debug("importJar: {}", errorMsg);
return errorMsg;
}
/**
* Import EML file as MailNode.
*/
private Mail importEml(String path, InputStream is) throws MessagingException, PathNotFoundException, ItemExistsException,
VirusDetectedException, AccessDeniedException, RepositoryException, DatabaseException, UserQuotaExceededException,
UnsupportedMimeTypeException, FileSizeExceededException, ExtensionException, AutomationException, IOException {
log.debug("importEml({}, {})", path, is);
Properties props = System.getProperties();
props.put("mail.host", "smtp.dummydomain.com");
props.put("mail.transport.protocol", "smtp");
Mail newMail = null;
try {
// Convert file
Session mailSession = Session.getDefaultInstance(props, null);
MimeMessage msg = new MimeMessage(mailSession, is);
Mail mail = MailUtils.messageToMail(msg);
// Create phantom path. In this case we don't have the IMAP message
// ID, son create a random one.
mail.setPath(path + "/" + UUID.randomUUID().toString() + "-" + PathUtils.escape(mail.getSubject()));
// Import files
newMail = OKMMail.getInstance().create(null, mail);
MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser());
} catch (IOException e) {
log.error("Error importing eml", e);
throw e;
} finally {
IOUtils.closeQuietly(is);
}
log.debug("importEml: {}", newMail);
return newMail;
}
/**
* Import MSG file as MailNode.
*/
private Mail importMsg(String path, InputStream is) throws MessagingException, PathNotFoundException, ItemExistsException,
VirusDetectedException, AccessDeniedException, RepositoryException, DatabaseException, UserQuotaExceededException,
UnsupportedMimeTypeException, FileSizeExceededException, ExtensionException, AutomationException, IOException {
log.debug("importMsg({}, {})", path, is);
Mail newMail = null;
try {
// Convert file
MsgParser msgp = new MsgParser();
Message msg = msgp.parseMsg(is);
Mail mail = MailUtils.messageToMail(msg);
// Create phantom path. In this case we don't have the IMAP message ID, son create a random one.
mail.setPath(path + "/" + UUID.randomUUID().toString() + "-" + PathUtils.escape(mail.getSubject()));
// Import files
newMail = OKMMail.getInstance().create(null, mail);
MailUtils.addAttachments(null, mail, msg, PrincipalUtils.getUser());
} catch (IOException e) {
log.error("Error importing msg", e);
throw e;
} finally {
IOUtils.closeQuietly(is);
}
log.debug("importMsg: {}", newMail);
return newMail;
}
}
|
package com.scf.skyware.mobile.domain;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
public class NoticeM
{
private int noticeNo;
private int rownum;
private String noticeTitle;
private String noticeBody;
private String noticeWriterId;
private String noticeDate;
private String noticeModDate;
private String noticeIsShow;
private String noticeWriter;
// 페이징
private int pageSize;
private int totalPage;
private int curPage;
// 검색조건
private String schState;
private String schType;
private String schText;
public int getNoticeNo()
{
return noticeNo;
}
public void setNoticeNo(int noticeNo)
{
this.noticeNo = noticeNo;
}
public int getRownum()
{
return rownum;
}
public void setRownum(int rownum)
{
this.rownum = rownum;
}
public String getNoticeTitle()
{
return noticeTitle;
}
public void setNoticeTitle(String noticeTitle)
{
this.noticeTitle = noticeTitle;
}
public String getNoticeBody()
{
return noticeBody;
}
public void setNoticeBody(String noticeBody)
{
this.noticeBody = noticeBody;
}
public String getNoticeWriterId()
{
return noticeWriterId;
}
public void setNoticeWriterId(String noticeWriterId)
{
this.noticeWriterId = noticeWriterId;
}
public String getNoticeDate()
{
return noticeDate;
}
public void setNoticeDate(String noticeDate)
{
if (noticeDate != null)
{
this.noticeDate = noticeDate.substring(0, 10);
}
else
{
this.noticeDate = noticeDate;
}
}
public String getNoticeModDate()
{
return noticeModDate;
}
public void setNoticeModDate(String noticeModDate)
{
if (noticeModDate != null)
{
this.noticeModDate = noticeModDate.substring(0, 10);
}
else
{
this.noticeModDate = noticeModDate;
}
}
public String getNoticeIsShow()
{
return noticeIsShow;
}
public void setNoticeIsShow(String noticeIsShow)
{
this.noticeIsShow = noticeIsShow;
}
public int getPageSize()
{
return pageSize;
}
public void setPageSize(int pageSize)
{
this.pageSize = pageSize;
}
public int getTotalPage()
{
return totalPage;
}
public void setTotalPage(int totalPage)
{
this.totalPage = totalPage;
}
public int getCurPage()
{
return curPage;
}
public void setCurPage(int curPage)
{
this.curPage = curPage;
}
public String getSchState()
{
return schState;
}
public void setSchState(String schState)
{
this.schState = schState;
}
public String getSchType()
{
return schType;
}
public void setSchType(String schType)
{
this.schType = schType;
}
public String getSchText()
{
return schText;
}
public void setSchText(String schText)
{
this.schText = schText;
}
public String getNoticeWriter()
{
return noticeWriter;
}
public void setNoticeWriter(String noticeWriter)
{
this.noticeWriter = noticeWriter;
}
@Override
public String toString()
{
return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
}
}
|
package br.ufrgs.rmpestano.intrabundle.model.enums;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Created by rmpestano on 1/26/14.
*/
public enum LocaleEnum {
PT("pt"), EN("en");
private final String value;
LocaleEnum(String value) {
this.value = value;
}
public static String getByLocale(Locale locale) {
for (String s : getAll()) {
if (s.equals(locale.getDisplayLanguage())) {
return s;
}
}
//locale not supported, return 'EN'
return EN.value;
}
public static List<String> getAll() {
List<String> retorno = new ArrayList<String>();
for (LocaleEnum l : LocaleEnum.values()) {
retorno.add(l.value);
}
return retorno;
}
@Override
public String toString() {
return value;
}
}
|
package com.itbank.food;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@Component
public class StoryDAO {
@Autowired
JdbcTemplate jdbc;
public List<StoryDTO> selectAll() {
String sql = "select * from Story";
return jdbc.query(sql, new StoryRowMapper());
}
public void insert(StoryDTO story) {
String sql = "insert into story values(null,?,?,?,sysdate(),'0',?,?)";
jdbc.update(sql, story.getStrWriter(), story.getStrTitle(), story.getStrContent(), story.getStrImg(),
story.getStrMaterial());
}
public StoryDTO select(int strNo) {
String sql = "select * from story where strNo = ?";
Object[] arg = { strNo };
return jdbc.queryForObject(sql, arg, new StoryRowMapper());
}
public Integer nextStrNo() {
String sql = "select auto_increment from information_schema.tables where table_name = 'story' AND table_schema = DATABASE()";
return jdbc.queryForObject(sql, Integer.class);
}
}
|
package com.codegym.province.repository;
import com.codegym.province.model.Customer;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface CustomerRepository extends PagingAndSortingRepository {
}
|
package info.kpumuk.erka;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
public class FlushMemcachedTask extends Task {
private static final List<String> LOCALHOST;
static {
ArrayList<String> l = new ArrayList<String>(1);
l.add("localhost");
LOCALHOST = Collections.unmodifiableList(l);
}
private List<String> servers = new ArrayList<String>(1);
private MemcachedClient client;
public FlushMemcachedTask() {
super();
client = new MemcachedClientImpl();
}
public void setClient(MemcachedClient client) {
this.client = client;
}
public List<String> getServers() {
if (servers.isEmpty()) {
return LOCALHOST;
}
return Collections.unmodifiableList(servers);
}
public void setServers(String csvServers) {
if (csvServers != null) {
String[] hosts = csvServers.split(",\\s*");
for (String host : hosts) {
if (host.length() > 0) {
servers.add(host);
}
}
}
}
@Override
public void execute() throws BuildException {
List<String> hosts = getServers();
for (String host : hosts) {
client.setHost(host);
if (client.flush()) {
System.out.println(host + " is flushed.");
}
}
}
}
|
package com.kobotan.android.Vshkole.activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import butterknife.ButterKnife;
import butterknife.InjectView;
import com.kobotan.android.Vshkole.R;
import com.kobotan.android.Vshkole.adapters.TabSwipeSubjectAdapter;
import com.kobotan.android.Vshkole.billingClasses.AuthorizationInfo;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;
import com.kobotan.android.Vshkole.utils.ClassСrutch;
import com.viewpagerindicator.TabPageIndicator;
public class SubjectsActivity extends FragmentActivity{
@InjectView(R.id.vpPager) ViewPager vpPager;
@InjectView(R.id.titles) TabPageIndicator titleIndicator;
GoogleAnalytics analytics;
Tracker tracker;
int numberClass;
FragmentPagerAdapter adapterViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.subjects_page);
initializeAds();
ButterKnife.inject(this);
analytics = GoogleAnalytics.getInstance(this);
tracker = analytics.newTracker(R.xml.global_tracker);
getActionBar().setDisplayHomeAsUpEnabled(true);
numberClass = getIntent().getIntExtra(ClassesActivity.CLASS_ID_KEY, 0);
adapterViewPager = new TabSwipeSubjectAdapter(getSupportFragmentManager(), numberClass);
vpPager.setAdapter(adapterViewPager);
titleIndicator.setViewPager(vpPager);
titleIndicator.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener());
}
@Override
protected void onStart() {
super.onStart();
analytics.reportActivityStart(this);
}
@Override
protected void onStop() {
super.onStop();
analytics.reportActivityStop(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.common_menu, menu);
MenuItem classTitle = menu.findItem(R.id.number_of_class);
classTitle.setTitle(ClassСrutch.getRealClassName(numberClass) + " класс");
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.backpack:
Intent intent = new Intent(this, BackpackActivity.class);
startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
private void initializeAds() {
AdView mAdView = (AdView) findViewById(R.id.adView);
if (!AuthorizationInfo.isBought(getApplicationContext())) {
AdRequest adRequest = new AdRequest.Builder()
.build();
mAdView.loadAd(adRequest);
}else{
mAdView.setVisibility(View.GONE);
}
}
}
|
package com.laoji.cloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* SSO上传服务 云上传
* @author: laoji
* @date:2020/4/8 18:04
*/
@SpringBootApplication
@EnableDiscoveryClient
public class CloudUploadApplication {
public static void main(String[] args) {
SpringApplication.run(CloudUploadApplication.class,args);
}
}
|
/*
* 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 RMI.Client;
import RMI.Interface.OK;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
/**
*
* @author Administrator
*/
public class OKImp extends UnicastRemoteObject implements OK {
public OKImp() throws RemoteException {
super();
}
@Override
public String sayOK() throws Exception {
return "OK!";
}
}
|
package com.tencent.tencentmap.mapsdk.a;
public interface mk {
bb a(int i, int i2);
boolean a(int i);
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
import java.math.BigDecimal;
/**
* BvPrepareRoutineId generated by hbm2java
*/
public class BvPrepareRoutineId implements java.io.Serializable {
private String routing;
private String routingName;
private String routingType;
private BigDecimal opuid;
private BigDecimal operationId;
private String requirePartNumber;
private Byte requireNum;
private String partName;
private String drawingid;
private String versionid;
private String partNumberSort;
private String partNumberSortIddesc;
private String isNeedJudge;
private Long judgeAdvanceTime;
private String isNeedData;
private Long dataAdvanceTime;
private String isNeedSort;
private Long sortAdvanceTime;
public BvPrepareRoutineId() {
}
public BvPrepareRoutineId(String routing, BigDecimal opuid, BigDecimal operationId, String requirePartNumber,
String partNumberSortIddesc) {
this.routing = routing;
this.opuid = opuid;
this.operationId = operationId;
this.requirePartNumber = requirePartNumber;
this.partNumberSortIddesc = partNumberSortIddesc;
}
public BvPrepareRoutineId(String routing, String routingName, String routingType, BigDecimal opuid,
BigDecimal operationId, String requirePartNumber, Byte requireNum, String partName, String drawingid,
String versionid, String partNumberSort, String partNumberSortIddesc, String isNeedJudge,
Long judgeAdvanceTime, String isNeedData, Long dataAdvanceTime, String isNeedSort, Long sortAdvanceTime) {
this.routing = routing;
this.routingName = routingName;
this.routingType = routingType;
this.opuid = opuid;
this.operationId = operationId;
this.requirePartNumber = requirePartNumber;
this.requireNum = requireNum;
this.partName = partName;
this.drawingid = drawingid;
this.versionid = versionid;
this.partNumberSort = partNumberSort;
this.partNumberSortIddesc = partNumberSortIddesc;
this.isNeedJudge = isNeedJudge;
this.judgeAdvanceTime = judgeAdvanceTime;
this.isNeedData = isNeedData;
this.dataAdvanceTime = dataAdvanceTime;
this.isNeedSort = isNeedSort;
this.sortAdvanceTime = sortAdvanceTime;
}
public String getRouting() {
return this.routing;
}
public void setRouting(String routing) {
this.routing = routing;
}
public String getRoutingName() {
return this.routingName;
}
public void setRoutingName(String routingName) {
this.routingName = routingName;
}
public String getRoutingType() {
return this.routingType;
}
public void setRoutingType(String routingType) {
this.routingType = routingType;
}
public BigDecimal getOpuid() {
return this.opuid;
}
public void setOpuid(BigDecimal opuid) {
this.opuid = opuid;
}
public BigDecimal getOperationId() {
return this.operationId;
}
public void setOperationId(BigDecimal operationId) {
this.operationId = operationId;
}
public String getRequirePartNumber() {
return this.requirePartNumber;
}
public void setRequirePartNumber(String requirePartNumber) {
this.requirePartNumber = requirePartNumber;
}
public Byte getRequireNum() {
return this.requireNum;
}
public void setRequireNum(Byte requireNum) {
this.requireNum = requireNum;
}
public String getPartName() {
return this.partName;
}
public void setPartName(String partName) {
this.partName = partName;
}
public String getDrawingid() {
return this.drawingid;
}
public void setDrawingid(String drawingid) {
this.drawingid = drawingid;
}
public String getVersionid() {
return this.versionid;
}
public void setVersionid(String versionid) {
this.versionid = versionid;
}
public String getPartNumberSort() {
return this.partNumberSort;
}
public void setPartNumberSort(String partNumberSort) {
this.partNumberSort = partNumberSort;
}
public String getPartNumberSortIddesc() {
return this.partNumberSortIddesc;
}
public void setPartNumberSortIddesc(String partNumberSortIddesc) {
this.partNumberSortIddesc = partNumberSortIddesc;
}
public String getIsNeedJudge() {
return this.isNeedJudge;
}
public void setIsNeedJudge(String isNeedJudge) {
this.isNeedJudge = isNeedJudge;
}
public Long getJudgeAdvanceTime() {
return this.judgeAdvanceTime;
}
public void setJudgeAdvanceTime(Long judgeAdvanceTime) {
this.judgeAdvanceTime = judgeAdvanceTime;
}
public String getIsNeedData() {
return this.isNeedData;
}
public void setIsNeedData(String isNeedData) {
this.isNeedData = isNeedData;
}
public Long getDataAdvanceTime() {
return this.dataAdvanceTime;
}
public void setDataAdvanceTime(Long dataAdvanceTime) {
this.dataAdvanceTime = dataAdvanceTime;
}
public String getIsNeedSort() {
return this.isNeedSort;
}
public void setIsNeedSort(String isNeedSort) {
this.isNeedSort = isNeedSort;
}
public Long getSortAdvanceTime() {
return this.sortAdvanceTime;
}
public void setSortAdvanceTime(Long sortAdvanceTime) {
this.sortAdvanceTime = sortAdvanceTime;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof BvPrepareRoutineId))
return false;
BvPrepareRoutineId castOther = (BvPrepareRoutineId) other;
return ((this.getRouting() == castOther.getRouting()) || (this.getRouting() != null
&& castOther.getRouting() != null && this.getRouting().equals(castOther.getRouting())))
&& ((this.getRoutingName() == castOther.getRoutingName())
|| (this.getRoutingName() != null && castOther.getRoutingName() != null
&& this.getRoutingName().equals(castOther.getRoutingName())))
&& ((this.getRoutingType() == castOther.getRoutingType())
|| (this.getRoutingType() != null && castOther.getRoutingType() != null
&& this.getRoutingType().equals(castOther.getRoutingType())))
&& ((this.getOpuid() == castOther.getOpuid()) || (this.getOpuid() != null
&& castOther.getOpuid() != null && this.getOpuid().equals(castOther.getOpuid())))
&& ((this.getOperationId() == castOther.getOperationId())
|| (this.getOperationId() != null && castOther.getOperationId() != null
&& this.getOperationId().equals(castOther.getOperationId())))
&& ((this.getRequirePartNumber() == castOther.getRequirePartNumber())
|| (this.getRequirePartNumber() != null && castOther.getRequirePartNumber() != null
&& this.getRequirePartNumber().equals(castOther.getRequirePartNumber())))
&& ((this.getRequireNum() == castOther.getRequireNum()) || (this.getRequireNum() != null
&& castOther.getRequireNum() != null && this.getRequireNum().equals(castOther.getRequireNum())))
&& ((this.getPartName() == castOther.getPartName()) || (this.getPartName() != null
&& castOther.getPartName() != null && this.getPartName().equals(castOther.getPartName())))
&& ((this.getDrawingid() == castOther.getDrawingid()) || (this.getDrawingid() != null
&& castOther.getDrawingid() != null && this.getDrawingid().equals(castOther.getDrawingid())))
&& ((this.getVersionid() == castOther.getVersionid()) || (this.getVersionid() != null
&& castOther.getVersionid() != null && this.getVersionid().equals(castOther.getVersionid())))
&& ((this.getPartNumberSort() == castOther.getPartNumberSort())
|| (this.getPartNumberSort() != null && castOther.getPartNumberSort() != null
&& this.getPartNumberSort().equals(castOther.getPartNumberSort())))
&& ((this.getPartNumberSortIddesc() == castOther.getPartNumberSortIddesc())
|| (this.getPartNumberSortIddesc() != null && castOther.getPartNumberSortIddesc() != null
&& this.getPartNumberSortIddesc().equals(castOther.getPartNumberSortIddesc())))
&& ((this.getIsNeedJudge() == castOther.getIsNeedJudge())
|| (this.getIsNeedJudge() != null && castOther.getIsNeedJudge() != null
&& this.getIsNeedJudge().equals(castOther.getIsNeedJudge())))
&& ((this.getJudgeAdvanceTime() == castOther.getJudgeAdvanceTime())
|| (this.getJudgeAdvanceTime() != null && castOther.getJudgeAdvanceTime() != null
&& this.getJudgeAdvanceTime().equals(castOther.getJudgeAdvanceTime())))
&& ((this.getIsNeedData() == castOther.getIsNeedData()) || (this.getIsNeedData() != null
&& castOther.getIsNeedData() != null && this.getIsNeedData().equals(castOther.getIsNeedData())))
&& ((this.getDataAdvanceTime() == castOther.getDataAdvanceTime())
|| (this.getDataAdvanceTime() != null && castOther.getDataAdvanceTime() != null
&& this.getDataAdvanceTime().equals(castOther.getDataAdvanceTime())))
&& ((this.getIsNeedSort() == castOther.getIsNeedSort()) || (this.getIsNeedSort() != null
&& castOther.getIsNeedSort() != null && this.getIsNeedSort().equals(castOther.getIsNeedSort())))
&& ((this.getSortAdvanceTime() == castOther.getSortAdvanceTime())
|| (this.getSortAdvanceTime() != null && castOther.getSortAdvanceTime() != null
&& this.getSortAdvanceTime().equals(castOther.getSortAdvanceTime())));
}
public int hashCode() {
int result = 17;
result = 37 * result + (getRouting() == null ? 0 : this.getRouting().hashCode());
result = 37 * result + (getRoutingName() == null ? 0 : this.getRoutingName().hashCode());
result = 37 * result + (getRoutingType() == null ? 0 : this.getRoutingType().hashCode());
result = 37 * result + (getOpuid() == null ? 0 : this.getOpuid().hashCode());
result = 37 * result + (getOperationId() == null ? 0 : this.getOperationId().hashCode());
result = 37 * result + (getRequirePartNumber() == null ? 0 : this.getRequirePartNumber().hashCode());
result = 37 * result + (getRequireNum() == null ? 0 : this.getRequireNum().hashCode());
result = 37 * result + (getPartName() == null ? 0 : this.getPartName().hashCode());
result = 37 * result + (getDrawingid() == null ? 0 : this.getDrawingid().hashCode());
result = 37 * result + (getVersionid() == null ? 0 : this.getVersionid().hashCode());
result = 37 * result + (getPartNumberSort() == null ? 0 : this.getPartNumberSort().hashCode());
result = 37 * result + (getPartNumberSortIddesc() == null ? 0 : this.getPartNumberSortIddesc().hashCode());
result = 37 * result + (getIsNeedJudge() == null ? 0 : this.getIsNeedJudge().hashCode());
result = 37 * result + (getJudgeAdvanceTime() == null ? 0 : this.getJudgeAdvanceTime().hashCode());
result = 37 * result + (getIsNeedData() == null ? 0 : this.getIsNeedData().hashCode());
result = 37 * result + (getDataAdvanceTime() == null ? 0 : this.getDataAdvanceTime().hashCode());
result = 37 * result + (getIsNeedSort() == null ? 0 : this.getIsNeedSort().hashCode());
result = 37 * result + (getSortAdvanceTime() == null ? 0 : this.getSortAdvanceTime().hashCode());
return result;
}
}
|
package ch.fhnw.edu.cpib.errors;
public class AlreadyGloballyDeclaredError extends Exception {
private static final long serialVersionUID = 1L;
public AlreadyGloballyDeclaredError() {
}
public AlreadyGloballyDeclaredError(String errorMessage) {
super(setupMessage(errorMessage));
}
public AlreadyGloballyDeclaredError(String message, Throwable cause) {
super(setupMessage(message), cause);
}
public AlreadyGloballyDeclaredError(Throwable cause) {
super(cause);
}
private static String setupMessage(String string) {
return "Name already globally declared [" + string + "]";
}
}
|
package com.app.sapient.grade.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.app.sapient.grade.dto.GradeItemDto;
import com.app.sapient.grade.exception.StudentNotFountException;
import com.app.sapient.grade.exception.TeacherNotFoundException;
import com.app.sapient.grade.service.GradeService;
@RestController
public class GradeController {
private static final Logger LOGGER = LoggerFactory.getLogger(GradeController.class);
private GradeService gradeService;
@Autowired
public GradeController(GradeService gradeService) {
this.gradeService = gradeService;
}
@PostMapping(value = "/grades")
public ResponseEntity<GradeItemDto> addGradeItem(@RequestBody GradeItemDto gradeItemDto) {
if(null == gradeItemDto || null == gradeItemDto.getStudentId() || null == gradeItemDto.getTeacherId()) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
try {
GradeItemDto createdItem = gradeService.addNewGradeItem(gradeItemDto);
return new ResponseEntity<>(createdItem, HttpStatus.OK);
} catch(TeacherNotFoundException | StudentNotFountException e) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
} catch(Exception e) {
LOGGER.error("Exception while adding grade item: {}", e.getMessage());
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
|
package com.app.innerclasses;
public class Test1 {
int x =10;
static int y=20;
public void methodOne()
{
class Inner
{
public void methodTwo()
{
System.out.println(x);
System.out.println(y);
}
}
Inner i = new Inner();
i.methodTwo();
}
public static void main(String[] args) {
new Test1().methodOne();
}
}
|
package com.javarush.task.task31.task3102;
import java.io.*;
import java.util.*;
/*
Находим все файлы
*/
public class Solution {
public static List<String> getFileTree(String root) throws IOException {
File pass = new File(root);
List<String> arr = new ArrayList();
Queue<File> queue = new PriorityQueue();
Collections.addAll(queue, pass.listFiles());
while (!queue.isEmpty()) {
File file = queue.remove();
if (file.isDirectory()) {
Collections.addAll(queue, file.listFiles());
} else {
arr.add(file.getAbsolutePath());
}
}
return arr;
}
public static void main(String[] args) throws IOException{
List<String> s = getFileTree("/Users/vrudnov/MyDoc/tmp/");
for (String s1:s) {
System.out.println(s1);
}
}
}
|
package com.example.liuyuhua.cainiaonews.utils;
/**
* “发现” 数据接口地址
* Created by liuyuhua on 2017/4/27.
*/
public class FindDataUtils {
public static String sHeadAdUrl = "http://rong.36kr.com/api/p/sc/images?type=6";
public static String sActivityUrl = "http://chuang.36kr.com/api/actapply?page=1&pageSize=12"; // 还差浏览更多
public static String sInvestorUrl = "https://rong.36kr.com/n/api/search/user?p=1"; // p=3\4\5..
}
|
package com.droidworker.droidweather.Bean.Impl;
import com.droidworker.droidweather.Bean.IBaseBean;
/**
* @author DroidWorkerLYF
*/
public class WeatherBean implements IBaseBean {
}
|
package be.spring.app.service;
import be.spring.app.controller.exceptions.ObjectNotFoundException;
import be.spring.app.form.CreateAndUpdateTeamForm;
import be.spring.app.model.Account;
import be.spring.app.dto.ActionWrapperDTO;
import be.spring.app.model.Address;
import be.spring.app.model.Team;
import be.spring.app.persistence.AddressDao;
import be.spring.app.persistence.MatchesDao;
import be.spring.app.persistence.TeamDao;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutionException;
/**
* Created by u0090265 on 5/10/14.
*/
@Service
@Transactional
public class TeamServiceImpl implements TeamService {
private static final Logger log = LoggerFactory.getLogger(TeamService.class);
@Autowired
private TeamDao teamDao;
@Autowired
ConcurrentDataService concurrentDataService;
@Autowired
private MatchesDao matchesDao;
@Autowired
private AddressDao addressDao;
@Override
public List<Team> getAll() {
return Lists.newArrayList(teamDao.findAll());
}
@Override
public boolean teamExists(String name) {
return teamDao.getTeamByName(name) != null;
}
@Override
public Team getTeam(long id) {
return teamDao.findOne(id);
}
@Transactional(readOnly = false)
@Override
public Team createTeam(CreateAndUpdateTeamForm form) {
Team team = new Team();
updateTeamFromForm(form, team);
teamDao.save(team);
return team;
}
@Transactional(readOnly = false)
@Override
public Team updateTeam(CreateAndUpdateTeamForm form) {
Team team = teamDao.findOne(form.getId());
updateTeamFromForm(form, team);
teamDao.save(team);
return team;
}
private void updateTeamFromForm(CreateAndUpdateTeamForm form, Team team) {
//If an existing address is chose, get the address, otherwise create a new one.
if (form.isUseExistingAddress()) {
Address address = addressDao.findOne(form.getAddressId());
if (address == null) throw new ObjectNotFoundException(String.format("Address with id %s not found", form.getAddressId()));
team.setAddress(address);
} else {
team.setAddress(getAddress(form));
}
team.setName(form.getTeamName());
}
private Address getAddress(CreateAndUpdateTeamForm form) {
Address address = new Address();
address.setAddress(form.getAddress());
address.setCity(form.getCity());
address.setPostalCode(Integer.parseInt(form.getPostalCode()));
address.setGoogleLink(form.isUseLink() ? form.getGoogleLink() : null);
return address;
}
@Override
public List<ActionWrapperDTO<Team>> getTeams(final Account account, final Locale locale) {
try {
return concurrentDataService.getTeamsActionWrappers(account, locale).get();
} catch (InterruptedException | ExecutionException e) {
log.error("getAllTeams error: {}", e.getMessage());
return Lists.newArrayList();
}
}
@Override
@Transactional(readOnly = false)
public boolean deleteTeam(long id, Account a) {
Team team = teamDao.findOne(id);
if (team == null) return true;
if (!matchesDao.getMatchesForTeam(team).isEmpty()) {
return false;
}
else {
teamDao.delete(team);
return true;
}
}
}
|
package com.github.manage.common.enums.biz;
import com.github.manage.common.enums.result.BizResultEnumBase;
import com.github.manage.common.enums.result.BizResultEnumObject;
/**
* @ProjectName: spring-cloud-examples
* @Package: com.github.manage.common.enums.biz
* @Description: 用户相关提示信息
* @Author: Vayne.Luo
* @date 2018/12/29
*/
public enum UserBizResultEnum implements BizResultEnumBase{
USER_EXIST(1000,"当前用户已存在!") ,
USER_NOT_EXIST(1001,"当前用户不存在!") ,
;
private Integer code;
private String message;
/** 枚举值对象 */
private BizResultEnumObject bizResultEnumObject;
UserBizResultEnum(Integer code, String message) {
bizResultEnumObject = new BizResultEnumObject(code,message);
}
UserBizResultEnum(Integer code, String message,String viewName) {
bizResultEnumObject = new BizResultEnumObject(code,message,viewName);
}
@Override
public BizResultEnumObject getBizResultEnumObject() {
return bizResultEnumObject;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
|
package tv.toby.spring.week02.omw;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.ParameterizedTypeReference;
import tv.toby.spring.week02.a.typetoken.SimpleTypeSafeMap;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by hanmomhanda on 2016-11-06.
*/
public class TypeTokenMain {
public static void main(String[] args) {
class SimpleTypeSafeMap {
private Map<Class<?>, Object> map = new HashMap<>();
public <T> void put(Class<T> k, T v) {
map.put(k, v);
}
public <T> T get(Class<T> k) {
return k.cast(map.get(k));
}
}
SimpleTypeSafeMap simpleTypeSafeMap = new SimpleTypeSafeMap();
simpleTypeSafeMap.put(String.class, "abcde");
simpleTypeSafeMap.put(Integer.class, 123);
// 타입 토큰을 이용해서 별도의 캐스팅 없이도 안전하다.
String v1 = simpleTypeSafeMap.get(String.class);
Integer v2 = simpleTypeSafeMap.get(Integer.class);
System.out.println(v1);
System.out.println(v2);
// 수퍼 타입 토큰을 써보자
class Super<T> {}
class Sub extends Super<List<String>> {}
Sub sub = new Sub();
Type typeOfGenericSuperclass = sub.getClass().getGenericSuperclass();
// 위의 세 줄을 한 줄로 표현하면
// Type typeOfGenericSuperclass = new Super<List<String>>() {}.getClass().getGenericSuperclass();
System.out.println(typeOfGenericSuperclass);
Type actualType = ((ParameterizedType) typeOfGenericSuperclass).getActualTypeArguments()[0];
System.out.println(actualType);
// 아래 코드는 컴파일 에러 발생
// simpleTypeSafeMap.put(actualType, Arrays.asList("a", "b", "c"));
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 SAP SE
* All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* Hybris ("Confidential Information"). You shall not disclose such
* Confidential Information and shall use it only in accordance with the
* terms of the license agreement you entered into with SAP Hybris.
*/
package com.cnk.travelogix.operations.order.converters.populator;
import de.hybris.platform.converters.Populator;
import de.hybris.platform.servicelayer.dto.converter.ConversionException;
import org.springframework.util.Assert;
import com.cnk.travelogix.common.core.cart.data.AccommodationNonPrimaryTravellerData;
import com.cnk.travelogix.common.core.model.NonPrimaryTravellerModel;
/**
* @author C5244544
*/
public class NonPrimaryTravellerPopulator implements Populator<NonPrimaryTravellerModel, AccommodationNonPrimaryTravellerData>
{
@Override
public void populate(final NonPrimaryTravellerModel source, final AccommodationNonPrimaryTravellerData target)
throws ConversionException
{
Assert.notNull(source, "Parameter source cannot be null.");
Assert.notNull(target, "Parameter target cannot be null.");
target.setDateOfBirth(source.getDateOfBirth());
target.setFirstName(source.getFirstName());
target.setLastName(source.getLastName());
target.setMiddleName(source.getMiddleName());
target.setTitle(source.getTitle());
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* SfEcoDetailId generated by hbm2java
*/
public class SfEcoDetailId implements java.io.Serializable {
private String changeuid;
private String seq;
public SfEcoDetailId() {
}
public SfEcoDetailId(String changeuid, String seq) {
this.changeuid = changeuid;
this.seq = seq;
}
public String getChangeuid() {
return this.changeuid;
}
public void setChangeuid(String changeuid) {
this.changeuid = changeuid;
}
public String getSeq() {
return this.seq;
}
public void setSeq(String seq) {
this.seq = seq;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof SfEcoDetailId))
return false;
SfEcoDetailId castOther = (SfEcoDetailId) other;
return ((this.getChangeuid() == castOther.getChangeuid()) || (this.getChangeuid() != null
&& castOther.getChangeuid() != null && this.getChangeuid().equals(castOther.getChangeuid())))
&& ((this.getSeq() == castOther.getSeq()) || (this.getSeq() != null && castOther.getSeq() != null
&& this.getSeq().equals(castOther.getSeq())));
}
public int hashCode() {
int result = 17;
result = 37 * result + (getChangeuid() == null ? 0 : this.getChangeuid().hashCode());
result = 37 * result + (getSeq() == null ? 0 : this.getSeq().hashCode());
return result;
}
}
|
package com.espendwise.manta.web.forms;
import com.espendwise.manta.model.view.SiteHeaderView;
import com.espendwise.manta.spi.Initializable;
import com.espendwise.manta.util.Utility;
import com.espendwise.manta.util.parser.Parse;
import com.espendwise.manta.util.validation.Validation;
import com.espendwise.manta.web.SiteOptionsForm;
import com.espendwise.manta.web.util.AppI18nUtil;
import com.espendwise.manta.web.validator.SiteFormValidator;
@Validation(SiteFormValidator.class)
public class SiteForm extends WebForm implements Initializable {
private DeliveryScheduleForm corporateSchedule;
public static interface ACTION {
public static String CREATE = "/create";
public static String DELETE = "/delete";
public static String CLONE = "/clone";
public static String CLONE_WITH_ASSOC = "/cloneWAssoc";
public static String GET_QRCODE = "/getQRCode";
}
private String selectedAction = ACTION.CLONE;
private String cloneCode;
private String cloneId;
//base
private Long siteId;
private String siteName;
private String accountId;
private String accountName;
private String status;
private String effDate;
private String expDate;
//properties
private String locationBudgetRefNum;
private String locationDistrRefNum;
private String targetFicilityRank;
private String locationLineLevelCode;
private String productBundle;
private String locationComments;
private String locationShipMsg;
//contact
private ContactInputForm contact;
//options
private SiteOptionsForm options;
private boolean init;
public SiteHeaderView getSiteHeader() {
return isNew()
? new SiteHeaderView()
: new SiteHeaderView(siteId, siteName, Parse.parseLong(accountId), accountName);
}
public Long getSiteId() {
return siteId;
}
public void setSiteId(Long siteId) {
this.siteId = siteId;
}
public String getSiteName() {
return siteName;
}
public void setSiteName(String siteName) {
this.siteName = siteName;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getAccountName() {
return accountName;
}
public String getStatus() {
return status;
}
public void setCloneCode(String cloneCode) {
this.cloneCode = cloneCode;
}
public String getCloneCode() {
return cloneCode;
}
public void setStatus(String status) {
this.status = status;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public boolean getIsNew() {
return isNew();
}
public String getExpDate() {
return expDate;
}
public void setExpDate(String expDate) {
this.expDate = expDate;
}
public String getEffDate() {
return effDate;
}
public void setEffDate(String effDate) {
this.effDate = effDate;
}
@Override
public void initialize() {
this.init = true;
}
@Override
public boolean isInitialized() {
return this.init;
}
public String getLocationLineLevelCode() {
return locationLineLevelCode;
}
public void setLocationLineLevelCode(String locationLineLevelCode) {
this.locationLineLevelCode = locationLineLevelCode;
}
public String getLocationDistrRefNum() {
return locationDistrRefNum;
}
public void setLocationDistrRefNum(String locationDistrRefNum) {
this.locationDistrRefNum = locationDistrRefNum;
}
public String getTargetFicilityRank() {
return targetFicilityRank;
}
public void setTargetFicilityRank(String targetFicilityRank) {
this.targetFicilityRank = targetFicilityRank;
}
public String getLocationBudgetRefNum() {
return locationBudgetRefNum;
}
public void setLocationBudgetRefNum(String locationBudgetRefNum) {
this.locationBudgetRefNum = locationBudgetRefNum;
}
public void setCorporateSchedule(DeliveryScheduleForm corporateSchedule) {
this.corporateSchedule = corporateSchedule;
}
public DeliveryScheduleForm getCorporateSchedule() {
return corporateSchedule;
}
public String getProductBundle() {
return productBundle;
}
public void setProductBundle(String productBundle) {
this.productBundle = productBundle;
}
public ContactInputForm getContact() {
return contact;
}
public void setContact(ContactInputForm contact) {
this.contact = contact;
}
public String getSelectedAction() {
return selectedAction;
}
public void setSelectedAction(String selectedAction) {
this.selectedAction = selectedAction;
}
public SiteOptionsForm getOptions() {
return options;
}
public void setOptions(SiteOptionsForm options) {
this.options = options;
}
public void setLocationComments(String locationComments) {
this.locationComments = locationComments;
}
public void setLocationShipMsg(String locationShipMsg) {
this.locationShipMsg = locationShipMsg;
}
public String getLocationComments() {
return locationComments;
}
public String getLocationShipMsg() {
return locationShipMsg;
}
public boolean isNew() {
return isInitialized() && (siteId == null || siteId == 0);
}
public String getCloneId() {
return cloneId;
}
public boolean isClonedWithAssoc() {
return isNew()
&& Utility.strNN(getCloneCode()).equals(SiteForm.ACTION.CLONE_WITH_ASSOC)
&& Utility.longNN(AppI18nUtil.parseNumberNN(cloneId)) > 0;
}
public void setCloneId(String cloneId) {
this.cloneId = cloneId;
}
@Override
public String toString() {
return "SiteForm{" +
"corporateSchedule=" + corporateSchedule +
", selectedAction='" + selectedAction + '\'' +
", cloneCode='" + cloneCode + '\'' +
", cloneId='" + cloneId + '\'' +
", siteId=" + siteId +
", siteName='" + siteName + '\'' +
", accountId='" + accountId + '\'' +
", accountName='" + accountName + '\'' +
", status='" + status + '\'' +
", effDate='" + effDate + '\'' +
", expDate='" + expDate + '\'' +
", locationBudgetRefNum='" + locationBudgetRefNum + '\'' +
", locationDistrRefNum='" + locationDistrRefNum + '\'' +
", targetFicilityRank='" + targetFicilityRank + '\'' +
", locationLineLevelCode='" + locationLineLevelCode + '\'' +
", productBundle='" + productBundle + '\'' +
", locationComments='" + locationComments + '\'' +
", locationShipMsg='" + locationShipMsg + '\'' +
", contact=" + contact +
", options=" + options +
", init=" + init +
'}';
}
}
|
package de.fatoak.engine.actor.components;
import android.util.Log;
import de.fatoak.beerfish.game.GameApp;
import de.fatoak.engine.actor.Actor;
import de.fatoak.engine.event.EventData;
import de.fatoak.engine.event.EventDataNotFoundException;
import de.fatoak.engine.event.IEventCallback;
import de.fatoak.engine.math.Vector;
import de.fatoak.engine.resource.DataElement;
import de.fatoak.engine.util.Logger;
/**
* Created by Markus on 09.05.2014.
*/
public final class AnimationComponent extends ActorComponent {
public final static String NAME = "AnimationComponent";
public enum ANIMATION_TYPE {
NONE,
IDLING,
MOVING
}
private boolean mAnimationIsPlayed = false;
private Actor mParentActor;
private ANIMATION_TYPE mTypeOfCurrentAnimation = ANIMATION_TYPE.NONE;
public AnimationComponent(Actor actor) {
mParentActor = actor;
}
public AnimationComponent(Actor actor, DataElement componentElement) {
this(actor);
}
public void init() {
registerEvents();
GameApp.getSingleton().logString(
Logger.LOGGING_FLAG.INFO,
"AnimationComponent was initialized for actor with id: " +
mParentActor.getActorId()
);
}
public String getName() {
return NAME;
}
public void startAnimation(ANIMATION_TYPE animationType, Vector diffVector) {
// Winkel ausrechnen, sodass Körper entsprechend verdreht wird.
}
public void stopAnimation() {
}
private void registerEvents() {
GameApp.getSingleton().listenToEvent("actorPositionChanged", new IEventCallback() {
@Override
public void eventTriggered(EventData eventData) {
try {
if(mParentActor.getActorId()!=eventData.getInt("actorId"))
return ;
Vector diffVector = new Vector(
eventData.getFloat("diffX"),
eventData.getFloat("diffY"),
eventData.getFloat("diffZ"));
ANIMATION_TYPE animationType = ANIMATION_TYPE.MOVING;
startAnimation(animationType, diffVector);
} catch(EventDataNotFoundException e) {
GameApp.getSingleton().logString(
Logger.LOGGING_FLAG.ERROR,
"Couldn't start animation for actor: " + mParentActor.getActorId() +
", because of EventDataNotFoundException: " + e.getMessage());
}
}
});
}
}
|
package com.tencent.mm.plugin.profile.ui;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.tencent.mm.R;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.g.a.su;
import com.tencent.mm.g.c.ai;
import com.tencent.mm.model.au;
import com.tencent.mm.model.c;
import com.tencent.mm.model.q;
import com.tencent.mm.model.s;
import com.tencent.mm.pluginsdk.model.m;
import com.tencent.mm.pluginsdk.ui.preference.b;
import com.tencent.mm.sdk.e.j.a;
import com.tencent.mm.sdk.e.k;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.ab;
import com.tencent.mm.ui.MMActivity;
import com.tencent.mm.ui.base.h;
import com.tencent.mm.ui.base.preference.Preference;
import java.util.List;
import junit.framework.Assert;
public class NormalUserFooterPreference extends Preference implements a {
private MMActivity bGc;
protected k<e, String> dHn = new 1(this);
public ProgressDialog eHw = null;
private int eLK;
private ab guS;
private String hev = null;
private boolean iAc;
private String juZ = "";
private Button kXG;
private boolean lUD;
private int lVM = 0;
private long lWQ = 0;
private int lWd;
private String lWl = "";
private boolean lWr = false;
private boolean lXa = false;
private boolean lXb;
private boolean lXc;
private boolean lXd = false;
private boolean lXe = false;
private a lXf;
private View lXg;
private Button lXh;
private Button lXi;
private Button lXj;
private View lXk;
private Button lXl;
private View lXm;
private Button lXn;
private Button lXo;
private Button lXp;
private Button lXq;
private Button lXr;
private Button lXs;
private TextView lXt;
private boolean lXu = false;
public boolean lXv = false;
class i extends c implements e {
private ProgressDialog eHw;
public i() {
super(NormalUserFooterPreference.this);
}
protected void bnA() {
onDetach();
onStop();
au.DF().a(30, (e) this);
au.DF().a(667, (e) this);
au.DF().a(853, (e) this);
super.bnA();
}
final void onStop() {
au.DF().b(30, (e) this);
au.DF().b(667, (e) this);
au.DF().b(853, (e) this);
}
protected void onDetach() {
if (this.eHw != null) {
this.eHw.dismiss();
this.eHw = null;
}
if (NormalUserFooterPreference.this.lXg != null) {
NormalUserFooterPreference.this.lXg.setVisibility(8);
}
if (NormalUserFooterPreference.this.lXm != null) {
NormalUserFooterPreference.this.lXm.setVisibility(0);
}
if (NormalUserFooterPreference.this.kXG != null) {
NormalUserFooterPreference.this.kXG.setVisibility(8);
}
if (NormalUserFooterPreference.this.lXs != null) {
NormalUserFooterPreference.this.lXs.setVisibility(8);
}
if (NormalUserFooterPreference.this.lXq != null) {
NormalUserFooterPreference.this.lXq.setVisibility(8);
}
if (NormalUserFooterPreference.this.lXp != null) {
NormalUserFooterPreference.this.lXp.setVisibility(8);
}
if (NormalUserFooterPreference.this.lXt != null) {
NormalUserFooterPreference.this.lXt.setVisibility(8);
}
onStop();
}
private void Bb() {
NormalUserFooterPreference normalUserFooterPreference = NormalUserFooterPreference.this;
au.HU();
ab Yg = c.FR().Yg(NormalUserFooterPreference.this.guS.field_username);
if (Yg == null || ((int) Yg.dhP) == 0) {
ai a = NormalUserFooterPreference.this.guS;
au.HU();
if (c.FR().S(a)) {
au.HU();
Yg = c.FR().Yg(NormalUserFooterPreference.this.guS.field_username);
} else {
x.e("MicroMsg.NormalUserFooterPreference", "insert contact failed, username = " + a.field_username);
Yg = null;
}
}
normalUserFooterPreference.guS = Yg;
if (NormalUserFooterPreference.this.guS != null) {
s.p(NormalUserFooterPreference.this.guS);
}
}
protected void bnG() {
if (NormalUserFooterPreference.this.lXf != null) {
NormalUserFooterPreference.this.lXf.onDetach();
}
NormalUserFooterPreference.this.lXf = new c(NormalUserFooterPreference.this);
NormalUserFooterPreference.this.lXf.FC();
}
public void a(int i, int i2, String str, l lVar) {
int i3 = 0;
x.d("MicroMsg.NormalUserFooterPreference", "onSceneEnd, errType = " + i + ", errCode = " + i2);
if (lVar.getType() == 30 || lVar.getType() == 667 || lVar.getType() == 853) {
onStop();
if (this.eHw != null) {
this.eHw.dismiss();
this.eHw = null;
}
if (bi.ci(NormalUserFooterPreference.this.mContext)) {
int i4;
if (i == 0 && i2 == 0) {
if (lVar.getType() == 30) {
i4 = ((m) lVar).bOh;
x.d("MicroMsg.NormalUserFooterPreference", "VerifyBaseHandler onSceneEnd, opCode = " + i4);
if (i4 == 1 || i4 == 3) {
List<String> list = ((m) lVar).qyZ;
if (list != null && list.contains(NormalUserFooterPreference.this.guS.field_username)) {
NormalUserFooterPreference.this.lXu = true;
Bb();
bnG();
for (String aU : list) {
b.aU(aU, NormalUserFooterPreference.this.eLK);
}
au.getNotification().xR();
return;
}
return;
}
return;
} else if (lVar.getType() == 667 || lVar.getType() == 853) {
NormalUserFooterPreference.this.lXu = true;
Bb();
bnG();
b.aU(NormalUserFooterPreference.this.guS.field_username, NormalUserFooterPreference.this.eLK);
au.getNotification().xR();
return;
}
}
if (i == 4 && i2 == -302) {
if (lVar.getType() == 30) {
i4 = ((m) lVar).bOh;
} else {
i4 = 0;
}
x.w("MicroMsg.NormalUserFooterPreference", "VerifyBaseHandler onSceneEnd, verify relation out of date, opCode = %d", Integer.valueOf(i4));
if (i4 == 3 || lVar.getType() == 853) {
h.a(NormalUserFooterPreference.this.bGc, NormalUserFooterPreference.this.bGc.getString(R.l.contact_info_verify_outofdate_msg), NormalUserFooterPreference.this.bGc.getString(R.l.app_tip), NormalUserFooterPreference.this.bGc.getString(R.l.app_add), NormalUserFooterPreference.this.bGc.getString(R.l.app_cancel), new OnClickListener() {
public final void onClick(DialogInterface dialogInterface, int i) {
i.this.bnF();
}
}, null);
}
} else if (i == 4 && i2 == -24 && !bi.oW(str)) {
Toast.makeText(NormalUserFooterPreference.this.bGc, str, 1).show();
} else {
switch (i) {
case 1:
if (!au.DF().Lh()) {
if (com.tencent.mm.network.ab.bU(NormalUserFooterPreference.this.mContext)) {
com.tencent.mm.pluginsdk.ui.j.eY(NormalUserFooterPreference.this.mContext);
i3 = 1;
break;
}
}
au.DF().getNetworkServerIp();
new StringBuilder().append(i2);
i3 = 1;
break;
break;
case 2:
Toast.makeText(NormalUserFooterPreference.this.mContext, NormalUserFooterPreference.this.mContext.getString(R.l.fmt_iap_err, new Object[]{Integer.valueOf(2), Integer.valueOf(i2)}), 3000).show();
i3 = 1;
break;
case 4:
if (i2 != -100) {
CharSequence str2;
if (i == 4 && i2 == -34) {
str2 = NormalUserFooterPreference.this.bGc.getString(R.l.fmessage_request_too_offen);
} else if (i == 4 && i2 == -94) {
str2 = NormalUserFooterPreference.this.bGc.getString(R.l.fmessage_user_not_support);
} else if (i != 4 || bi.oW(str2)) {
str2 = NormalUserFooterPreference.this.bGc.getString(R.l.sendrequest_send_fail);
}
Toast.makeText(NormalUserFooterPreference.this.bGc, str2, 1).show();
break;
}
h.a(NormalUserFooterPreference.this.mContext, au.Dh(), com.tencent.mm.bp.a.af(NormalUserFooterPreference.this.mContext, R.l.app_tip), new 1(this), new 2(this));
i3 = 1;
break;
break;
}
if (i3 == 0) {
}
}
}
}
}
}
class j extends i implements e {
public j() {
super();
}
protected final void bnC() {
if (NormalUserFooterPreference.this.guS == null || !com.tencent.mm.l.a.gd(NormalUserFooterPreference.this.guS.field_type)) {
z(false, true);
} else {
bnB();
}
}
protected final void bnA() {
super.bnA();
NormalUserFooterPreference.this.lXg.setVisibility(0);
NormalUserFooterPreference.this.lXp.setVisibility(8);
NormalUserFooterPreference.this.kXG.setVisibility(8);
NormalUserFooterPreference.this.lXs.setVisibility(8);
NormalUserFooterPreference.this.lXq.setVisibility(8);
NormalUserFooterPreference.this.lXr.setVisibility(8);
NormalUserFooterPreference.this.lXm.setVisibility(8);
NormalUserFooterPreference.this.lXt.setVisibility(8);
switch (NormalUserFooterPreference.this.eLK) {
case 1:
case 2:
case 3:
case 12:
case 13:
case 18:
case 22:
case 23:
case 24:
case 25:
case 26:
case 27:
case 28:
case 29:
case 30:
case 34:
case 58:
case 59:
case 60:
NormalUserFooterPreference.this.lXl.setVisibility(0);
NormalUserFooterPreference.this.lXk.setVisibility(0);
break;
default:
NormalUserFooterPreference.this.lXl.setVisibility(8);
NormalUserFooterPreference.this.lXk.setVisibility(8);
break;
}
if (NormalUserFooterPreference.this.guS.BA()) {
NormalUserFooterPreference.this.lXj.setText(NormalUserFooterPreference.this.bGc.getString(R.l.contact_info_moveout_blacklist));
NormalUserFooterPreference.this.lXt.setVisibility(0);
} else {
NormalUserFooterPreference.this.lXj.setText(NormalUserFooterPreference.this.bGc.getString(R.l.contact_info_movein_blacklist));
}
NormalUserFooterPreference.this.lXh.setOnClickListener(new 1(this));
NormalUserFooterPreference.this.lXj.setOnClickListener(new 2(this));
}
protected final void onDetach() {
super.onDetach();
}
protected final void bnG() {
super.bnG();
}
public final void a(int i, int i2, String str, l lVar) {
super.a(i, i2, str, lVar);
}
}
public NormalUserFooterPreference(Context context) {
super(context);
this.bGc = (MMActivity) context;
init();
}
public NormalUserFooterPreference(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
this.bGc = (MMActivity) context;
init();
}
public NormalUserFooterPreference(Context context, AttributeSet attributeSet, int i) {
super(context, attributeSet, i);
this.bGc = (MMActivity) context;
init();
}
private void init() {
this.iAc = false;
this.lXf = null;
}
private void initView() {
if (!this.iAc || this.guS == null) {
x.w("MicroMsg.NormalUserFooterPreference", "iniView : bindView = " + this.iAc + " contact = " + this.guS);
if (this.lXf != null) {
try {
this.lXf.bnC();
return;
} catch (Throwable th) {
return;
}
}
return;
}
if (this.lXf != null) {
this.lXf.FC();
}
bnx();
}
public final void onBindView(View view) {
x.d("MicroMsg.NormalUserFooterPreference", "on bindView " + view.toString());
this.lXg = view.findViewById(R.h.contact_info_passive_verify);
this.lXh = (Button) view.findViewById(R.h.contact_info_verify_accept);
this.lXi = (Button) view.findViewById(R.h.contact_info_delete_contact);
this.lXl = (Button) view.findViewById(R.h.contact_info_verify_expose_btn);
this.lXk = view.findViewById(R.h.contact_info_verify_mid);
this.lXj = (Button) view.findViewById(R.h.contact_info_verify_add_black);
this.lXp = (Button) view.findViewById(R.h.contact_info_add_contact_btn);
this.lXm = view.findViewById(R.h.contact_info_sayhi_item);
this.lXn = (Button) view.findViewById(R.h.contact_info_sayhi_expose_btn);
this.lXo = (Button) view.findViewById(R.h.contact_info_sayhi_request_btn);
this.kXG = (Button) view.findViewById(R.h.contact_info_send_btn);
this.lXs = (Button) view.findViewById(R.h.contact_info_mod_snspermission_btn);
this.lXq = (Button) view.findViewById(R.h.contact_info_voip_btn);
this.lXr = (Button) view.findViewById(R.h.contact_info_black_list_expose_btn);
this.lXt = (TextView) view.findViewById(R.h.contact_info_movein_blacklist_tip_tv);
this.iAc = true;
initView();
super.onBindView(view);
if (this.bGc.getIntent().getBooleanExtra("Accept_NewFriend_FromOutside", false) && this.lXh != null) {
this.lXh.performClick();
}
}
public final boolean a(ab abVar, String str, boolean z, boolean z2, boolean z3, int i, int i2, boolean z4, boolean z5, long j, String str2) {
auw();
Assert.assertTrue(abVar != null);
Assert.assertTrue(bi.oV(abVar.field_username).length() > 0);
if (ab.XV(q.GF()).equals(abVar.field_username)) {
return false;
}
this.guS = abVar;
this.juZ = str;
this.lUD = z;
this.eLK = i;
this.lWd = i2;
this.lXc = bi.a(Boolean.valueOf(s.hc(abVar.field_username)), false);
this.lXa = z4;
this.lXb = z5;
this.lWQ = j;
this.lWl = str2;
this.lXv = false;
this.lWr = abVar.field_deleteFlag == 1;
this.lXu = this.bGc.getIntent().getBooleanExtra("Contact_AlwaysShowSnsPreBtn", false);
this.lVM = this.bGc.getIntent().getIntExtra("add_more_friend_search_scene", 0);
this.lXd = this.bGc.getIntent().getBooleanExtra("Contact_IsLbsChattingProfile", false);
this.lXe = this.bGc.getIntent().getBooleanExtra("Contact_IsLbsGotoChatting", false);
this.hev = this.bGc.getIntent().getStringExtra("lbs_ticket");
if (!q.gQ(abVar.field_username)) {
au.HU();
if (!c.FZ().has(abVar.field_username)) {
if (ab.XO(abVar.field_username)) {
this.lXf = new h(this);
} else if (s.hr(abVar.field_username)) {
this.lXf = new d(this);
} else if (s.hc(abVar.field_username)) {
this.lXf = new g(this);
} else if (ab.XP(abVar.field_username)) {
this.lXf = new f(this);
} else if (com.tencent.mm.l.a.gd(abVar.field_type) && !ab.gY(abVar.field_username)) {
this.lXf = new c(this);
this.lXv = true;
} else if (z2) {
this.lXf = new j();
this.lXv = true;
} else if (z3 || ab.gY(abVar.field_username)) {
this.lXf = new b(this);
} else {
this.lXf = new c(this);
this.lXv = true;
}
initView();
return true;
}
}
this.lXf = new c(this);
this.lXv = true;
initView();
return true;
}
public final boolean bnx() {
if (this.lXu && com.tencent.mm.l.a.gd(this.guS.field_type)) {
this.lXs.setVisibility(0);
return true;
}
this.lXs.setVisibility(8);
return false;
}
public final boolean auw() {
if (this.lXf != null) {
this.lXf.onDetach();
}
this.dHn.removeAll();
if (this.eHw != null) {
this.eHw.dismiss();
this.eHw = null;
}
return true;
}
public final void a(String str, com.tencent.mm.sdk.e.l lVar) {
if (bi.oV(str).length() <= 0 || this.guS == null) {
return;
}
if (str.equals(this.guS.field_username) || str.equals(this.guS.field_encryptUsername)) {
au.HU();
this.guS = c.FR().Yg(this.guS.field_username);
ah.A(new 2(this));
}
}
public final void bny() {
x.i("MicroMsg.NormalUserFooterPreference", "summerper checkPermission checkmicrophone[%b], stack[%s], activity[%s]", Boolean.valueOf(com.tencent.mm.pluginsdk.permission.a.a(this.bGc, "android.permission.RECORD_AUDIO", 82, "", "")), bi.cjd(), this.bGc);
if (com.tencent.mm.pluginsdk.permission.a.a(this.bGc, "android.permission.RECORD_AUDIO", 82, "", "")) {
su suVar = new su();
suVar.cdE.bOh = 5;
suVar.cdE.talker = this.guS.field_username;
suVar.cdE.context = this.bGc;
suVar.cdE.cdz = 4;
com.tencent.mm.sdk.b.a.sFg.m(suVar);
}
}
public final void bnz() {
x.i("MicroMsg.NormalUserFooterPreference", "summerper checkPermission checkCamera[%b], stack[%s], activity[%s]", Boolean.valueOf(com.tencent.mm.pluginsdk.permission.a.a(this.bGc, "android.permission.CAMERA", 19, "", "")), bi.cjd(), this.bGc);
if (com.tencent.mm.pluginsdk.permission.a.a(this.bGc, "android.permission.CAMERA", 19, "", "")) {
x.i("MicroMsg.NormalUserFooterPreference", "summerper checkPermission checkmicrophone[%b], stack[%s], activity[%s]", Boolean.valueOf(com.tencent.mm.pluginsdk.permission.a.a(this.bGc, "android.permission.RECORD_AUDIO", 19, "", "")), bi.cjd(), this.bGc);
if (com.tencent.mm.pluginsdk.permission.a.a(this.bGc, "android.permission.RECORD_AUDIO", 19, "", "")) {
su suVar = new su();
suVar.cdE.bOh = 5;
suVar.cdE.talker = this.guS.field_username;
suVar.cdE.context = this.bGc;
suVar.cdE.cdz = 2;
com.tencent.mm.sdk.b.a.sFg.m(suVar);
}
}
}
}
|
package Dominio;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import Persistencia.EmpleadoPers;
// Esta es la clase del usuario que vaya a acceder al menú de los vehículos
// Declaración de variables, que tiene la clase Empleado,
public class Empleado {
private int codigoAcceso;
private String nombreUsuario;
private String password;
private EmpleadoPers empleadopers;
// Declaración de constructores.
public Empleado(int codigoAcceso, String nombreUsuario, String password) {
this.codigoAcceso = codigoAcceso;
this.nombreUsuario = nombreUsuario;
this.password = password;
this.empleadopers= new EmpleadoPers();
}
public Empleado() {
this.empleadopers= new EmpleadoPers();
}
// Creación de getters y setters de las variables indicadas previamente.
public int getCodigoAcceso() {
return codigoAcceso;
}
public void setCodigoAcceso(int codigoAcceso) {
this.codigoAcceso = codigoAcceso;
}
public String getNombreUsuario() {
return nombreUsuario;
}
public void setNombreUsuario(String nombreUsuario) {
this.nombreUsuario = nombreUsuario;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
// Se crea esta clase, para que se pueda leer los datos del usuario.
public ArrayList<Empleado> leerEmpleados() throws FileNotFoundException {
return empleadopers.leer();
}
}
|
package view;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import service.UserService;
import entity.UserInfo;
/**
* 用户信息添加面板
* @author 张丹
*
*/
public class AddUserInfoView extends JPanel implements ActionListener {
private JLabel jLabel;
private JLabel jLabel2;
private JLabel jLabel3;
private JLabel jLabel4;
private JLabel jLabel5;
private JLabel jLabel6;
private JTextField jTextField;
private JPasswordField jPasswordField;
private ButtonGroup buttonGroup;
private ButtonGroup buttonGroup2;
private JRadioButton jRadioButton;
private JRadioButton jRadioButton2;
private JRadioButton jRadioButton3;
private JRadioButton jRadioButton4;
private JButton jButton5;
private JButton jButton6;
private UserService userservice = new UserService();
public AddUserInfoView() {
this.setSize(500, 500);
this.setLayout(null);
this.createComponent();
}
public void createComponent() {
this.jLabel = new JLabel("用户名");
this.jLabel2 = new JLabel("用户密码");
this.jLabel3 = new JLabel("性别");
this.jLabel4 = new JLabel("用户权限");
this.jLabel5 = new JLabel("确定");
this.jLabel6 = new JLabel("重置");
this.jButton5 = new JButton("确定");
this.jButton6 = new JButton("重置");
this.jTextField = new JTextField(10);
this.jTextField.setOpaque(false);
this.jPasswordField = new JPasswordField(10);
this.jPasswordField.setOpaque(false);
this.jRadioButton = new JRadioButton("男");
this.jRadioButton.setOpaque(false);
this.jRadioButton2 = new JRadioButton("女");
this.jRadioButton2.setOpaque(false);
this.buttonGroup = new ButtonGroup();
this.buttonGroup.add(jRadioButton);
this.buttonGroup.add(jRadioButton2);
this.jRadioButton3 = new JRadioButton("服务员");
this.jRadioButton3.setOpaque(false);
this.jRadioButton4 = new JRadioButton("管理员");
this.jRadioButton4.setOpaque(false);
this.buttonGroup2 = new ButtonGroup();
this.buttonGroup2.add(jRadioButton3);
this.buttonGroup2.add(jRadioButton4);
jButton5.setLayout(null);
jLabel5.setBounds(30, 0, 40, 40);
this.jButton5.add(jLabel5);
// 在按钮上添加图片
ImageIcon icon = new ImageIcon("images/4.jpg");
this.jButton5.setIcon(icon);
jButton6.setLayout(null);
jLabel6.setBounds(30, 0, 40, 40);
jButton6.setIcon(icon);
this.jButton6.add(jLabel6);
this.jLabel.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.jLabel.setForeground(new Color(92, 167, 186));
this.jLabel2.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.jLabel2.setForeground(new Color(92, 167, 186));
this.jLabel3.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.jLabel3.setForeground(new Color(92, 167, 186));
this.jLabel4.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.jLabel4.setForeground(new Color(92, 167, 186));
this.jRadioButton.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.jRadioButton.setForeground(new Color(137, 190, 178));
this.jRadioButton2.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.jRadioButton2.setForeground(new Color(137, 190, 178));
this.jRadioButton3.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.jRadioButton3.setForeground(new Color(137, 190, 178));
this.jRadioButton4.setFont(new Font("华文行楷", Font.PLAIN, 14));
this.jRadioButton4.setForeground(new Color(137, 190, 178));
this.jLabel.setBounds(140, 40, 100, 40);
this.jTextField.setBounds(240, 40, 100, 40);
this.jLabel2.setBounds(140, 100, 100, 40);
this.jPasswordField.setBounds(240, 100, 100, 40);
this.jLabel3.setBounds(140, 160, 100, 40);
this.jRadioButton.setBounds(240, 160, 100, 40);
this.jRadioButton2.setBounds(340, 160, 100, 40);
this.jLabel4.setBounds(140, 220, 100, 40);
this.jRadioButton3.setBounds(240, 220, 100, 40);
this.jRadioButton4.setBounds(340, 220, 100, 40);
this.jButton5.setBounds(140, 320, 100, 40);
this.jButton6.setBounds(280, 320, 100, 40);
// ImageIcon icon=new ImageIcon("image/01");
// jButton5.setIcon(icon);
this.add(jLabel);
this.add(jLabel2);
this.add(jLabel3);
this.add(jLabel4);
this.add(jTextField);
this.add(jPasswordField);
this.add(jRadioButton);
this.add(jRadioButton2);
this.add(jRadioButton3);
this.add(jRadioButton4);
this.add(jButton5);
this.add(jButton6);
this.jButton5.addActionListener(this);
this.jButton6.addActionListener(this);
}
public void clearData() {
this.jTextField.setText("");
this.jPasswordField.setText("");
this.buttonGroup.clearSelection();
this.buttonGroup2.clearSelection();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getActionCommand().trim().equals("确定")) {
UserInfo newuserinfo = new UserInfo();
newuserinfo.setU_name(jTextField.getText());
newuserinfo.setU_password(jPasswordField.getText());
if (jRadioButton.isSelected()) {
newuserinfo.setU_sex(jRadioButton.getText());
if (jRadioButton3.isSelected()) {
newuserinfo.setU_comptce(jRadioButton3.getText());
}
if (jRadioButton4.isSelected()) {
newuserinfo.setU_comptce(jRadioButton4.getText());
}
}
if (jRadioButton2.isSelected()) {
newuserinfo.setU_sex(jRadioButton2.getText());
if (jRadioButton3.isSelected()) {
newuserinfo.setU_comptce(jRadioButton3.getText());
}
if (jRadioButton4.isSelected()) {
newuserinfo.setU_comptce(jRadioButton4.getText());
}
}if(!newuserinfo.getU_name().equals("")&&!newuserinfo.getU_password().equals("")&&newuserinfo.getU_sex()!=null&&newuserinfo.getU_comptce()!=null){
UserInfo findUserinfo = new UserInfo();
findUserinfo.setU_name(jTextField.getText());
if (userservice.getUserInfo(findUserinfo).size() == 0) {
boolean flag = userservice.addUserInfo(newuserinfo);
// System.out.println(flag);
if (flag) {
JOptionPane.showMessageDialog(this, "添加成功");
this.clearData();
} else {
JOptionPane.showMessageDialog(this, "添加未成功");
}
} else {
JOptionPane.showMessageDialog(this, "您添加的员工已存在,请重新添加");
}
}
else{
JOptionPane.showMessageDialog(this, "填写的信息不全,请补充");
}
}
if (e.getActionCommand().trim().equals("重置")) {
this.clearData();
}
}
}
|
package exercicios;
import java.util.Scanner;
public class Ex02 {
public void executa() {
// Cria o scanner para leitura dos dados
Scanner sc = new Scanner(System.in);
// Recebe o primeiro double
System.out.println("Informe o 1o double:");
double d1 = sc.nextDouble();
// Recebe o segundo double
System.out.println("Informe o 2o double:");
double d2 = sc.nextDouble();
// Impressão dos resultados
System.out.printf("%.2f + %.2f = %.2f\n", d1, d2, d1 + d2);
System.out.printf("%.2f - %.2f = %.2f\n", d1, d2, d1 - d2);
System.out.printf("%.2f * %.2f = %.2f\n", d1, d2, d1 * d2);
System.out.printf("%.2f / %.2f = %.2f\n", d1, d2, d1 / d2);
}
}
|
package com.arkinem.libraryfeedbackservice.model;
import java.util.List;
import java.util.UUID;
import javax.validation.constraints.NotBlank;
public class QuestionDto {
private final UUID id;
@NotBlank
private final String body;
private final List<Answer> answers;
private final boolean isDeleted;
public QuestionDto(UUID id, String body, List<Answer> answers, boolean isDeleted) {
this.id = id;
this.body = body;
this.answers = answers;
this.isDeleted = isDeleted;
}
public UUID getId( ) {
return id;
}
public String getBody() {
return body;
}
public List<Answer> getAnswers() {
return answers;
}
public boolean getIsDeleted() {
return isDeleted;
}
}
|
package com.danielnamur.javaexamsimulator.controllers;
import java.util.List;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.danielnamur.javaexamsimulator.models.Course;
import com.danielnamur.javaexamsimulator.models.User;
import com.danielnamur.javaexamsimulator.services.CourseService;
import com.danielnamur.javaexamsimulator.services.UserService;
import com.danielnamur.javaexamsimulator.validator.UserValidator;
@Controller
public class JavaExamController {
private CourseService courseService;
private UserService userService;
private UserValidator userValidator;
public JavaExamController(CourseService courseService, UserService userService, UserValidator userValidator) {
this.courseService = courseService;
this.userService = userService;
this.userValidator = userValidator;
}
@RequestMapping("/")
public String index(@ModelAttribute("user") User user) {
return "index.jsp";
}
@RequestMapping(value="/registration", method=RequestMethod.POST)
public String registerUser(@Valid @ModelAttribute("user") User user, BindingResult result, HttpSession session) {
userValidator.validate(user, result);
if(result.hasErrors()) {
return "index.jsp";
}
User u = userService.registerUser(user);
session.setAttribute("userId", u.getId());
return "redirect:/courses";
}
@RequestMapping(value="/login", method=RequestMethod.POST)
public String loginUser(@RequestParam("email") String email, @RequestParam("password") String password,
Model model,HttpSession session) {
boolean isAuthenticated = userService.authenticateUser(email, password);
if(isAuthenticated) {
User u = userService.findByEmail(email);
session.setAttribute("userId", u.getId());
return "redirect:/courses";
}
else {
model.addAttribute("error", "Correo o contraseña incorrecta. Intentalo nuevamente");
return "index.jsp";
}
}
@RequestMapping("/courses")
public String homePage(HttpSession session, Model model) {
if(session.getAttribute("userId") !=null) {
User user = userService.findUserById((Long) session.getAttribute("userId"));
model.addAttribute("user", user);
List<Course> courseList = courseService.findAllCourses();
model.addAttribute("course", courseList);
return "homePage.jsp";
}
else {
return "redirect:/";
}
}
@RequestMapping("/logout")
public String logout(HttpSession session) {
session.invalidate();
return "redirect:/";
}
@RequestMapping("/courses/new")
public String createCourse(@Valid @ModelAttribute("course") Course course, BindingResult result, HttpSession session) {
if(result.hasErrors()) {
return "course.jsp";
}
else {
courseService.createCourse(course);
return "redirect:/courses";
}
}
//Información del Curso
@RequestMapping("courses/{id}")
public String displayCourse(@PathVariable("id") Long id, Model model, HttpSession session) {
Course myCourse = courseService.findCourseById(id);
model.addAttribute("course", myCourse);
Long userId = (Long) session.getAttribute("userId");
User u = userService.findUserById(userId);
model.addAttribute("currentUser", u);
return "courseInfo.jsp";
}
//Agregar Usuario a un Curso
@RequestMapping("courses/add/{id}")
public String addCourse(@PathVariable("id") Long id, Model model, HttpSession session) {
Long userId = (Long) session.getAttribute("userId");
User u = userService.findUserById(userId);
Course course = courseService.findCourseById(id);
u.getCourses().add(course);
userService.updateUser(u);
return "redirect:/courses";
}
//Editar Curso
@RequestMapping("/courses/edit/{id}")
public String editPage(@ModelAttribute("course") Course myCourse, @PathVariable("id")Long myId, Model model) {
Course course = courseService.findCourseById(myId);
model.addAttribute("course", course);
return "editCourse.jsp";
}
//Actualizar Curso
@PostMapping("/courses/update")
public String updateCourse(@Valid @ModelAttribute("course")Course myCourse, BindingResult result) {
if(result.hasErrors()) {
return "edit.jsp";
}
else {
courseService.updateCourse(myCourse);
return "redirect:/courses";
}
}
//Eliminar Curso
@RequestMapping("/courses/delete/{id}")
public String deleteCourse(@PathVariable("id")Long id) {
Course myCourse = courseService.findCourseById(id);
if(myCourse != null) {
courseService.deleteCourse(myCourse);
return "redirect:/courses";
}
else {
return "redirect:/courses";
}
}
//Remover Usuario del Curso
@RequestMapping("/courses/remove/{id}")
public String removerUserFromCourse(@PathVariable("id") Long myId, Model model, HttpSession session) {
Long userId = (Long) session.getAttribute("userId");
User u = userService.findUserById(userId);
Course course = courseService.findCourseById(myId);
u.getCourses().remove(course);
userService.updateUser(u);
return "redirect:/courses";
}
}
|
package mybatis.bean;
/**
* Õ½Ú
* @author gongxb
*
* 2017Äê11ÔÂ22ÈÕ
*/
public class Chapter {
private String name;
private String id;
private String bookId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBookId() {
return bookId;
}
public void setBookId(String bookId) {
this.bookId = bookId;
}
@Override
public String toString() {
return "Chapter [name=" + name + ", id=" + id + ", bookId=" + bookId + "]";
}
}
|
package fr.doranco.ecommerce.vue;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import fr.doranco.ecommerce.entity.pojo.Article;
import fr.doranco.ecommerce.entity.pojo.ArticlePanier;
import fr.doranco.ecommerce.entity.pojo.Utilisateur;
import fr.doranco.ecommerce.metier.ArticleMetier;
import fr.doranco.ecommerce.metier.IArticleMetier;
import fr.doranco.ecommerce.metier.IPanierMetier;
import fr.doranco.ecommerce.metier.IUtilisateurMetier;
import fr.doranco.ecommerce.metier.PanierMetier;
import fr.doranco.ecommerce.metier.UtilisateurMetier;
@ManagedBean(name = "gestionAchatBean")
@SessionScoped
public class GestionAchatBean implements Serializable {
private static final long serialVersionUID = 1L;
private IPanierMetier panierMetier = new PanierMetier();
private IUtilisateurMetier userMetier = new UtilisateurMetier();
@ManagedProperty(name = "messageSuccess", value = "")
private String messageSuccess = " ";
@ManagedProperty(name = "messageError", value = "")
private String messageError = " ";
Utilisateur user = LoginBean.getConnectedUser();
public GestionAchatBean() {
}
public String ajouterAuPanier(Article article, String quantite) {
System.out.println(user.getPanier());
Integer qte = Integer.valueOf(quantite);
ArticlePanier articlePanier = null;
boolean isFound = false;
for (ArticlePanier ap : user.getPanier()) {
if (ap.getArticle().getId().equals(article.getId())) {
articlePanier = ap;
isFound = true;
}
}
if (isFound) {
Integer indexArticlePanier = user.getPanier().indexOf(articlePanier);
articlePanier.setQuantite(articlePanier.getQuantite() + qte);
user.getPanier().set(indexArticlePanier, articlePanier);
} else {
ArticlePanier newArticlePanier = new ArticlePanier(article, Integer.valueOf(quantite));
newArticlePanier.setUtilisateur(user);;
user.getPanier().add(newArticlePanier);
// newArticlePanier.setUtilisateur(user);;
// user.getPanier().add(newArticlePanier);
//pb 1 article panier n'a pas d'utilisateur,
//pb 2
// Voir l'explication de Asmaa si l'utilisateur n'a pas d'article dans son panier alors faire le Add
}
try {
userMetier.updateUtilisateur(user);
messageSuccess = "Article ajouté avec succès au panier";
} catch (Exception e1) {
e1.printStackTrace();
return "";
}
return "";
}
// public String ajouterAuPanier2(Article article, String quantite) {
//
// System.out.println(user.getPanier());
// Integer qte = Integer.valueOf(quantite);
// ArticlePanier articlePanier = new ArticlePanier();
// articlePanier.setArticle(article);
// articlePanier.setUtilisateur(user);
//
// if (user.getPanier().contains(articlePanier)) {
// Integer oldQuantite = user.getPanier().get(user.getPanier().indexOf(articlePanier)).getQuantite();
// user.getPanier().get(user.getPanier().indexOf(articlePanier)).setQuantite(qte + oldQuantite);
// }
// Boolean IsArticleIdentiqueDansUserPanier = false;
//
// List<ArticlePanier> articlePaniers = null;
// try {
// articlePaniers = panierMetier.getPanierByUser(user.getId());
// } catch (Exception e2) {
// // TODO Auto-generated catch block
// e2.printStackTrace();
// }
//
// for (ArticlePanier articleP : articlePaniers) {
//
// if (article.getId().equals(articleP.getArticle().getId())
// && articlePanier.getUtilisateur().getId().equals(articleP.getUtilisateur().getId())) {
// Integer oldQuantite = articleP.getQuantite();
// articlePanier.setQuantite(qte + oldQuantite);
// int index = articlePaniers.indexOf(articleP);
//
// articlePaniers.set(index, articlePanier);
// IsArticleIdentiqueDansUserPanier = true;
//
// }
// }
//
// if (!IsArticleIdentiqueDansUserPanier) {
// articlePanier.setQuantite(qte);
//
// articlePaniers.add(articlePanier);
// }
//
// try
//
// {
// panierMetier.updateArticlePanier(articlePanier);
// messageSuccess = "Article ajouté avec succès au panier";
// } catch (Exception e1) {
//
// e1.printStackTrace();
// return "";
// }
//
// return "";
// }
public List<Article> getArticles() {
IArticleMetier articleMetier = new ArticleMetier();
List<Article> articles = new ArrayList<Article>();
try {
articles = articleMetier.getArticles();
} catch (Exception e) {
messageError = "Erreur technique ! Veuillez réessayer plus tard.\n" + e.getMessage();
e.printStackTrace();
}
return articles;
}
public String getMessageSuccess() {
return messageSuccess;
}
public void setMessageSuccess(String messageSuccess) {
this.messageSuccess = messageSuccess;
}
public String getMessageError() {
return messageError;
}
public void setMessageError(String messageError) {
this.messageError = messageError;
}
}
|
package pfe.bouygues.construction;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Ical {
private final Logger logger = LoggerFactory.getLogger(getClass());
private List<Event> elist = new ArrayList<Event>();
private String product;
private String organisation;
public Ical(String product, String organisation){
this.product = product;
this.organisation = organisation;
}
public void addEvent(Calendar dateBegin, Calendar dateEnd, String title, String description){
this.elist.add(new Event(dateBegin, dateEnd, title, description));
}
// public void print(Writer w) throws IOException{
// w.write("BEGIN:VCALENDAR\n");
// w.write("VERSION:2.0\n");
// w.write("CALSCALE:GREGORIAN\n");
// w.write("PRODID:-//" + this.organisation + "//NONSGML " + this.product + "//FR\n");
// for(int i = 0; i < this.elist.size(); i++)
// this.elist.get(i).print(w);
// w.write("END:VCALENDAR\n");
// }
public boolean write(){
StringBuilder dt = new StringBuilder();
dt.append("BEGIN:VCALENDAR\n");
dt.append("VERSION:2.0\n");
dt.append("CALSCALE:GREGORIAN\n");
dt.append("PRODID:-//" + this.organisation + "//NONSGML " + this.product + "//FR\n");
for(int i = 0; i < this.elist.size(); i++)
try {
dt.append(this.elist.get(i).getString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dt.append("END:VCALENDAR\n");
try{
Charset charset = Charset.forName("UTF-8");
CharsetEncoder encoder = charset.newEncoder();
File file = new File("fiches/calendar.ics");
System.out.println("fichier créé : "+file.createNewFile());
OutputStream fos = new FileOutputStream(file);
String st = dt.toString();
WritableByteChannel channel = Channels.newChannel(fos);
ByteBuffer bb = encoder.encode(CharBuffer.wrap(st));
// CAUTION: THE BUFFER MUST NOT BE FLIPPED ANYMORE.
// bb.flip();
channel.write(bb);
channel.close();
fos.close();
}catch(Exception e){
return false;
}
return true;
}
public static class Event{
private Calendar dateBegin;
private Calendar dateEnd;
private String title;
private String description;
public Event(Calendar dateBegin, Calendar dateEnd, String title, String description) {
Logger logger = LoggerFactory.getLogger(Event.class);
this.dateBegin = dateBegin;logger.debug("begin: "+this.dateBegin);
this.dateEnd = dateEnd;logger.debug("end: "+this.dateEnd);
this.title = title;
this.description = description;
}
public String getString() throws IOException
{
StringBuilder dt = new StringBuilder();
dt.append("BEGIN:VEVENT\n");
dt.append("UID:" + Math.random() + "@hubble\n");
dt.append("DTSTART:");
dt.append(new Integer(this.dateBegin.get(Calendar.YEAR)).toString());
String str = new Integer(this.dateBegin.get(Calendar.MONTH)+1).toString();
if(str.length() == 1)
str = "0" + str;
dt.append(str);
str = new Integer(this.dateBegin.get(Calendar.DAY_OF_MONTH)).toString();
if(str.length() == 1)
str = "0" + str;
dt.append(str);
dt.append("T120000Z\n");
dt.append("DTEND:");
dt.append(new Integer(this.dateEnd.get(Calendar.YEAR)).toString());
str = new Integer(this.dateEnd.get(Calendar.MONTH)+1).toString();
if(str.length() == 1)
str = "0" + str;
dt.append(str);
str = new Integer(this.dateEnd.get(Calendar.DAY_OF_MONTH)).toString();
if(str.length() == 1)
str = "0" + str;
dt.append(str);
dt.append("T130000Z\n");
dt.append("SUMMARY:" + this.title + "\n");
dt.append("DESCRIPTION:" + this.description + "\n");
dt.append("END:VEVENT\n");
return dt.toString();
}
// public void print(Writer w) throws IOException{
// w.write("BEGIN:VEVENT\n");
// w.write("UID:" + Math.random() + "@hubble\n");
// StringBuilder dt = new StringBuilder();
// dt.append("DTSTART:");
// dt.append(new Integer(this.dateBegin.get(Calendar.YEAR)).toString());
// String str = new Integer(this.dateBegin.get(Calendar.MONTH)).toString();
// if(str.length() == 1)
// str = "0" + str;
// dt.append(str);
// str = new Integer(this.dateBegin.get(Calendar.DAY_OF_MONTH)).toString();
// if(str.length() == 1)
// str = "0" + str;
// dt.append(str);
// dt.append("T120000Z\n");
// w.write(dt.toString());
// dt = new StringBuilder();
// dt.append("DTEND:");
// dt.append(new Integer(this.dateEnd.get(Calendar.YEAR)).toString());
// str = new Integer(this.dateEnd.get(Calendar.MONTH)).toString();
// if(str.length() == 1)
// str = "0" + str;
// dt.append(str);
// str = new Integer(this.dateEnd.get(Calendar.DAY_OF_MONTH)).toString();
// if(str.length() == 1)
// str = "0" + str;
// dt.append(str);
// dt.append("T130000Z\n");
// w.write(dt.toString());
// w.write("SUMMARY:" + this.title + "\n");
// w.write("DESCRIPTION:" + this.description + "\n");
// w.write("END:VEVENT\n");
// }
}
}
|
package com.base.crm.product.service;
import java.util.List;
import com.base.crm.product.entity.Product;
public interface ProductService {
int deleteByPrimaryKey(Long productId);
int insertSelective(Product record);
Product selectByPrimaryKey(Long productId);
int updateByPrimaryKeySelective(Product record);
Long selectPageTotalCount(Product record);
List<Product> selectPageByObjectForList(Product record);
List<Product> selectByObjectForList(Product object);
}
|
package com.tencent.mm.plugin.freewifi.ui;
import android.net.wifi.WifiInfo;
import android.os.Build.VERSION;
import com.tencent.mm.R;
import com.tencent.mm.ab.e;
import com.tencent.mm.ab.l;
import com.tencent.mm.plugin.freewifi.d.a;
import com.tencent.mm.plugin.freewifi.d.i;
import com.tencent.mm.plugin.freewifi.k;
import com.tencent.mm.plugin.freewifi.k$a;
import com.tencent.mm.plugin.freewifi.k.b;
import com.tencent.mm.plugin.freewifi.m;
import com.tencent.mm.plugin.freewifi.model.d;
import com.tencent.mm.plugin.freewifi.ui.b.2;
import com.tencent.mm.protocal.c.bdp;
import com.tencent.mm.protocal.c.xq;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
class b$1 implements e {
final /* synthetic */ b jmu;
b$1(b bVar) {
this.jmu = bVar;
}
public final void a(int i, int i2, String str, l lVar) {
k$a aOa = k.aOa();
aOa.bIQ = this.jmu.bIQ;
aOa.jid = m.E(this.jmu.intent);
aOa.jif = b.jio.jiQ;
aOa.jig = b.jio.name;
aOa.jie = m.G(this.jmu.intent);
aOa.bVU = this.jmu.bVU;
aOa.result = i2;
aOa.hKX = str;
aOa.aOc().b(this.jmu.intent, i2 != 0).aOb();
x.i("MicroMsg.FreeWifi.FreeWifiNetCheckUI", "sessionKey=%s, step=%d, method=FreeWifiConnector.getApInfo.callback, desc=net request [getApInfo] returns. errType=%d, errCode=%d, errMsg=%s", new Object[]{m.E(this.jmu.intent), Integer.valueOf(m.F(this.jmu.intent)), Integer.valueOf(i), Integer.valueOf(i2), str});
if (i == 0 && i2 == 0) {
b bVar = this.jmu;
if (lVar instanceof a) {
a aVar = (a) lVar;
bVar.intent.putExtra("ConstantsFreeWifi.FREE_WIFI_SHOULD_BIND_PHONE", aVar.aOU());
xq aOV = aVar.aOV();
if (aOV != null) {
x.i("MicroMsg.FreeWifi.FreeWifiNetCheckUI", "sessionKey=%s, step=%d, method=FreeWifiConnector.getApInfo.callback(openFrontPageByApInfo/getFrontPage), desc=net request [getapinfo] gets response. frontpageinfo: appid: %s, nickName: %s, userName: %s, headImgUrl: %s, welcomeMsg: %s, privacyDescriUrl: %s, timestamp=%s, sign=%s, HasMobile=%d", new Object[]{m.E(bVar.intent), Integer.valueOf(m.F(bVar.intent)), aOV.rbW, aOV.hcS, aOV.hbL, aOV.jPM, aOV.rDu, aOV.rDv, aOV.rhq, aOV.rsy, Integer.valueOf(aOV.qZg)});
bVar.intent.putExtra("free_wifi_appid", aOV.rbW);
bVar.intent.putExtra("free_wifi_head_img_url", aOV.jPM);
bVar.intent.putExtra("free_wifi_welcome_msg", aOV.rDu);
bVar.intent.putExtra("free_wifi_privacy_url", aOV.rDv);
bVar.intent.putExtra("free_wifi_app_nickname", aOV.hcS);
bVar.intent.putExtra("free_wifi_welcome_sub_title", aOV.rDw);
}
if (bVar.bVU != 2) {
bVar.activity.getIntent().putExtra("free_wifi_jump_to_main_ui", true);
}
bdp aOT = aVar.aOT();
if (aOT == null) {
x.e("MicroMsg.FreeWifi.FreeWifiNetCheckUI", "get qstring from server is null");
bVar.activity.finish();
aOa = k.aOa();
aOa.bIQ = bVar.bIQ;
aOa.jid = m.E(bVar.intent);
aOa.jif = b.jip.jiQ;
aOa.jig = b.jip.name;
aOa.jie = m.G(bVar.intent);
aOa.bVU = bVar.bVU;
aOa.result = -1;
aOa.hKX = "qstrInfo is null.";
aOa.aOc().b(bVar.intent, true).aOb();
return;
} else if (m.isEmpty(aOT.iwF)) {
x.e("MicroMsg.FreeWifi.FreeWifiNetCheckUI", "get qstrInfo.ssid from server is empty");
bVar.activity.finish();
aOa = k.aOa();
aOa.bIQ = bVar.bIQ;
aOa.jid = m.E(bVar.intent);
aOa.jif = b.jip.jiQ;
aOa.jig = b.jip.name;
aOa.jie = m.G(bVar.intent);
aOa.bVU = bVar.bVU;
aOa.result = -1;
aOa.hKX = "qstrInfo.Ssid is empty.";
aOa.aOc().b(bVar.intent, true).aOb();
return;
} else {
bVar.intent.putExtra("free_wifi_ssid", aOT.iwF);
x.i("MicroMsg.FreeWifi.FreeWifiNetCheckUI", "sessionKey=%s, step=%d, method=FreeWifiConnector.getApInfo.callback(openFrontPageByApInfo), desc=net request [getApInfo/getFrontPage] gets response. qstrInfo: prototype = %d, ssid : %s, pssword : %s", new Object[]{m.E(bVar.intent), Integer.valueOf(m.F(bVar.intent)), Integer.valueOf(aOT.sfQ), aOT.iwF, aOT.ryU});
String aOW = aVar.aOW();
String aOX = aVar.aOX();
bVar.intent.putExtra("free_wifi_openid", aOW);
bVar.intent.putExtra("free_wifi_tid", aOX);
bVar.intent.putExtra("ConstantsFreeWifi.FREE_WIFI_TIMESTAMP", aOV.rhq);
bVar.intent.putExtra("ConstantsFreeWifi.FREE_WIFI_SIGN", aOV.rsy);
x.i("MicroMsg.FreeWifi.FreeWifiNetCheckUI", "sessionKey=%s, step=%d, method=FreeWifiConnector.getApInfo.callback(openFrontPageByApInfo), desc=net request [getApInfo/getFrontPage] gets response. openId=%s, tid=%s", new Object[]{m.E(bVar.intent), Integer.valueOf(m.F(bVar.intent)), aOW, aOX});
bVar.intent.putExtra("free_wifi_protocol_type", aOT.sfQ);
if (aOT.sfQ == 10) {
if (bi.oW(aOT.iwF) || bi.oW(aOT.ryU)) {
x.e("MicroMsg.FreeWifi.FreeWifiNetCheckUI", "ssid or password is null");
bVar.activity.finish();
return;
}
bVar.intent.putExtra("ConstantsFreeWifi.FREE_WIFI_PROTOCOL_NUMBER", 4);
bVar.intent.putExtra("free_wifi_auth_type", 2);
bVar.intent.putExtra("free_wifi_passowrd", aOT.ryU);
bVar.intent.setClass(bVar.activity, FreeWifiFrontPageUI.class);
bVar.activity.startActivity(bVar.intent);
bVar.activity.finish();
bVar.activity.overridePendingTransition(R.a.slide_right_in, R.a.slide_left_out);
return;
} else if (aOT.sfQ == 11) {
if (bi.oW(aOT.iwF) || bi.oW(aOT.ryU)) {
x.e("MicroMsg.FreeWifi.FreeWifiNetCheckUI", "ssid or password is null");
bVar.activity.finish();
return;
}
bVar.intent.putExtra("free_wifi_auth_type", 2);
bVar.intent.putExtra("free_wifi_passowrd", aOT.ryU);
bVar.intent.setClass(bVar.activity, FreewifiActivateWeChatNoAuthStateUI.class);
bVar.activity.startActivity(bVar.intent);
bVar.activity.finish();
bVar.activity.overridePendingTransition(R.a.slide_right_in, R.a.slide_left_out);
return;
} else if (aOT.sfQ == 12) {
bVar.intent.putExtra("free_wifi_auth_type", 1);
bVar.intent.setClass(bVar.activity, FreeWifiActivateAuthStateUI.class);
bVar.activity.startActivity(bVar.intent);
bVar.activity.finish();
bVar.activity.overridePendingTransition(R.a.slide_right_in, R.a.slide_left_out);
return;
} else if (aOT.sfQ == 31) {
bVar.intent.putExtra("ConstantsFreeWifi.FREE_WIFI_PROTOCOL_NUMBER", 31);
x.i("MicroMsg.FreeWifi.FreeWifiNetCheckUI", "sessionKey=%s, step=%d, method=FreeWifiConnector.getApInfo.callback(openFrontPageByApInfo), desc=it goes into protocal 31 handle branch.", new Object[]{m.E(bVar.intent), Integer.valueOf(m.F(bVar.intent))});
String stringExtra = bVar.intent.getStringExtra("free_wifi_schema_ticket");
x.i("MicroMsg.FreeWifi.FreeWifiNetCheckUI", "sessionKey=%s, step=%d, method=FreeWifiConnector.getApInfo.callback(openFrontPageByApInfo), desc=it tries to get ticket. ticket=%s.", new Object[]{m.E(bVar.intent), Integer.valueOf(m.F(bVar.intent)), stringExtra});
if (bi.oW(stringExtra)) {
bVar.activity.finish();
aOa = k.aOa();
aOa.bIQ = bVar.bIQ;
aOa.jid = m.E(bVar.intent);
aOa.jif = b.jip.jiQ;
aOa.jig = b.jip.name;
aOa.bVU = bVar.bVU;
aOa.jie = m.G(bVar.intent);
aOa.result = -1;
aOa.hKX = "31 ticket is empty.";
aOa.aOc().b(bVar.intent, true).aOb();
return;
}
String str2 = aOT.iwF;
String str3 = aOV.rhq;
String str4 = aOV.rsy;
WifiInfo aOA = d.aOA();
if (aOA == null) {
x.i("MicroMsg.FreeWifi.FreeWifiNetCheckUI", "sessionKey=%s, step=%d, method=FreeWifiConnector.protocol31GetPortalApInfo, desc=it tries to get current connected wifi info but return null, so it fails to connect wifi. ", new Object[]{m.E(bVar.intent), Integer.valueOf(m.F(bVar.intent))});
bVar.Ci(bVar.activity.getString(R.l.free_wifi_errmsg_retry));
aOa = k.aOa();
aOa.bIQ = bVar.bIQ;
aOa.jid = m.E(bVar.intent);
aOa.jif = b.jip.jiQ;
aOa.jig = b.jip.name;
aOa.bVU = bVar.bVU;
aOa.jie = m.G(bVar.intent);
aOa.result = -1;
aOa.hKX = "wifiInfo is empty.";
aOa.aOc().b(bVar.intent, true).aOb();
return;
}
boolean BY = d.BY(str2);
String str5 = "MicroMsg.FreeWifi.FreeWifiNetCheckUI";
String str6 = "sessionKey=%s, step=%d, method=FreeWifiConnector.protocol31GetPortalApInfo, desc=it gets connected wifi info. wifiInfo=%s, is_current_connected_ssid_equals_target_ssid=%b";
Object[] objArr = new Object[4];
objArr[0] = m.E(bVar.intent);
objArr[1] = Integer.valueOf(m.F(bVar.intent));
objArr[2] = aOA == null ? "null" : aOA.toString();
objArr[3] = Boolean.valueOf(BY);
x.i(str5, str6, objArr);
str5 = m.BQ(aOA.getSSID());
str6 = aOA.getBSSID();
String macAddress = aOA.getMacAddress();
if (VERSION.SDK_INT > 22 && (macAddress == null || macAddress.equals("02:00:00:00:00:00"))) {
macAddress = m.aOf();
}
x.i("MicroMsg.FreeWifi.FreeWifiNetCheckUI", "sessionKey=%s, step=%d, method=FreeWifiConnector.protocol31GetPortalApInfo desc=it starts net request [GetPortalApInfo] for portal ap info. apKey=%s, apSsid=%s, apBssid=%s, mobileMac=%s, ticket=%s", new Object[]{m.E(bVar.intent), Integer.valueOf(m.F(bVar.intent)), bVar.bIQ, str5, str6, macAddress, stringExtra});
aOa = k.aOa();
aOa.bIQ = bVar.bIQ;
aOa.jid = m.E(bVar.intent);
aOa.jif = b.jip.jiQ;
aOa.jig = b.jip.name;
aOa.bVU = bVar.bVU;
aOa.jie = m.G(bVar.intent);
aOa.result = 0;
aOa.hKX = "";
aOa.aOc().b(bVar.intent, true).aOb();
aOa = k.aOa();
aOa.ssid = bVar.intent.getStringExtra("free_wifi_ssid");
aOa.bIQ = bVar.bIQ;
aOa.jic = bVar.intent.getStringExtra("free_wifi_appid");
aOa.jid = m.E(bVar.intent);
aOa.jie = m.G(bVar.intent);
aOa.jif = b.jiz.jiQ;
aOa.jig = b.jiz.name;
aOa.bVU = m.H(bVar.intent);
aOa.jie = m.G(bVar.intent);
aOa.aOc().b(bVar.intent, false).aOb();
new i(bVar.bIQ, str5, str6, macAddress, stringExtra, m.E(bVar.intent)).s(bVar.activity).b(new 2(bVar, aOW, aOX, str3, str4));
return;
} else if (aOT.sfQ == 32) {
bVar.intent.putExtra("ConstantsFreeWifi.FREE_WIFI_PROTOCOL_NUMBER", 32);
x.i("MicroMsg.FreeWifi.FreeWifiNetCheckUI", "sessionKey=%s, step=%d, method=FreeWifiConnector.getApInfo.callback(openFrontPageByApInfo), desc=it goes into protocal 32 handle branch.", new Object[]{m.E(bVar.intent), Integer.valueOf(m.F(bVar.intent))});
bVar.intent.setClass(bVar.activity, FreeWifiFrontPageUI.class);
bVar.activity.startActivity(bVar.intent);
bVar.activity.finish();
bVar.activity.overridePendingTransition(R.a.slide_right_in, R.a.slide_left_out);
return;
} else if (aOT.sfQ == 1) {
bVar.intent.putExtra("ConstantsFreeWifi.FREE_WIFI_PROTOCOL_NUMBER", 1);
bVar.intent.putExtra("free_wifi_auth_type", 1);
bVar.intent.setClass(bVar.activity, FreeWifiFrontPageUI.class);
bVar.activity.startActivity(bVar.intent);
bVar.activity.finish();
bVar.activity.overridePendingTransition(R.a.slide_right_in, R.a.slide_left_out);
return;
} else {
bVar.activity.finish();
bVar.Ci(bVar.activity.getString(R.l.free_wifi_errmsg_update_client));
return;
}
}
}
bVar.Ci(bVar.activity.getString(R.l.free_wifi_errmsg_retry));
} else if (m.cD(i, i2) && !m.isEmpty(str)) {
this.jmu.Ci(str + "(" + m.a(m.G(this.jmu.intent), b.jio, i2) + ")");
} else if (i2 == -30031) {
this.jmu.Ci(this.jmu.activity.getString(R.l.free_wifi_errmsg_ssid_not_match_3));
} else {
this.jmu.Ci(this.jmu.activity.getString(R.l.free_wifi_errmsg_retry) + "(" + String.format("%02d", new Object[]{Integer.valueOf(m.G(this.jmu.intent))}) + b.jio.jiQ + Math.abs(i2) + ")");
}
}
}
|
package com.rkrzmail.absensi.Activity;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import com.rkrzmail.absensi.APIService.APIClient2;
import com.rkrzmail.absensi.APIService.APIInterfacesRest;
import com.rkrzmail.absensi.APIService.AppUtil;
import com.rkrzmail.absensi.R;
import com.rkrzmail.absensi.model.Absen.PostAbsen;
import com.rkrzmail.absensi.model.Login.ModelLogin;
import com.rkrzmail.absensi.model.dataabsen.PostAbsensi;
import com.rkrzmail.absensi.model.param.ModelParam;
import com.rkrzmail.absensi.model.parameter.DataParameter;
import com.robin.locationgetter.EasyLocation;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import in.mayanknagwanshi.imagepicker.ImageSelectActivity;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.os.Environment.getExternalStoragePublicDirectory;
import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE;
import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO;
public class ActivityIzin extends AppCompatActivity implements LocationListener {
Button btnKirim;
ImageView imageView;
EditText txtKeterangan, txtlocation2;
Bitmap foto, bitmap;
ImageButton btnTakePicture;
Spinner spinnerShift;
String Gname, Gunit, Gbranch, Gposition, GNIK;
TextView txtlocation;
LocationManager locationManager;
String latitude, longitude, filePath;
private static final int REQUEST_LOCATION=1;
protected LocationListener locationListener;
double latitude2;
double longitude2;
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_izin);
txtlocation= findViewById(R.id.location);
txtlocation2= findViewById(R.id.location2);
txtlocation2.setText(latitude+","+longitude);
spinnerShift= findViewById(R.id.spinnershift);
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Gname = pref.getString("name", "name");
Gunit = pref.getString("unit", "unit");
Gbranch = pref.getString("branch", "branch");
Gposition = pref.getString("position", "position");
GNIK = pref.getString("nik", "nik");
btnTakePicture = findViewById(R.id.btnTakePicture);
btnKirim = findViewById(R.id.btnkirim);
imageView = findViewById(R.id.imageview);
txtKeterangan = findViewById(R.id.txtketerangan);
initSpinnerShift();
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
spinnerShift.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedShift= parent.getItemAtPosition(position).toString();
Toast.makeText(ActivityIzin.this , "kamu sedang masuk shift" + selectedShift, Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
if (Build.VERSION.SDK_INT>=23){
requestPermissions(new String[] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION}, 2);
}
locationManager= (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
onGPS();
} else {
//gps already exist
getLocation();
}
btnTakePicture.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
capturepic();
}
});
btnKirim.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(txtlocation2.getText().toString().equalsIgnoreCase("null,null")){
Toast.makeText(ActivityIzin.this, "silahkan nyalakan permission location", Toast.LENGTH_SHORT).show();
} else {
if (imageView.getDrawable() == null) {
Toast.makeText(ActivityIzin.this, "foto blm di isi", Toast.LENGTH_SHORT).show();
}
if (txtKeterangan.getText().toString().length() == 0) {
txtKeterangan.setError("keterangan belum di isi !");
}
if (imageView.getDrawable() == null && txtKeterangan.getText().toString().length() == 0) {
txtKeterangan.setError("keterangan belum di isi !");
Toast.makeText(ActivityIzin.this, "foto blm di isi", Toast.LENGTH_SHORT).show();
}
if (txtKeterangan.getText().toString().length() != 0 && imageView.getDrawable() != null) {
sendDataAbsen();
onBackPressed();
}
}
}
});
}
private void onGPS() {
final AlertDialog.Builder builder= new AlertDialog.Builder(this);
builder.setMessage("Enabled GPS").setCancelable(false).setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}).setNegativeButton("NO", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});//oke
final AlertDialog alertDialog=builder.create();
alertDialog.show();
}
public void getLocation(){
if(ActivityCompat.checkSelfPermission(ActivityIzin.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(ActivityIzin.this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
} else{
Location locationGPS= locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location locationNetwork= locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location locationPassive= locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
if(locationGPS != null){
double lat= locationGPS.getLatitude();
double longi = locationGPS.getLongitude();
latitude = String.valueOf(lat);
longitude = String.valueOf(longi);
txtlocation2.setText(latitude+","+longitude);
//txtlocation.setText("your location"+"\n"+"latitude"+latitude+"\n"+"longitude"+longitude);
} else if(locationPassive != null){
double lat= locationPassive.getLatitude();
double longi = locationPassive.getLongitude();
latitude = String.valueOf(lat);
longitude = String.valueOf(longi);
txtlocation2.setText(latitude+","+longitude);
// txtlocation.setText("your location"+"\n"+"latitude"+latitude+"\n"+"longitude"+longitude);
} else if(locationNetwork != null){
double lat= locationNetwork.getLatitude();
double longi = locationNetwork.getLongitude();
latitude = String.valueOf(lat);
longitude = String.valueOf(longi);
txtlocation2.setText(latitude+","+longitude);
// txtlocation.setText("your location"+"\n"+"latitude"+latitude+"\n"+"longitude"+longitude);
} else {
Toast.makeText(this, "Cant get your location", Toast.LENGTH_SHORT).show();
}
//try run
}
}
private void capturepic()
{
Intent intent = new Intent(this, ImageSelectActivity.class);
intent.putExtra(ImageSelectActivity.FLAG_COMPRESS, true);//default is true
intent.putExtra(ImageSelectActivity.FLAG_CAMERA, true);//default is true
intent.putExtra(ImageSelectActivity.FLAG_GALLERY, true);//default is true
startActivityForResult(intent, 1213);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1213 && resultCode == Activity.RESULT_OK) {
filePath = data.getStringExtra(ImageSelectActivity.RESULT_FILE_PATH);
Bitmap selectedImage = BitmapFactory.decodeFile(filePath);
imageView.setImageBitmap(selectedImage);
foto= bitmap;
}
}
// ini kan lu mau maksa user aktifin gPS NYA nah itu lu udh bikin fungsi nya, bukannya dipanggil lagi ya di atas nya , kaya sendData Absen ini kan udh lu bikin fungsi nya trus lu panggil di atas
//send post data with image
private void sendDataAbsen() {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
String now = formatter.format(new Date());
File foto = new File(filePath);
// File foto = createTempFile(bitmap);
// byte[] bImg1 = AppUtil.FiletoByteArray(foto);
RequestBody requestFile1 = RequestBody.create(MediaType.parse("image/jpeg"),foto);
MultipartBody.Part fotox = MultipartBody.Part.createFormData("foto", foto.getName() + ".jpg", requestFile1);
String lspinner= spinnerShift.getSelectedItem().toString();
String[] shift = lspinner.split(" ");
String spinner = shift[0];
APIInterfacesRest apiInterface = APIClient2.getClient().create(APIInterfacesRest.class);
Call<PostAbsen> postAdd = apiInterface.sendDataAbsen(
toRequestBody(AppUtil.replaceNull(GNIK)),
toRequestBody(AppUtil.replaceNull(Gname)),
toRequestBody(AppUtil.replaceNull(Gunit)),
toRequestBody(AppUtil.replaceNull(Gbranch)),
toRequestBody(AppUtil.replaceNull(Gposition)),
fotox,
toRequestBody(AppUtil.replaceNull(now)),
toRequestBody(AppUtil.replaceNull("IZIN")),
toRequestBody(AppUtil.replaceNull(latitude+","+longitude)),
toRequestBody(AppUtil.replaceNull(spinner)),
toRequestBody(AppUtil.replaceNull(" ")),
toRequestBody(AppUtil.replaceNull(" - ")),
toRequestBody(AppUtil.replaceNull(" - ")),
toRequestBody(AppUtil.replaceNull("0000-00-00 00:00:00")),
toRequestBody(AppUtil.replaceNull(now)),
toRequestBody(AppUtil.replaceNull(txtKeterangan.getText().toString()))
);
postAdd.enqueue(new Callback<PostAbsen>() {
@Override
public void onResponse(Call<PostAbsen> call, Response<PostAbsen> response) {
PostAbsen responServer = response.body();
if (responServer != null) {
Toast.makeText(ActivityIzin.this,responServer.getMessage(),Toast.LENGTH_LONG).show();
}
}
@Override
public void onFailure(Call<PostAbsen> call, Throwable t) {
Toast.makeText(ActivityIzin.this, "Maaf koneksi bermasalah", Toast.LENGTH_LONG).show();
call.cancel();
}
});
}
//change string to requestbody
public RequestBody toRequestBody(String value) {
if (value == null) {
value = "";
}
RequestBody body = RequestBody.create(MediaType.parse("text/plain"), value);
return body;
}
public void onBackPressed() {
finish();
}
private void initSpinnerShift(){
final APIInterfacesRest apiInterface = APIClient2.getClient().create(APIInterfacesRest.class);
final Call<ModelParam> data = apiInterface.getParameter();
data.enqueue(new Callback<ModelParam>() {
@Override
public void onResponse(Call<ModelParam> call, Response<ModelParam> response) {
if (response.isSuccessful()) {
ModelParam listdata = response.body();
List<String> listSpinner = new ArrayList<String>();
for (int i = 0; i < listdata.getData().size(); i++){
if(Gunit.equals(listdata.getData().get(i).getUnit())){
String name= listdata.getData().get(i).getShiftName();
String mulai= listdata.getData().get(i).getJamMulai();
String selesai= listdata.getData().get(i).getJamSelesai();
//listSpinner.add(name);
listSpinner.add(name+" " +mulai+ " "+ selesai);
//listSpinner.add(selesai);
}
}
listSpinner.add(0, "- SELECT TYPE -");
listSpinner.add(1, "Non-Shift");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ActivityIzin.this,
android.R.layout.simple_spinner_item, listSpinner);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerShift.setAdapter(adapter);
} else {
Toast.makeText(ActivityIzin.this, "Gagal mengambil data shift", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<ModelParam> call, Throwable t) {
Toast.makeText(ActivityIzin.this, "Koneksi internet bermasalah", Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onLocationChanged(Location location) {
txtlocation = (TextView) findViewById(R.id.location);
latitude2 =location.getLatitude();
longitude2=location.getLongitude();
// txtlocation.setText("Latitude:" + latitude2 + ", Longitude:" + longitude2);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","disable");
}
@Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
@Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","status");
}
}
|
package cn.gzcc.feibao.security;
import cn.gzcc.feibao.dao.UserJpa;
import cn.gzcc.feibao.entity.User;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
@Service
public class UserDetailsServicelmpl implements UserDetailsService {
protected final Log logger = LogFactory.getLog(this.getClass());
@Autowired
private UserJpa userJpa;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String s1 = request.getParameter("inline-radios");
// String n1=request.getParameter("username");
HttpSession session = request.getSession();
session.setAttribute("role", s1);
// session.setAttribute("loginname",s1);
List<User> users = userJpa.findUserByName(s);
UserDetails user = null;
if (users.size() == 0) {
this.logger.debug("Query returned no results for user '" + s + "'");
throw new UsernameNotFoundException("Username not found");
} else {
List<GrantedAuthority> dbAuths = new ArrayList();
user = new org.springframework.security.core.userdetails.User(s, users.get(0).getPassword(), dbAuths);
}
return user;
}
}
|
package MusicManager;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class M3UReader {
private static final String FILE_NOT_EXISTS = "\tFile not exists.";
public File m3uFile;
public List<String> m3uContent = new ArrayList<>();
public List<File> mp3FileList = new ArrayList<>();
public M3UReader(File m3uFile) {
this.m3uFile = m3uFile;
}
public void setM3uFile(File m3uFile) {
this.m3uFile = m3uFile;
}
public List<File> getMp3FileList() {
return mp3FileList;
}
private void readAllLinesFromM3u() throws IOException {
String m3uLines;
BufferedReader br = new BufferedReader(new FileReader(m3uFile));
while ((m3uLines = br.readLine()) != null) {
m3uContent.add(m3uLines);
}
br.close();
}
public List<String> returnFileList() {
try {
this.readAllLinesFromM3u();
} catch (IOException e) {
e.printStackTrace();
}
List<String> formattedM3u = new ArrayList<>();
String concatenated;
for (String m3uLine : m3uContent) {
if (!m3uLine.startsWith("#")) {
if (m3uLine.matches(".[^:]")) {
concatenated = m3uFile.getParent() + System.lineSeparator() + m3uLine;
if (!checkIfFileExists(concatenated)){
mp3FileList.add(new File(concatenated));
concatenated += FILE_NOT_EXISTS;}
else {
mp3FileList.add(new File(concatenated));
}
} else {
concatenated = m3uLine;
if (!checkIfFileExists(concatenated)){
mp3FileList.add(new File(concatenated));
concatenated += FILE_NOT_EXISTS;}
else {
mp3FileList.add(new File(concatenated));
}
}
formattedM3u.add(concatenated);
}
}
return formattedM3u;
}
private boolean checkIfFileExists(String path) {
File file = new File(path);
return file.exists();
}
}
|
package com.vilio.fms.commonMapper.dao;
import com.vilio.fms.commonMapper.pojo.FmsFileLoad;
import java.util.List;
/**
* Created by dell on 2017/5/17.
*/
public interface FmsFileLoadMapper {
FmsFileLoad selectByPrimaryKey(Integer id);
FmsFileLoad queryBySerialNo(String serialNo);
int saveFileLoad(FmsFileLoad fmsFileLoad);
int modifyFileLoadUrl(FmsFileLoad fmsFileLoad);
}
|
package com.liangtengyu.version2;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: lty
* @Date: 2021/2/25 09:52
*/
public class HandlerChainForCard {
List<Handler> handlers = new ArrayList<>();
public void setHandler(Handler handler) {
handlers.add(handler);
}
public void handle(){
for (Handler handler : handlers) {
boolean b = handler.doHandle();
if (b) {
break;
}
}
}
}
|
package zm.gov.moh.core.repository.database.dao.derived;
import java.util.List;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Query;
import zm.gov.moh.core.repository.database.entity.derived.ConceptAnswerName;
@Dao
public interface ConceptAnswerNameDao {
//get by concept id
@Query("SELECT concept_answer_id,concept_answer.concept_id,answer_concept,name,sort_weight FROM concept_answer JOIN concept_name ON concept_name.concept_id = concept_answer.answer_concept WHERE concept_answer.concept_id = :id AND concept_name.locale_preferred = 1 ORDER BY sort_weight ASC")
LiveData<List<ConceptAnswerName>> getByConceptId(long id);
}
|
/*
* 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 dao;
import factory.ConnectionFactory;
import gui.Main;
import model.Cliente;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComboBox;
/**
*
* @author Luucx7
*/
public class ClienteDAO {
public static Connection connection;
public int CPF;
public String nome;
public int RG;
public String celular;
public String telefone;
public String email;
public String endereco;
public String cidade;
public String estado;
public String nascimento;
public ClienteDAO() {
ClienteDAO.connection=ConnectionFactory.getConnection();
}
public static void ClienteBusca(JComboBox jCB) {
String sql = "SELECT * FROM clientes";
ResultSet rs = null;
try {
try (PreparedStatement stmt = ConnectionFactory.getConnection().prepareStatement(sql)) {
rs = stmt.executeQuery(sql);
while (rs.next()) {
jCB.addItem(rs.getString(2)+" - "+rs.getString(1));
}
}
} catch (SQLException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static Cliente Busca(String CPF) {
Cliente cliente = new Cliente();
String sql = "SELECT * FROM clientes WHERE CPF='"+CPF+"'";
ResultSet rs = null;
try {
PreparedStatement stmt = ConnectionFactory.getConnection().prepareStatement(sql);
rs = stmt.executeQuery(sql);
while (rs.next()) {
cliente.setCPF(rs.getString(1));
cliente.setNome(rs.getString(2));
cliente.setRG(rs.getString(3));
cliente.setCelular(rs.getString(4));
cliente.setTelefone(rs.getString(5));
cliente.setEmail(rs.getString(6));
cliente.setEndereco(rs.getString(7));
cliente.setBairro(rs.getString(8));
cliente.setCidade(rs.getString(9));
cliente.setEstado(rs.getString(10));
cliente.setNascimento(rs.getDate(11));
}
} catch (SQLException ex) {
Logger.getLogger(ClienteDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return cliente;
}
public void add(Cliente cliente) {
String sql = "INSERT INTO clientes(CPF,Nome,RG,Celular,Telefone,Email,Endereco,Bairro,Cidade,Estado,Nascimento) VALUES(?,?,?,?,?,?,?,?,?,?,?)";
try {
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, cliente.getCPF());
stmt.setString(2, cliente.getNome());
stmt.setString(3, cliente.getRG());
stmt.setString(4, cliente.getCelular());
stmt.setString(5, cliente.getTelefone());
stmt.setString(6, cliente.getEmail());
stmt.setString(7, cliente.getEndereco());
stmt.setString(8, cliente.getBairro());
stmt.setString(9, cliente.getCidade());
stmt.setString(10, cliente.getEstado());
stmt.setDate(11, cliente.getNascimento());
stmt.execute();
stmt.close();
} catch (SQLException u) {
throw new RuntimeException(u);
} finally {
ConnectionFactory.closeConnection(connection);
}
}
public void delete(Cliente cliente) {
String sql = "Delete from clientes where nome=?;";
try {
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, cliente.getNome());
stmt.execute();
stmt.close();
} catch (SQLException u) {
throw new RuntimeException(u);
} finally {
ConnectionFactory.closeConnection(connection);
}
}
public void changeByCPF(Cliente cliente) {
try {
try (PreparedStatement stmt = connection.prepareStatement("Update clientes Set Nome = ?, RG=?, Celular = ?, Telefone = ?, Email = ?, Endereco = ?, Bairro=?, Cidade=?, Estado=?, Nascimento = ? where CPF = ?");) {
System.err.println(cliente.getCPF());
stmt.setString(1, cliente.getNome());
stmt.setString(2, cliente.getRG());
stmt.setString(3, cliente.getCelular());
stmt.setString(4, cliente.getTelefone());
stmt.setString(5, cliente.getEmail());
stmt.setString(6, cliente.getEndereco());
stmt.setString(7, cliente.getBairro());
stmt.setString(8, cliente.getCidade());
stmt.setString(9, cliente.getEstado());
stmt.setDate(10, cliente.getNascimento());
stmt.setString(11, cliente.getCPF());
stmt.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(ClienteDAO.class.getName()).log(Level.SEVERE, null, ex);
}
} finally {
ConnectionFactory.closeConnection(connection);
}
}
public void changeByNome(Cliente cliente) {
try {
try (PreparedStatement stmt = connection.prepareStatement("Update clientes RG=?, Celular = ?, Telefone = ?, Email = ?, Endereco = ?, Bairro=?, Cidade=?, Estado=?, Nascimento = ? where CPF = ?");) {
stmt.setString(1, cliente.getRG());
stmt.setString(2, cliente.getCelular());
stmt.setString(3, cliente.getTelefone());
stmt.setString(4, cliente.getEmail());
stmt.setString(5, cliente.getEndereco());
stmt.setString(6, cliente.getBairro());
stmt.setString(7, cliente.getCidade());
stmt.setString(8, cliente.getEstado());
stmt.setDate(9, cliente.getNascimento());
stmt.setString(10, cliente.getNome());
stmt.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(ClienteDAO.class.getName()).log(Level.SEVERE, null, ex);
}
} finally {
ConnectionFactory.closeConnection(connection);
}
}
}
|
package Naveen;
import java.util.Scanner;
public class Feedback {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner read = new Scanner(System.in);
int n = read.nextInt();
double total=0;
Customer Cust[] = new Customer[n];
for(int i=0; i<n; ++i)
{
Cust[i]=new Customer();
Cust[i].getters();
}
for(int i=0; i<n; ++i)
Cust[i].setters();
for(int i=0; i<n; ++i)
total+=Cust[i].feedbackRating;
System.out.println("The average feedback rating is:"+total/n+" out of 5");
read.close();
}
}
|
package interviewbit.linkedlist;
public class Add2NumberList {
public ListNode addTwoNumbers(ListNode a, ListNode b) {
if (a == null)
return b;
if (b == null)
return a;
int carry = 0;
ListNode sum = null, sumhead = null, temp = null, ahead = a, bhead = b;
int s = ahead.val + bhead.val + carry;
carry = 0;
if (s > 9) {
carry = s / 10;
s = s % 10;
}
sum = new ListNode(s);
ahead = ahead.next;
bhead = bhead.next;
sumhead = sum;
while (ahead != null && bhead != null) {
s = ahead.val + bhead.val + carry;
carry = 0;
if (s > 9) {
carry = s / 10;
s = s % 10;
}
temp = new ListNode(s);
sumhead.next = temp;
ahead = ahead.next;
bhead = bhead.next;
sumhead = sumhead.next;
}
while (ahead != null) {
s = ahead.val + carry;
carry = 0;
if (s > 9) {
carry = s / 10;
s = s % 10;
}
temp = new ListNode(s);
sumhead.next = temp;
ahead = ahead.next;
sumhead = sumhead.next;
}
while (bhead != null) {
s = bhead.val + carry;
carry = 0;
if (s > 9) {
carry = s / 10;
s = s % 10;
}
temp = new ListNode(s);
sumhead.next = temp;
bhead = bhead.next;
sumhead = sumhead.next;
}
if(carry>0){
temp = new ListNode(carry);
carry = 0;
sumhead.next = temp;
sumhead = sumhead.next;
}
ListNode sumreverse = reverseList(sum);
while(sumreverse!=null){
if(sumreverse.val!=0){
break;
}else{
sumreverse=sumreverse.next;
}
}
sum = reverseList(sumreverse);
return sum;
}
private ListNode reverseList(ListNode z) {
if (z == null)
return z;
ListNode temp, node, a = z;
temp = new ListNode(a.val);
a = a.next;
while (a != null) {
node = new ListNode(a.val);
node.next = temp;
temp = node;
a = a.next;
}
return temp;
}
}
|
package com.douane.controler;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
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.douane.entities.BaeDpw;
import com.douane.entities.Deficit;
import com.douane.entities.Message;
import com.douane.repository.DeficitRepository;
import com.douane.repository.MessageRepository;
import com.douane.securite.config.JwtTokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import springfox.documentation.annotations.ApiIgnore;
@RestController
@RequestMapping("/api/v1/deficit")
@Api(value="Deficit end-point" , description = "Operations pertaining to deficit" )
@ApiIgnore
public class DeficitController {
@Autowired
private DeficitRepository deficitRepository ;
@Autowired
private MessageRepository messageRepository;
@Autowired
private JwtTokenUtil jwtTokenUtil;
private String title = "Deficit" ;
private Message<Deficit> message = new Message<Deficit>() ;
@PreAuthorize("hasRole('admin') or hasRole('dpworld') and hasRole('epal')" )
@ApiOperation(value = "View a list of available BAE ", response = BaeDpw.class)
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Successfully retrieved list"),
@ApiResponse(code = 401, message = "You are not authorized to view the resource"),
@ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"),
@ApiResponse(code = 404, message = "The resource you were trying to reach is not found")
}
)
@GetMapping(path = "/getdata")
public Message<Deficit> findNomatkedData () {
Long start =(Long) deficitRepository.findStartEndId().get(0).get("start") ;
Long end = (Long) deficitRepository.findStartEndId().get(0).get("end") ;
message.setId(this.title+"-"+start+"-"+end) ;
message.setCount(deficitRepository.getCount());
message.setStart_id(start);
message.setEnd_id(end);
message.setDescription("manifest liste ");
message.setContant( deficitRepository.getDataNoMarked());
return message;
}
@PreAuthorize("hasRole('admin') or hasRole('dpworld') and hasRole('epal')" )
@GetMapping(path = "/getalldata")
public List<Deficit> findAllData(){
return deficitRepository.findAll() ;
}
@GetMapping(path = "/getdata/{id}")
public Optional<Deficit> getDataById(@PathVariable(name = "id") long id) {
return deficitRepository.findById(id) ;
}
@DeleteMapping(path = "/deletebyid/{id}")
public void removebyId(@PathVariable(name = "id") long id) {
deficitRepository.deleteById(id);
System.out.println("Record has been deleted with the id: " + id);
}
@PostMapping(path = "/save", produces = "application/json")
public void createData(@RequestBody Deficit data) {
deficitRepository.save(data);
System.out.println(" data has been saved successfully: " + data);
}
@PostMapping(path = "/update", produces = "application/json")
public void updateData(@RequestBody Deficit data) {
if (deficitRepository.existsById(data.getId())) {
deficitRepository.save(data);
System.out.println("Data has been updated successfully :" + data);
} else {
System.out.println("Record not exists with the Id: " + data.getId());
}
}
@PreAuthorize("hasRole('admin') or hasRole('dpworld') and hasRole('epal')" )
@PostMapping(path = "/market/{id}", produces = "application/json")
public void marketData(@PathVariable(name = "id") Long id ) {
if (deficitRepository.existsById(id)) {
Deficit data = deficitRepository.findById(id).get() ;
data.setFlag(true);
data.setDateMarkage(new Date());
deficitRepository.save(data);
System.out.println("Data has been updated successfully :" + data);
} else {
System.out.println("Record not exists with the Id: " + id);
}
}
@PreAuthorize("hasRole('admin') or hasRole('dpworld') and hasRole('epal')" )
@PostMapping(path = "/marked/{start}/{end}", produces = "application/json")
public void markedlist(@PathVariable(name="start") Long start ,@PathVariable(name="end") Long end ) {
try {
System.out.println(start +" "+ end);
deficitRepository.setMareked(start, end);
System.out.println("Data has been marked successfully :");
} catch (Exception e) {
System.out.println("Record not exists");
System.err.println(e.getMessage());
}
}
@GetMapping(path = "/getcount")
public int getcount () {
return deficitRepository.getCount() ;
}
@PreAuthorize("hasRole('admin')")
@ApiOperation(value = "get a collection items whene id between two ids ")
@PostMapping(path = "/getdata/{start}/{end}", produces = "application/json")
public List<Deficit> getDatabetween(@PathVariable(name = "start") long start, @PathVariable(name = "end") long end , HttpServletRequest request) {
try {
return deficitRepository.getDataBetweenIs(start, end) ;
} catch (Exception e) {
System.out.println(e);
return null ;
}
}
}
|
package com.yixin.kepler.common.enums;
/**
* 微众银行产品结构枚举类
* @author YixinCapital -- chenjiacheng
* 2018年07月09日 17:19
**/
public enum WBPsCodeEnum {
NEW_CAR_DISCOUNT("PS000801","新车贴息"),
NEW_CAR_NOT_DICOUNT("PS000802","新车不贴息"),
USED_CAR_NOT_DISCOUNT("PS000803","二手车不贴息")
;
private String value;
private String name;
WBPsCodeEnum(String value, String name) {
this.value = value;
this.name = name;
}
public String getValue() {
return value;
}
public String getName() {
return name;
}
}
|
public class recursiveFunction {
public static void main (String[] args) {
counter(10);
System.out.println("//////////");
System.out.println(factor(5));
}
public static void counter (int n) {
System.out.println(n);
if (n - 1 >= 0) {
counter(n - 1);
}
}
public static int factor(int n) {
if (n == 1) {
return 1;
} else {
return n * factor(n-1);
}
}
// write a recursive function which return the sum numbers between 1 and n
}
|
package com.phone4s.www.service;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import com.phone4s.www.model.RepairBussiness;
public class RepairBussinessService {
public DriverManagerDataSource dataSource = null;
public DriverManagerDataSource getDataSource() {
return dataSource;
}
public void setDataSource(DriverManagerDataSource dataSource) {
this.dataSource = dataSource;
}
public List<RepairBussiness> getTopRepairBussiness() {
JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSource);
List<RepairBussiness> results = jdbcTemplate.query(
"select * from t_phone4s_repair_bussiness",
new RowMapper<RepairBussiness>() {
@Override
public RepairBussiness mapRow(ResultSet rs, int rowNum) throws SQLException {
return new RepairBussiness(rs.getInt("id"), rs.getString("name"), rs.getString("description"), rs.getString("logo"), rs.getString("spread_image"), rs.getString("credit"), null, null,rs.getString("longitude"),rs.getString("latitude"));
}
});
return results;
}
}
|
package org.choco;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@SpringBootApplication
public class ChocoApplication extends WebMvcConfigurerAdapter {
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false);
}
public static void main(String[] args) {
SpringApplication.run(ChocoApplication.class, args);
}
}
|
package Lab11.Zad3;
public class StateFailedAuthorization implements State{
private Authorization authorization;
public StateFailedAuthorization(Authorization authorization){
this.authorization = authorization;
}
@Override
public void checkAuthorization(String login, String password) {
System.out.println("Sorry, wrong login or password :(");
}
}
|
package exam.app.vo;
/**
* @author PC-01
* DB 테이블에 있는 컬럼을 기준으로 데이터를 객체화한 클래스
* <p>
* DB테이블의 컬럼이 이 클래스의 멤버 변수가 된다.<br>
* DB테이블의 컬럼과 클래스의 멤버변수를 매핑하는 역할을 수행한다. <br>
* </p>
*/
public class AppVO {
private String name;
private int Kor;
private int Math;
private int Eng;
public AppVO() {
super();
}
public AppVO(String name, int kor, int math, int eng) {
super();
this.name = name;
this.Kor = kor;
this.Math = math;
this.Eng = eng;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getKor() {
return Kor;
}
public void setKor(int kor) {
Kor = kor;
}
public int getMath() {
return Math;
}
public void setMath(int math) {
Math = math;
}
public int getEng() {
return Eng;
}
public void setEng(int eng) {
Eng = eng;
}
}
|
package Tomas;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//Write a program that prompts the user to enter two points (x1, y1) and (x2, y2) and displays the
//distance between them. The formula for computing the distance is √(x2 − x1)2 + (y2 − y1)2. Note
//that you can use Math.pow(a, 0.5) or Math.sqrt(a) to compute √a.
Scanner myScanner = new Scanner(System.in);
System.out.println("Enter x1");
double x1 = myScanner.nextDouble();
System.out.println("Enter x2");
double x2 = myScanner.nextDouble();
System.out.println("Enter y1");
double y1 = myScanner.nextDouble();
System.out.println("Enter y2");
double y2 = myScanner.nextDouble();
System.out.println("The distance between the points is: " + Math.pow(Math.pow((x2-x1),2)+Math.pow((y2-y1),2),0.5));
myScanner.close();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.