text
stringlengths
10
2.72M
/* * 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 ejercicios.manejodearquivos; import java.io.File; import java.util.Scanner; /** * * @author manuel */ public class BorrarArchivosSegunTamaño { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here System.out.println("Introduce el directorio donde quieres borrar los archivos con mas de 1MB"); Scanner sc = new Scanner(System.in); String ruta = sc.nextLine(); File directorio = new File(ruta); if(directorio.exists()){ File[] ficheros = directorio.listFiles(); for(File fichero:ficheros){ if(fichero.isFile()){ if(fichero.length()>10){ fichero.delete(); } } } }else{ System.err.println("El directorio no existe"); } } }
package com.yanovski.load_balancer.models; public enum ModificationType { ADDED, DELETED, DELETED_ALL }
public class Part2 { public String findSimpleGene(String dna, String startCodon, String stopCodon) { //start codon ATG //end codon TAA int startIndex = dna.indexOf(startCodon); int stopIndex = dna.indexOf(stopCodon, startIndex)+3; if( Character.isUpperCase(dna.charAt(0)) ) { //charAt() method returns the character at the specified index in the string startCodon = startCodon.toLowerCase(); stopCodon = stopCodon.toLowerCase(); } else { startCodon = startCodon.toUpperCase(); stopCodon = stopCodon.toUpperCase(); } if (startIndex == -1) { //no ATG return ""; } if (stopIndex == -1) { //no TAA return ""; } if((stopIndex-startIndex) % 3 == 0) { return dna.substring(startIndex,stopIndex); } else { return ""; } } public void testSimpleGene(){ String dna1,dna2,dna3,dna4,dna5; dna1 = "AATAGATTGATTAA"; //no ATG dna2 = "CGATGGTTTG"; //no TAA dna3 = "TAGTCGGTTCGAATTG"; //no ATG or TAA dna4 = "ATCATGCGGTGCGCATAAGGT"; //ATG , TAA and the substring between them is a multiple of 3 (a gene) dna5 = "cgatgcgtatgcgtaa"; //ATG, TAA and the substring between them is not a multiple of //display all the dna strings declared System.out.println("1: DNA Strand is " +dna1); System.out.println("2: DNA Strand is " +dna2); System.out.println("3: DNA Strand is " +dna3); System.out.println("4: DNA Strand is " +dna4); System.out.println("5: DNA Strand is " +dna5); String gene1,gene2,gene3,gene4,gene5; //display the genes if they exist gene1=findSimpleGene(dna1,"ATG", "TAA"); System.out.println("The gene number 1 is "+gene1); gene2=findSimpleGene(dna2, "ATG", "TAA"); System.out.println("The gene number 2 is "+gene2); gene3=findSimpleGene(dna3, "ATG", "TAA"); System.out.println("The gene number 3 is "+gene3); gene4=findSimpleGene(dna4, "ATG", "TAA"); System.out.println("The gene number 4 is "+gene4); gene5=findSimpleGene(dna5, "ATG", "TAA"); System.out.println("The gene number 5 is "+gene5); } public static void main (String[] args) { Part2 dna = new Part2(); dna.testSimpleGene(); } }
public class Apartment { private int rooms; private int squareMeters; private int pricePerSquareMeter; public Apartment(int rooms, int squareMeters, int pricePerSquareMeter) { this.rooms = rooms; this.squareMeters = squareMeters; this.pricePerSquareMeter = pricePerSquareMeter; } public boolean larger(Apartment otherAppartment) { return this.squareMeters > otherAppartment.squareMeters; } public int priceDifference(Apartment otherApartment) { return Math.abs(squareMeters * pricePerSquareMeter - otherApartment.squareMeters * otherApartment.pricePerSquareMeter); } public boolean moreExpensiveThan(Apartment otherApartment) { return squareMeters * pricePerSquareMeter > otherApartment.squareMeters * otherApartment.pricePerSquareMeter; } }
import java.util.ArrayList; public interface Observer { public void update(ArrayList<SoundClip> clips); }
package com.eshop.domain; import com.fasterxml.jackson.annotation.JsonBackReference; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.io.Serializable; import java.util.Objects; /** * A bundle of product parameteres. */ @Entity @Table(name = "parameters") @Data @NoArgsConstructor public class ProductParameteres implements Serializable { @Id @GeneratedValue private Integer id; private String colour; private String brand; private int weight; private String operatingSystem; @OneToOne(mappedBy = "productParameteres") @JsonBackReference private Product product; public ProductParameteres(String colour, String brand, int weight, String operatingSystem) { this.colour = colour; this.brand = brand; this.weight = weight; this.operatingSystem = operatingSystem; } @Override public String toString() { return "ProductParameteres{" + "id=" + id + '}'; } @Override public int hashCode() { return Objects.hash(id); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ProductParameteres)) return false; ProductParameteres that = (ProductParameteres) o; return id.equals(that.id); } }
package org.giddap.dreamfactory.leetcode.blogs; /** * */ public class Blog201004SearchingElementInRotatedArray { }
package com.baizhi; import com.baizhi.dao.UserDao; import com.baizhi.entity.User; import com.baizhi.service.UserService; import org.apache.jasper.tagplugins.jstl.core.ForEach; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; @RunWith(SpringRunner.class) @SpringBootTest public class HomeworkApplicationTests { @Autowired private UserDao userDao; @Autowired private UserService userService; @Test public void contextLoads() { /*List<User> list = userDao.selectAll(); for (User user : list) { System.out.println(user); }*/ List<User> list = userService.selectAll(); for (User user : list) { System.out.println(user); } } }
package com.esum.appcommon.resource.message; import java.text.MessageFormat; import java.util.Collection; import java.util.HashMap; import java.util.Locale; import java.util.ResourceBundle; import javax.servlet.http.HttpServletRequest; import com.esum.appcommon.resource.ResourceManager; public class AcubeResource { private static HashMap bundleCache; private static LocaleConfig localeConfig; static { init(); } private AcubeResource() {}; public static void init() { init(ResourceManager.ResoureBundleFilePath); } public static void init(String configFile) { bundleCache = new HashMap(); localeConfig = new LocaleConfig(configFile); } public static MessageBundle getMessageBundle(String localeCode, String resourceCode) { LocaleConfigVO vo = localeConfig.getLocaleConfig(localeCode); Locale locale = new Locale(vo.getLanguage(), vo.getCountry()); return getMessageBundle(locale, resourceCode); } public static MessageBundle getMessageBundle(HttpServletRequest request, String resourceCode) { Locale locale = getLocale(request); return getMessageBundle(locale, resourceCode); } public static MessageBundle getMessageBundle(Locale locale, String resourceCode) { MessageBundle bundle = null; try { String resourceName = localeConfig.getResourceName(resourceCode); String key = resourceName + "_" + locale; bundle = (MessageBundle) bundleCache.get(key); if (bundle != null) { return bundle; } //System.out.println("new resource-bundle : " + key); bundle = new MessageBundle(); ResourceBundle resBundle = //ResourceBundle.getBundle(resourceName, locale); ReloadablePropertyResourceBundle.getResourceBundle(resourceName, locale); bundle.setBundle(resBundle); bundleCache.put(key, bundle); } catch (Exception e) { e.printStackTrace(); } return bundle; } public static String getMessage(HttpServletRequest request, String strResourceName, String key) { return getMessage(getLocale(request), strResourceName, key); } public static String getMessage(HttpServletRequest request, String strResourceName, String key, Object[] params) { return getMessage(getLocale(request), strResourceName, key, params); } public static String getMessage(HttpServletRequest request, String strResourceName, String key, Object param0) { return getMessage(getLocale(request), strResourceName, key, param0); } public static String getMessage(HttpServletRequest request, String strResourceName, String key, Object param0, Object param1) { return getMessage(getLocale(request), strResourceName, key, param0, param1); } public static String getMessage(HttpServletRequest request, String strResourceName, String key, Object param0, Object param1, Object param2) { return getMessage(getLocale(request), strResourceName, key, param0, param1, param2); } public static String getMessage(HttpServletRequest request, String strResourceName, String key, Object param0, Object param1, Object param2, Object param3) { return getMessage(getLocale(request), strResourceName, key, param0, param1, param2, param3); } public static String getMessage(Locale locale, String strResourceName, String key) { MessageBundle bundle = null; try { String resourceName = localeConfig.getResourceName(strResourceName); String resourceKey = resourceName + "_" + locale; bundle = (MessageBundle) bundleCache.get(resourceKey); if (bundle != null) { return bundle.getString(key); } bundle = new MessageBundle(); ResourceBundle resBundle = ReloadablePropertyResourceBundle.getResourceBundle(resourceName, locale); bundle.setBundle(resBundle); bundleCache.put(key, bundle); } catch (Exception e) { e.printStackTrace(); } return bundle.getString(key); } public static String getMessage(Locale locale, String strResourceName, String key, Object[] params) { MessageBundle bundle = null; try { String resourceName = localeConfig.getResourceName(strResourceName); String resourceKey = resourceName + "_" + locale; bundle = (MessageBundle) bundleCache.get(resourceKey); if (bundle != null) { return MessageFormat.format(bundle.getString(key), params); } bundle = new MessageBundle(); ResourceBundle resBundle = ReloadablePropertyResourceBundle.getResourceBundle(resourceName, locale); bundle.setBundle(resBundle); bundleCache.put(key, bundle); } catch (Exception e) { e.printStackTrace(); } return MessageFormat.format(bundle.getString(key), params); } public static String getMessage(Locale locale, String strResourceName, String key, Object param0) { MessageBundle bundle = null; Object[] params = {param0}; try { String resourceName = localeConfig.getResourceName(strResourceName); String resourceKey = resourceName + "_" + locale; bundle = (MessageBundle) bundleCache.get(resourceKey); if (bundle != null) { return MessageFormat.format(bundle.getString(key), params); } bundle = new MessageBundle(); ResourceBundle resBundle = ReloadablePropertyResourceBundle.getResourceBundle(resourceName, locale); bundle.setBundle(resBundle); bundleCache.put(key, bundle); } catch (Exception e) { e.printStackTrace(); } return MessageFormat.format(bundle.getString(key), params); } public static String getMessage(Locale locale, String strResourceName, String key, Object param0, Object param1) { MessageBundle bundle = null; Object[] params = {param0, param1}; try { String resourceName = localeConfig.getResourceName(strResourceName); String resourceKey = resourceName + "_" + locale; bundle = (MessageBundle) bundleCache.get(resourceKey); if (bundle != null) { return MessageFormat.format(bundle.getString(key), params); } bundle = new MessageBundle(); ResourceBundle resBundle = ReloadablePropertyResourceBundle.getResourceBundle(resourceName, locale); bundle.setBundle(resBundle); bundleCache.put(key, bundle); } catch (Exception e) { e.printStackTrace(); } return MessageFormat.format(bundle.getString(key), params); } public static String getMessage(Locale locale, String strResourceName, String key, Object param0, Object param1, Object param2) { MessageBundle bundle = null; Object[] params = {param0, param1, param2}; try { String resourceName = localeConfig.getResourceName(strResourceName); String resourceKey = resourceName + "_" + locale; bundle = (MessageBundle) bundleCache.get(resourceKey); if (bundle != null) { return MessageFormat.format(bundle.getString(key), params); } bundle = new MessageBundle(); ResourceBundle resBundle = ReloadablePropertyResourceBundle.getResourceBundle(resourceName, locale); bundle.setBundle(resBundle); bundleCache.put(key, bundle); } catch (Exception e) { e.printStackTrace(); } return MessageFormat.format(bundle.getString(key), params); } public static String getMessage(Locale locale, String strResourceName, String key, Object param0, Object param1, Object param2, Object param3) { MessageBundle bundle = null; Object[] params = {param0, param1, param2, param3}; try { String resourceName = localeConfig.getResourceName(strResourceName); String resourceKey = resourceName + "_" + locale; bundle = (MessageBundle) bundleCache.get(resourceKey); if (bundle != null) { return MessageFormat.format(bundle.getString(key), params); } bundle = new MessageBundle(); ResourceBundle resBundle = ReloadablePropertyResourceBundle.getResourceBundle(resourceName, locale); bundle.setBundle(resBundle); bundleCache.put(key, bundle); } catch (Exception e) { e.printStackTrace(); } return MessageFormat.format(bundle.getString(key), params); } public static Locale getLocale(HttpServletRequest request) { Locale locale = (Locale) request.getSession(true).getAttribute("SELECTED_LANG"); if (locale == null) { locale = request.getLocale(); } return locale; } public static HashMap getLocaleHashMap() { return localeConfig.getLocaleConfig(); } public static LocaleConfigVO[] getLocaleConfigArray() { HashMap configMap = localeConfig.getLocaleConfig(); LocaleConfigVO[] configArray = new LocaleConfigVO[configMap.size()]; Collection values = configMap.values(); values.toArray(configArray); return configArray; } public static String getDefaultCode() { return localeConfig.getDefaultCode(); } }
package springwebapp.test; import static com.clc.controller.AppConstants.INCORRECT_CREDENTIALS; import static com.clc.controller.AppConstants.PASSWORD_INVALID; import static com.clc.controller.AppConstants.USERNAME_INVALID; import org.testng.Assert; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import com.clc.controller.BusinessLogicController; @Listeners(value=ReportGenerate.class) public class AutheticateTest { static BusinessLogicController controller = new BusinessLogicController(); @Test(enabled=false,alwaysRun=true,dataProvider = "testData" ,dataProviderClass=(DataProviderClass.class),dependsOnMethods="invalidCrendentials") public void verifyCrendentials(String unm, String pwd, String emsg) { String returnVal = controller.autheticateUser(unm, pwd); Assert.assertEquals(returnVal, emsg); } @Test(enabled=false,dataProvider = "testData" ,dataProviderClass=(DataProviderClass.class)) public void invalidCrendentials() { String returnVal = controller.autheticateUser("asadmin", "dadmin123"); Assert.assertEquals(returnVal, INCORRECT_CREDENTIALS); } @Test(invocationCount=3,invocationTimeOut=5) //in public void invalidUserName() { System.out.println("Hello.........."); String returnVal = controller.autheticateUser(null, "admin123"); Assert.assertEquals(returnVal, USERNAME_INVALID); returnVal = controller.autheticateUser("", "admin123"); Assert.assertEquals(returnVal, USERNAME_INVALID); returnVal = controller.autheticateUser("asd", "admin123"); Assert.assertEquals(returnVal, USERNAME_INVALID); } @Test(enabled = false) public void invalidPassword() { String returnVal = controller.autheticateUser("admin", null); Assert.assertEquals(returnVal, PASSWORD_INVALID); returnVal = controller.autheticateUser("admin12", ""); Assert.assertEquals(returnVal, PASSWORD_INVALID); returnVal = controller.autheticateUser("aasasssd", "aa"); Assert.assertEquals(returnVal, PASSWORD_INVALID); } }
package com.lmx.jredis.storage; import java.io.File; import java.io.RandomAccessFile; import java.lang.reflect.Method; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.security.AccessController; import java.security.PrivilegedAction; /** * 存储单元 * Created by lmx on 2017/4/14. */ public class BaseMedia { MappedByteBuffer buffer; int size = 1024 * 1024; FileChannel fileChannel; static File file; static File defaultFile; File f; final static String BASE_DIR = System.getProperty("data.path") == null ? "data" : System.getProperty("data.path") + File.separator + "data"; final public static String CHARSET = "UTF-8"; final char NORMAL = '1'; final char DELETE = '0'; int maxUnit = 1024; static int dbLength = 8; int accessIndex = 0; static { initFileSys(); } public void setIndex(int i) { if (i <= dbLength - 1) this.accessIndex = i; else throw new IndexOutOfBoundsException(); } public static void initFileSys() { file = new File(BASE_DIR); if (!file.exists()) file.mkdir(); for (int i = 0; i < dbLength; i++) { file = new File(BASE_DIR + File.separator + i); if (!file.exists()) file.mkdir(); if (i == 0) { defaultFile = file; } } } public static void delFileSys() { file = new File(BASE_DIR); if (file.exists()) { for (int i = 0; i < dbLength; i++) { file = new File(BASE_DIR + File.separator + i); if (file.exists()) { for (File file1 : file.listFiles()) { file1.delete(); } } } } } public BaseMedia() { } /** * 初始化10个分区为db * * @param db * @param fileName * @param memSize * @throws Exception */ public BaseMedia(int db, String fileName, int memSize) throws Exception { if (db == 0) f = new File(defaultFile.getAbsolutePath() + File.separator + fileName); else f = new File(defaultFile.getParentFile().getAbsolutePath() + File.separator + db + File.separator + fileName); if (!f.exists()) f.createNewFile(); fileChannel = new RandomAccessFile(f, "rw").getChannel(); long fileSize = Math.max(memSize * size, fileChannel.size()); buffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, fileSize == 0 ? memSize * size : fileSize); } public BaseMedia(String fileName, int memSize) throws Exception { f = new File(defaultFile.getAbsolutePath() + File.separator + fileName); if (!f.exists()) f.createNewFile(); fileChannel = new RandomAccessFile(f, "rw").getChannel(); long fileSize = Math.max(memSize * size, fileChannel.size()); buffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, fileSize == 0 ? memSize * size : fileSize); } public void clean() throws Exception { fileChannel.close(); AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { try { Method getCleanerMethod = buffer.getClass().getMethod("cleaner", new Class[0]); getCleanerMethod.setAccessible(true); sun.misc.Cleaner cleaner = (sun.misc.Cleaner) getCleanerMethod.invoke(buffer, new Object[0]); cleaner.clean(); delFile(); } catch (Exception e) { e.printStackTrace(); } return null; } }); } public void delFile() { f.delete(); } public void reAllocate() throws Exception { System.err.println("reAllocate file begin"); String dir = f.getParentFile().getParentFile().getAbsolutePath(); File newFile = new File(dir + File.separator + accessIndex + File.separator + f.getName() + "_tmp"); com.google.common.io.Files.copy(f, newFile); File newFile_ = new File(f.getAbsolutePath()); clean(); com.google.common.io.Files.copy(newFile, newFile_); newFile.delete(); fileChannel = new RandomAccessFile(newFile_, "rw").getChannel(); buffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, buffer.capacity() * 2); System.err.println("reAllocate file end"); } public void resize(int pos) throws Exception { //reallocate buffer if (buffer.remaining() - pos < 4) { reAllocate(); if ((pos = buffer.getInt()) != 0) buffer.position(pos); else buffer.position(4); } } }
package baidumapsdk.demo; import android.app.Application; import com.baidu.mapapi.SDKInitializer; import org.xutils.x; public class DemoApplication extends Application { @Override public void onCreate() { super.onCreate(); // 在使用 SDK 各组间之前初始化 context 信息,传入 ApplicationContext SDKInitializer.initialize(this); x.Ext.init(this); x.Ext.setDebug(true); } }
package fr.centralesupelec.sio.model; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; /** * An entity class for a movie. */ public class Movie { // Parameters of a movie. private long id; private String title; private List<String> genres = new ArrayList<>(); private List<String> directors = new ArrayList<>(); private List<String> actors = new ArrayList<>(); // Getters and Setters. public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public List<String> getGenres() { return genres; } public void setGenres(String genres) { this.genres.add(genres); } public List<String> getDirectors() { return directors; } public void setDirectors(String director) { Person person = new Director(); person.setName(director); this.directors.add(person.getName()); } public List<String> getActors() { return actors; } public void setActors(String actor) { Person person = new Actor(); person.setName(actor); this.actors.add(person.getName()); } }
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.Socket; import java.util.ArrayList; public class Downloading extends Thread{ Peers p; boolean flag = true; public Downloading(Peers p){ this.p = p; } public synchronized void run(){ while(flag){ try { p.down = new Socket("192.168.31.133", p.downloadPort); //while(p.chunklist.size()!=15){ ArrayList<Integer> toreceive = new ArrayList<Integer>(); DataInputStream disC = new DataInputStream( new BufferedInputStream(p.down.getInputStream())); DataOutputStream dos = new DataOutputStream(p.down.getOutputStream()); DataOutputStream fos = null; int lentore = disC.readInt(); for(int i=0; i<lentore; i++){ toreceive.add(disC.readInt()); } System.out.println("I'm gonna receive "+lentore+" chunks"); for(int j=0; j<lentore; j++){ System.out.print(toreceive.get(j)+ " "); } System.out.println(); int length=(int) disC.readLong()+1; //一次写入刚好文件大小! for(int index=0; index<lentore; index++){ int cid = toreceive.get(index); int bufferSize = 80000; byte[] buf = new byte[length]; System.out.println("Receiving "+cid+" chunk"); fos = new DataOutputStream( new BufferedOutputStream(new FileOutputStream("C:/users/ben/Desktop/Peers/P" + p.PeerID + "/" + "chunk" + cid + ".txt"))); while((length = disC.read(buf, 0, buf.length)) > 0){ fos.write(buf, 0, length); fos.flush(); fos.close(); break;//写完一个chunk,强行跳出来写下一个,不然都写到一个chunk.txt文件里去了。 } if(p.chunklist.contains(toreceive.get(index))==false) p.chunklist.add(toreceive.get(index)); p.addToSummary(); } System.out.println("Now I have "+p.chunklist.size()+" chunks"); p.down.close(); if(p.chunklist.size()==15) flag=false; Thread.sleep(5000); //} } catch (IOException | InterruptedException e) { e.printStackTrace(); } } p.FileJoiner(); System.out.println("All jobs are done here"); } }
package com.qa.pages; import com.qa.baseclass.BaseClass; public class SearchPage extends BaseClass{ }
package com.redpantssoft.cloudtodolist.provider; import android.accounts.Account; import android.content.ContentProvider; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.content.UriMatcher; import android.content.res.Resources; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.database.sqlite.SQLiteStatement; import android.net.Uri; import android.provider.BaseColumns; import android.util.Log; import com.redpantssoft.cloudtodolist.R; import com.redpantssoft.cloudtodolist.TodoListSyncHelper; import com.redpantssoft.cloudtodolist.client.GaeAuthenticator; import com.redpantssoft.cloudtodolist.client.HttpRestClient; import com.redpantssoft.cloudtodolist.client.TodoListRestClient; import org.apache.http.auth.AuthenticationException; import org.apache.http.auth.InvalidCredentialsException; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; /** * Provides access to a database of cloudtodolist entries. Each entry has an id, a title, notes, * and a completed flag */ public class TodoListProvider extends ContentProvider implements RestDataProvider { // Used for debugging and logging private static final String TAG = "TodoListProvider"; // Name of the underlying sqlite database private static final String DATABASE_NAME = "cloudtodolist.db"; // Current version of the underlying sqlite database private static final int DATABASE_VERSION = 1; /** * A UriMatcher Definitions * The Uri matcher allows the handlers to identify what data is to affected */ // Constants used by the Uri matcher to identify URI matches private static final int ENTRIES = 1; private static final int ENTRY_ID = 2; // Reference to a URI matcher private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); // Add both the CONTENT_URI and CONTENT_ID_URI uri's to the matcher static { uriMatcher.addURI(TodoListSchema.AUTHORITY, TodoListSchema.Entries.PATH_TODOLIST_ENTRIES, ENTRIES); uriMatcher.addURI(TodoListSchema.AUTHORITY, TodoListSchema.Entries.PATH_TODOLIST_ENTRY_ID + "#", ENTRY_ID); } /** * A helper class to manage database creation and version management. * <p/> * NOTE: this will defer opening and upgrading the database until first use, * to avoid blocking application startup with long-running database upgrades. Best * practice is to access the provider in a background task, or to use a Loader */ class DatabaseHelper extends SQLiteOpenHelper { /** * Constructor - tells the base class the name of * database and current version * * @param context context of the provider */ DatabaseHelper(Context context) { // calls the super constructor, requesting the default cursor factory. super(context, DATABASE_NAME, null, DATABASE_VERSION); } /** * Called when the database is created for the first time. This will create * the TodoList table as defined in the schema. This will also initialize * the lastSyncTime to 0 ( the beginning of time) * * @param db instance of a writable database */ @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + TodoListSchema.Entries.TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + TodoListSchema.Entries.ID + " INTEGER KEY UNIQUE DEFAULT NULL," + TodoListSchema.Entries.TITLE + " TEXT," + TodoListSchema.Entries.NOTES + " TEXT," + TodoListSchema.Entries.COMPLETE + " INTEGER," + TodoListSchema.Entries.CREATED + " LONG," + TodoListSchema.Entries.MODIFIED + " LONG," + TodoListSchema.Entries.PENDING_TX + " INTEGER DEFAULT 0," + TodoListSchema.Entries.PENDING_UPDATE + " INTEGER KEY DEFAULT 0," + TodoListSchema.Entries.PENDING_DELETE + " INTEGER KEY DEFAULT 0" + ");"); setLastSyncTime(0); } /** * Called when the database needs to be upgraded. This will drop the table, wiping all * the data. This is acceptable as a sync will result in a full refresh. * * @param db instance of a writable database * @param oldVersion old version * @param newVersion new version */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Logs that the database is being upgraded Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); // Kills the table and existing data db.execSQL("DROP TABLE IF EXISTS " + TodoListSchema.Entries.TABLE_NAME); // Recreates the database with a new version onCreate(db); } } // DatabaseHelper reference private DatabaseHelper dbHelper; /** * This is for unit tests, returns direct access to a the database to * prepopulate data for tests * * @return A writable SQLite database object for the data being managed by the provider */ SQLiteDatabase getWritableDatabase() { return dbHelper.getWritableDatabase(); } /** * Static WHERE clauses */ private static final String WHERE_DIRTY_ENTRIES = " (" + TodoListSchema.Entries.PENDING_DELETE + " > 0" + " OR " + TodoListSchema.Entries.PENDING_UPDATE + " > 0) "; private static final String WHERE_CURRENT_ENTRIES = " (" + TodoListSchema.Entries.PENDING_DELETE + " = 0" + " AND " + TodoListSchema.Entries.PENDING_UPDATE + " = 0) "; private static final String WHERE_NON_DELETED_ENTRIES = TodoListSchema.Entries.PENDING_DELETE + " = 0"; // Shared prefs object for TodoListProvider persistent data private SharedPreferences sharedPreferences; /** * This method is called for all registered content providers on the application main thread at * application launch time. It must not perform lengthy operations, or application startup * will be delayed. * * @return if the provider was successfully loaded, false otherwise */ @Override public boolean onCreate() { // Creates a new helper object. Note that the database itself isn't opened until // something tries to access it, and it's only created if it doesn't already exist. dbHelper = new DatabaseHelper(getContext()); // Initialize the last sync time from the shared prefs sharedPreferences = getContext().getSharedPreferences(this.getClass().getName(), Context.MODE_PRIVATE); // Assumes that any failures will be reported by a thrown exception. return true; } /** * This handles requests for the MIME type of the data at the given URI * * @param uri Uri to query * @return a MIME type string, or null if there is no type */ @Override public String getType(Uri uri) { // Return the MIME type based on the incoming URI pattern switch (uriMatcher.match(uri)) { case ENTRIES: return TodoListSchema.Entries.CONTENT_TYPE; case ENTRY_ID: return TodoListSchema.Entries.CONTENT_ITEM_TYPE; default: throw new IllegalArgumentException("Unknown URI " + uri); } } /** * Handles query requests from clients * * @param uri Uri to query * @param what list of columns to put into the cursor. If null all columns are included. * @param where selection criteria to apply when filtering rows. If null then all rows are included * @param whereArgs any included '?'s in where will be replaced by the values from whereArgs, * in order that they appear in the selection. The values will be bound as Strings. * @param sortOrder sort order for the rows in the cursor. If null then the the * TodoListSchema.DEFAULT_SORT_ORDER will be used * @return a cursor or null */ @Override public Cursor query(Uri uri, String[] what, String where, String[] whereArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); String orderBy; switch (uriMatcher.match(uri)) { case ENTRY_ID: /** * When an ENTRY_ID resource is specified, a filter to include that entry id is * added to the where clause */ qb.appendWhere(BaseColumns._ID + "=" + uri.getPathSegments().get(TodoListSchema.Entries.TODOLIST_ENTRY_ID_PATH_POSITION) + " AND "); // fall through case ENTRIES: /** * For all requests, entries that have the PENDING_DELETE flag are not returned in the * query and treated as if they have been deleted. */ qb.appendWhere(TodoListSchema.Entries.PENDING_DELETE + "=" + 0); qb.setTables(TodoListSchema.Entries.TABLE_NAME); if (sortOrder != null) { orderBy = sortOrder; } else { orderBy = TodoListSchema.Entries.DEFAULT_SORT_ORDER; } break; default: // If the URI doesn't match any of the known patterns, throw an exception. throw new IllegalArgumentException("Unknown URI " + uri); } // Perform the query Cursor cur = qb.query(dbHelper.getReadableDatabase(), what, where, whereArgs, null, null, orderBy); // This is required register the cursor, with the resolver, for notifications on the specified URI. cur.setNotificationUri(getContext().getContentResolver(), uri); return cur; } /** * Handles requests to insert a new row * * @param uri Uri of the insertion request. * @param contentValues set of column_name/value pairs to add to the database * @return Uri for the newly inserted item */ @Override public Uri insert(Uri uri, ContentValues contentValues) { // Initialize a new ContentValues object to whatever was passed in ContentValues values = new ContentValues(); if (contentValues != null) values.putAll(contentValues); long now = System.currentTimeMillis(); long newId; switch (uriMatcher.match(uri)) { case ENTRIES: /** * Initialize the PENDING_UPDATE to 2. This indicates that * the entry needs to synced upstream. This is a tri-state flag * used to indicate that the sync operation has been staged and * completed. */ values.put(TodoListSchema.Entries.PENDING_UPDATE, 2); values.put(TodoListSchema.Entries.PENDING_DELETE, 0); // Initialize values, that are omitted, to defaults if (!values.containsKey(TodoListSchema.Entries.CREATED)) values.put(TodoListSchema.Entries.CREATED, now); if (!values.containsKey(TodoListSchema.Entries.MODIFIED)) values.put(TodoListSchema.Entries.MODIFIED, now); if (!values.containsKey(TodoListSchema.Entries.TITLE)) values.put(TodoListSchema.Entries.TITLE, Resources.getSystem() .getString(android.R.string.untitled) ); if (!values.containsKey(TodoListSchema.Entries.NOTES)) values.put(TodoListSchema.Entries.NOTES, ""); if (!values.containsKey(TodoListSchema.Entries.COMPLETE)) values.put(TodoListSchema.Entries.COMPLETE, 0); // Perform the insert newId = dbHelper.getWritableDatabase() .insert(TodoListSchema.Entries.TABLE_NAME, null, values); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } // If the insert succeeded, the newly inserted row will be assigned an ID. // If it is zero, it failed. if (newId <= 0) throw new IllegalArgumentException("Failed to insert row into " + uri); // Notify changes on the newly created entry URI Uri entryUri = ContentUris.withAppendedId(TodoListSchema.Entries.CONTENT_ID_URI_BASE, newId); notifyContentResolverOfChange(entryUri); // Request a lazy sync to sync this change upstream try { TodoListSyncHelper.requestLazySync(getContext()); } catch (UnsupportedOperationException e) { // This will happen when running unit tests, just ignore } return entryUri; } /** * Helper class for building 'where' clause strings */ @SuppressWarnings({"UnusedDeclaration", "unused"}) private class WhereStringBuilder { // Base where clause String where; // string to append to the base String append; WhereStringBuilder() { this.where = null; this.append = null; } WhereStringBuilder(String where) { this.where = where; this.append = null; } void appendAnd(String append) { if (this.append != null) { this.append += " AND " + append; } else { this.append = append; } } void appendAndParenthesis(String append) { if (this.append != null) { this.append += " AND (" + append + ")"; } else { this.append = append; } } void appendOr(String append) { if (this.append != null) { this.append += " OR " + append; } else { this.append = append; } } void appendOrParenthesis(String append) { if (this.append != null) { this.append += " OR (" + append + ")"; } else { this.append = append; } } public String build() { if (where != null) { return where + " AND (" + append + ")"; } else { return append; } } } /** * Handles requests to delete one or more rows * * @param uri Uri to query * @param where selection criteria to apply when deleting rows. If null then all rows are deleted * @param whereArgs any included '?'s in where will be replaced by the values from whereArgs, * in order that they appear in the selection. The values will be bound as Strings. * @return number of rows deleted */ @Override public int delete(Uri uri, String where, String[] whereArgs) { ContentValues values = new ContentValues(); int count; WhereStringBuilder whereBuilder = new WhereStringBuilder(where); switch (uriMatcher.match(uri)) { case ENTRY_ID: /** * When an ENTRY_ID resource is specified, a filter to include that entry id is * added to the where clause */ whereBuilder.appendAnd(BaseColumns._ID + " = " + getEntryIdFromUri(uri)); //fall through case ENTRIES: // Append where clause to include all PENDING_DELETE = 0 rows whereBuilder.appendAnd(WHERE_NON_DELETED_ENTRIES); /** * The delete doesn't immediately delete, it set the PENDING_DELETE flag * to 1. This will trigger an upstream sync of the deleted item. Once it is * delete upstream, it will be deleted completely from the database. */ values.put(TodoListSchema.Entries.PENDING_DELETE, 1); count = dbHelper.getWritableDatabase().update(TodoListSchema.Entries.TABLE_NAME, values, whereBuilder.build(), whereArgs); break; // If the incoming pattern is invalid, throws an exception. default: throw new IllegalArgumentException("Unknown URI " + uri); } if (count > 0) { // If any rows where affected, notify listeners and request a lazy sync notifyContentResolverOfChange(uri); try { TodoListSyncHelper.requestLazySync(getContext()); } catch (UnsupportedOperationException e) { // This will happen when running unit tests, just ignore } } return count; } /** * Handles requests to update one or more rows * * @param uri Uri to query * @param contentValues bundle mapping column names to new column values * @param where selection criteria to apply when updating rows. If null then all rows are updated * @param whereArgs any included '?'s in where will be replaced by the values from whereArgs, * in order that they appear in the selection. The values will be bound as Strings. * @return number of rows updated */ @Override public int update(Uri uri, ContentValues contentValues, String where, String[] whereArgs) { // Initialize a new ContentValues object to whatever was passed in ContentValues values = new ContentValues(); if (contentValues != null) values.putAll(contentValues); WhereStringBuilder wherebuilder = new WhereStringBuilder(where); int count; switch (uriMatcher.match(uri)) { case ENTRY_ID: /** * When an ENTRY_ID resource is specified, a filter to include that entry id is * added to the where clause */ wherebuilder.appendAnd(BaseColumns._ID + " = " + getEntryIdFromUri(uri)); // fall through case ENTRIES: // Append where clause to include all PENDING_DELETE = 0 rows wherebuilder.appendAnd(WHERE_NON_DELETED_ENTRIES); // Set the Modified times to NOW if not set values.put(TodoListSchema.Entries.MODIFIED, System.currentTimeMillis()); // Mark the entry as pending an update values.put(TodoListSchema.Entries.PENDING_UPDATE, 2); // Perform the update SQLiteDatabase db = dbHelper.getWritableDatabase(); count = db.update(TodoListSchema.Entries.TABLE_NAME, values, wherebuilder.build(), whereArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } if (count > 0) { // If any rows where affected, notify listeners and request a lazy sync notifyContentResolverOfChange(uri); try { TodoListSyncHelper.requestLazySync(getContext()); } catch (UnsupportedOperationException e) { // This will happen when running unit tests, just ignore } } return count; } /** * Handles requests to perform a batch of operation * This implementation will perform the operations in a transaction. In the event * of any operation failing, the transaction will be rolled back * * @param operations operations to apply * @return list of results of the operations */ @Override public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) { ContentProviderResult[] backRefs = new ContentProviderResult[operations.size() - 1]; List<ContentProviderResult> results = new ArrayList<ContentProviderResult>(operations.size()); SQLiteDatabase db = dbHelper.getWritableDatabase(); // Make this a transaction buy starting a SQLite transaction and returning all or // none ContentProviderResults db.beginTransaction(); try { for (ContentProviderOperation operation : operations) results.add(operation.apply(this, results.toArray(backRefs), results.size())); db.setTransactionSuccessful(); } catch (Exception e) { Log.e(TAG, "Batch Operation failed: " + e.toString()); results.clear(); } finally { db.endTransaction(); } return results.toArray(new ContentProviderResult[results.size()]); } private void notifyContentResolverOfChange(Uri uri) { getContext().getContentResolver().notifyChange(uri, null); } private void notifyContentResolverOfChange() { notifyContentResolverOfChange(TodoListSchema.Entries.CONTENT_URI); } private void notifyContentResolverOfChange(int id) { notifyContentResolverOfChange( ContentUris.withAppendedId(TodoListSchema.Entries.CONTENT_ID_URI_BASE, id)); } /** * Clears out the local data store and resets the last sync time. */ private void clearLocalDataStore() { dbHelper.getWritableDatabase().delete(TodoListSchema.Entries.TABLE_NAME, null, null); setLastSyncTime(0); } /** * Method to convert a JSONObject result, from the upstream REST service, to a * ContentValues object suitable to for a local datastore operation * * @param entry - JSONObject entry to convert * @return - newly created ContentValues structure, initialized from the JSONObject entry * @throws JSONException - indicates an invalid format for the JSONObject entry */ private static ContentValues entryObjectValues(JSONObject entry) throws JSONException { ContentValues entryValues = new ContentValues(); entryValues.put(TodoListSchema.Entries.ID, entry.getInt(TodoListRestClient.ENTRY_ID)); entryValues.put(TodoListSchema.Entries.COMPLETE, entry.getBoolean(TodoListRestClient.ENTRY_COMPLETE) ? 1 : 0); if (!entry.isNull(TodoListRestClient.ENTRY_TITLE)) { entryValues.put(TodoListSchema.Entries.TITLE, entry.getString(TodoListRestClient.ENTRY_TITLE)); } else { entryValues.put(TodoListSchema.Entries.TITLE, ""); } if (!entry.isNull(TodoListRestClient.ENTRY_NOTES)) { entryValues.put(TodoListSchema.Entries.NOTES, entry.getString(TodoListRestClient.ENTRY_NOTES)); } else { entryValues.put(TodoListSchema.Entries.NOTES, ""); } entryValues.put(TodoListSchema.Entries.CREATED, (long) (entry.getDouble(TodoListRestClient.ENTRY_CREATED) * 1000)); entryValues.put(TodoListSchema.Entries.MODIFIED, (long) (entry.getDouble(TodoListRestClient.ENTRY_MODIFIED) * 1000)); return entryValues; } /** * Handles requests to sync the content provider with an HttpRestClient. * * @param httpRestClient - client object to perform upstream sync with * @param account - optional account to use to validate requests to the rest service * @param fullSync - indicates whether a fullSync is being requested, a full sync clears all * the local data and retrieves all the current data from the service * @return SyncResult object indicating the status and result of the sync operation */ @Override synchronized public SyncResult onPerformSync(HttpRestClient httpRestClient, Account account, boolean fullSync) { // Initialize an empty result object SyncResult result = new SyncResult(); // Wrap the HttpRest client in a TodoListRest client which wraps the service API if (account != null) { try { httpRestClient.setAuthenticator(new GaeAuthenticator(getContext(), account)); } catch (AuthenticationException e) { Log.e(TAG, "onPerformSync, Authentication Error: " + e.getMessage()); result.numAuthenticationErrors++; if (e.getCause() instanceof InvalidCredentialsException) { result.invalidCredentials = true; } return result; } catch (IOException e) { Log.e(TAG, "onPerformSync, Network Error: " + e.getMessage()); result.numIoExceptions += 1; return result; } catch (URISyntaxException e) { Log.e(TAG, "onPerformSync, Invalid request: " + e.getMessage()); result.numRequestExceptions += 1; return result; } } TodoListRestClient client = new TodoListRestClient(httpRestClient); /** * If a full sync is requested, clear the local datastore, otherwise, start an * upstream sync. */ if (fullSync) { clearLocalDataStore(); } else { performUpstreamSync(client, result); } if (!(result.serverError() || result.networkError())) { if (lastSyncTime() > 0) { performIncrementalSync(client, result); } else { performFullSync(client, result); } } return result; } /** * Performs an incremental sync by using the lastSyncTime as a MODIFIED filter * to the getEntries API request. * * @param client - cloudtodolist api client object * @param result - result of the incremental sync operation */ private void performIncrementalSync(TodoListRestClient client, SyncResult result) { try { TodoListRestClient.EntryListResponse response = client.getEntries(lastSyncTime()); int statusCode = response.getResponse().getStatusCode(); if (statusCode == TodoListRestClient.Response.SUCCESS_OK) { List<JSONObject> entries = response.getEntryList(); SQLiteDatabase db = dbHelper.getWritableDatabase(); /** * Compile a SQL statement to retrieve the number of entries for a specified ID. * This should always return 0 or 1 since the ID is a unique key */ String idWhere = TodoListSchema.Entries.ID + " = ?"; SQLiteStatement entryCount = db.compileStatement( "SELECT COUNT(*) FROM " + TodoListSchema.Entries.TABLE_NAME + " WHERE " + idWhere); // Start a transaction to make the update atomic db.beginTransaction(); try { for (JSONObject entry : entries) { long id = entry.getLong(TodoListRestClient.ENTRY_ID); String[] whereArgs = {Long.toString(id)}; if (entry.getBoolean(TodoListRestClient.ENTRY_DELETED)) { // If the entry is deleted, remove it from the local database // regardless of whether or not it is dirty. If its been deleted, // our local changes are irrelevant. long deletes = db.delete(TodoListSchema.Entries.TABLE_NAME, idWhere, whereArgs); if (deletes > 0) { result.numDeletes += deletes; result.numEntries++; notifyContentResolverOfChange(); } } else { ContentValues values = entryObjectValues(entry); /** * Look in the database to see if this entry already exists or * is a new addition. */ entryCount.bindLong(1, id); if (entryCount.simpleQueryForLong() > 0) { String where = idWhere + " AND " + WHERE_CURRENT_ENTRIES + " AND " + TodoListSchema.Entries.MODIFIED + " != " + values.getAsLong(TodoListSchema.Entries.MODIFIED); long updates = db.update(TodoListSchema.Entries.TABLE_NAME, values, where, whereArgs); if (updates > 0) { result.numUpdates += updates; result.numEntries++; notifyContentResolverOfChange(); } } else { db.insert(TodoListSchema.Entries.TABLE_NAME, TodoListSchema.Entries.TITLE, values); result.numInserts++; result.numEntries++; notifyContentResolverOfChange(); } } } setLastSyncTime(response.getTimestamp()); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } else if (statusCode == TodoListRestClient.Response.FAILED_BAD_REQUEST) { // A bad request is returned if the last sync time is out of the acceptable // window. In this case, we need to do a refresh. result.fullSyncRequested = true; } else result.numRequestExceptions = 1; } catch (IOException e) { Log.e(TAG, "performIncrementalSync, Network Error: " + e.getMessage()); result.numIoExceptions += 1; } catch (URISyntaxException e) { Log.e(TAG, "performIncrementalSync, Invalid request: " + e.getMessage()); result.numRequestExceptions += 1; } catch (JSONException e) { Log.e(TAG, "performIncrementalSync, Invalid response: " + e.getMessage()); result.numResponseExceptions += 1; } catch (AuthenticationException e) { Log.e(TAG, "performIncrementalSync, Authentication Error: " + e.getMessage()); result.numAuthenticationErrors++; if (e instanceof InvalidCredentialsException) { result.invalidCredentials = true; } } } /** * Performs a full sync by retrieving the entire list of existing entries. This may have * been a requested full sync, for it may be because an incremental sync hasn't been performed * in the required window of time. If it was a requested full sync, the local datastore should * be empty. Regardless, the operation will create a temporary table to save off all the dirty * entries, retrieve a full set of existing entries, and then re-apply the dirty entries to preserve * those changes * * @param client - cloudtodolist api client object * @param result - result of the full sync operation */ private void performFullSync(TodoListRestClient client, SyncResult result) { try { TodoListRestClient.EntryListResponse response = client.getEntries(); if (response.getResponse().getStatusCode() == TodoListRestClient.Response.SUCCESS_OK) { List<JSONObject> entries = response.getEntryList(); SQLiteDatabase db = dbHelper.getWritableDatabase(); String tempTableName = TodoListSchema.Entries.TABLE_NAME + "_refresh"; db.beginTransaction(); try { // Create a Temporary Table to store all the dirty entries db.execSQL("CREATE TEMP TABLE " + tempTableName + " AS SELECT * from " + TodoListSchema.Entries.TABLE_NAME + " WHERE " + WHERE_DIRTY_ENTRIES); // Replace the current table with the entries from the refresh db.delete(TodoListSchema.Entries.TABLE_NAME, null, null); for (JSONObject entry : entries) db.insert(TodoListSchema.Entries.TABLE_NAME, TodoListSchema.Entries.TITLE, entryObjectValues(entry)); // Now add back the Temporary items as an UPDATE. This insures that deleted // dirty items are deleted and unsynced changes are maintained Cursor cur = db.query(tempTableName, null, null, null, null, null, null); String where = TodoListSchema.Entries.ID + "= ?"; for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) { String[] whereArgs = {cur.getString(cur.getColumnIndex(TodoListSchema.Entries.ID))}; ContentValues values = new ContentValues(); for (String column : cur.getColumnNames()) values.put(column, cur.getString(cur.getColumnIndex(column))); db.update(TodoListSchema.Entries.TABLE_NAME, values, where, whereArgs); } setLastSyncTime(response.getTimestamp()); db.setTransactionSuccessful(); } finally { db.endTransaction(); // Clean up the temporary Table db.execSQL("DROP TABLE IF EXISTS " + tempTableName + ";"); } notifyContentResolverOfChange(); } else result.numRequestExceptions = 1; } catch (IOException e) { Log.e(TAG, "performFullSync, Network Error: " + e.getMessage()); result.numIoExceptions += 1; } catch (URISyntaxException e) { Log.e(TAG, "performFullSync, Invalid request: " + e.getMessage()); result.numRequestExceptions += 1; } catch (JSONException e) { Log.e(TAG, "performFullSync, Invalid response: " + e.getMessage()); result.numResponseExceptions += 1; } catch (AuthenticationException e) { Log.e(TAG, "performFullSync, Authentication Error: " + e.getMessage()); result.numAuthenticationErrors++; if (e instanceof InvalidCredentialsException) { result.invalidCredentials = true; } } } /** * Handles staging an upstream sync.First, stage the sync by creating a * temporary table that contains all the dirty entries and updating the * PENDING_UPDATE and PENDING_TX lags in the main table. This indicates * that the sync operations, for these entries, is in progress * * @return name of the temporary staging table */ private String stageUpstreamSync() { SQLiteDatabase db = dbHelper.getWritableDatabase(); String tempTableName = TodoListSchema.Entries.TABLE_NAME + "_upsync"; ContentValues values = new ContentValues(); values.put(TodoListSchema.Entries.PENDING_UPDATE, 1); values.put(TodoListSchema.Entries.PENDING_TX, 1); /** * */ db.beginTransaction(); try { // Create a Temporary Table to store all the syncable items db.execSQL("CREATE TEMP TABLE " + tempTableName + " AS SELECT * from " + TodoListSchema.Entries.TABLE_NAME + " WHERE " + WHERE_DIRTY_ENTRIES + ";"); // Update the pending flags to indicate that the entry // is currently being processed db.update(TodoListSchema.Entries.TABLE_NAME, values, WHERE_DIRTY_ENTRIES, null); db.setTransactionSuccessful(); } finally { db.endTransaction(); } return tempTableName; } /** * Handles ending an upstream sync by clearing the temporary staging * table and rolling back all PENDING_TX flags * * @param tempTableName name of an existing temporary staging table */ private void endUpstreamSync(String tempTableName) { SQLiteDatabase db = dbHelper.getWritableDatabase(); db.execSQL("DROP TABLE " + tempTableName + ";"); ContentValues pendingTxValue = new ContentValues(); pendingTxValue.put(TodoListSchema.Entries.PENDING_TX, 0); getWritableDatabase().update( TodoListSchema.Entries.TABLE_NAME, pendingTxValue, TodoListSchema.Entries.PENDING_TX + "=1", null); } /** * Handles syncing all local,dirty entries with the the upstream service. * * @param client - cloudtodolist api client object * @param result - result of the upstream sync operation */ void performUpstreamSync(TodoListRestClient client, SyncResult result) { SQLiteDatabase db = dbHelper.getWritableDatabase(); String tempTableName = stageUpstreamSync(); Cursor cur = null; try { String idWhere = BaseColumns._ID + " = ?"; // Walk through the temporary staging table and perform the pending action cur = db.query(tempTableName, null, null, null, null, null, TodoListSchema.Entries.DEFAULT_SORT_ORDER); for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) { int rowId = cur.getInt(cur.getColumnIndex(BaseColumns._ID)); String[] whereArgs = {Integer.toString(rowId)}; int id = cur.getInt(cur.getColumnIndex(TodoListSchema.Entries.ID)); try { if (cur.getInt(cur.getColumnIndex(TodoListSchema.Entries.PENDING_DELETE)) > 0) { // Attempt to delete the item via the client, if it succeeds, delete it locally TodoListRestClient.Response response = client.deleteEntry(id); if (response.getResponse().getStatusCode() == TodoListRestClient.Response.SUCCESS_OK) { db.delete(TodoListSchema.Entries.TABLE_NAME, idWhere, whereArgs); result.numUpstreamDeletes += 1; notifyContentResolverOfChange(rowId); } else result.numRequestExceptions = 1; } else if (cur.getInt(cur.getColumnIndex(TodoListSchema.Entries.PENDING_UPDATE)) > 0) { ContentValues values = new ContentValues(); values.put(TodoListSchema.Entries.TITLE, cur.getString(cur.getColumnIndex(TodoListSchema.Entries.TITLE))); values.put(TodoListSchema.Entries.NOTES, cur.getString(cur.getColumnIndex(TodoListSchema.Entries.NOTES))); values.put(TodoListSchema.Entries.COMPLETE, cur.getInt(cur.getColumnIndex(TodoListSchema.Entries.COMPLETE))); // If the entry was updated, check if it has a valid ID. If it // is zero, the entry need to be inserted, otherwise update TodoListRestClient.EntryObjectResponse response; if (id == 0) { response = client.postEntry(values); } else { response = client.putEntry(id, values); } // If success, update the local entry if it is not dirty and // decrement the PENDING_TX flag int statusCode = response.getResponse().getStatusCode(); if (statusCode == TodoListRestClient.Response.SUCCESS_OK) result.numUpstreamUpdates += 1; else if (statusCode == TodoListRestClient.Response.SUCCESS_ADDED) result.numUpstreamInserts += 1; else { result.numRequestExceptions = 1; continue; } // Update the entry in the response, but not the "editable" fields values = entryObjectValues(response.getEntryObject()); values.remove(TodoListSchema.Entries.TITLE); values.remove(TodoListSchema.Entries.NOTES); values.remove(TodoListSchema.Entries.COMPLETE); db.beginTransaction(); try { long pendingTx = DatabaseUtils.longForQuery(db, "SELECT " + TodoListSchema.Entries.PENDING_UPDATE + " FROM " + TodoListSchema.Entries.TABLE_NAME + " WHERE " + idWhere, whereArgs ); values.put(TodoListSchema.Entries.PENDING_UPDATE, pendingTx - 1); db.update(TodoListSchema.Entries.TABLE_NAME, values, idWhere, whereArgs); notifyContentResolverOfChange(rowId); db.setTransactionSuccessful(); } finally { db.endTransaction(); } } } catch (JSONException e) { Log.e(TAG, "performUpstreamSync, Invalid response: " + e.getMessage()); result.numResponseExceptions++; } catch (URISyntaxException e) { Log.e(TAG, "performUpstreamSync, Invalid request: " + e.getMessage()); result.numRequestExceptions++; } catch (AuthenticationException e) { Log.e(TAG, "performUpstreamSync, Authentication Error: " + e.getMessage()); result.numAuthenticationErrors++; if (e instanceof InvalidCredentialsException) { result.invalidCredentials = true; } } } } catch (IOException e) { Log.e(TAG, "performUpstreamSync, Network error: " + e.getMessage()); result.numIoExceptions += 1; } finally { endUpstreamSync(tempTableName); cur.close(); } } /** * Parses the entry ID from the specified URI * * @param uri - uri to parse * @return entry id specified in the uri */ private static int getEntryIdFromUri(Uri uri) { return Integer.parseInt( uri.getPathSegments().get( TodoListSchema.Entries.TODOLIST_ENTRY_ID_PATH_POSITION) ); } /** * Retrieves the last sync time from the SharedPrefs */ private double lastSyncTime() { String key = getContext().getString(R.string.lastSyncTime); String val = sharedPreferences.getString(key, "0"); return Double.parseDouble(val); } /** * Writes the lastSyncTime to a the SharedPRefs */ private void setLastSyncTime(double lastSyncTime) { SharedPreferences.Editor editor = sharedPreferences.edit(); String key = getContext().getString(R.string.lastSyncTime); String val = Double.toString(lastSyncTime); editor.putString(key, val); editor.commit(); } }
package org.giddap.dreamfactory.leetcode.onlinejudge.implementations; import org.giddap.dreamfactory.leetcode.commons.TreeNode; import org.giddap.dreamfactory.leetcode.onlinejudge.PathSumII; import java.util.ArrayList; import java.util.List; /** * DFS with backtracking. */ public class PathSumIIDfsImpl implements PathSumII { @Override public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> ret = new ArrayList<>(); calculdatePathSum(ret, new ArrayList<Integer>(), root, sum); return ret; } private void calculdatePathSum(List<List<Integer>> ret, List<Integer> path, TreeNode node, int remainingSum) { if (node == null) { return; } remainingSum -= node.val; if (node.left == null && node.right == null) { if (remainingSum == 0) { ArrayList<Integer> one = new ArrayList<Integer>(path); one.add(node.val); ret.add(one); } return; } path.add(node.val); calculdatePathSum(ret, path, node.left, remainingSum); calculdatePathSum(ret, path, node.right, remainingSum); path.remove(path.size() - 1); } }
/* Copyright 2006 thor.jini.org Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* * ThorSession_Impl.java * * Created on 18 September 2001, 11:35 */ package org.jini.projects.thor.service; import java.rmi.Remote; import net.jini.id.UuidFactory; import org.jini.glyph.chalice.DefaultExporterManager; import org.jini.glyph.chalice.ExporterManager; import org.jini.projects.thor.handlers.Branch; import org.jini.projects.thor.handlers.Branch_Impl; import org.jini.projects.thor.service.store.StorageFactory; /** * Concrete class implementing the Session Interface for the public ROOT * * @author calum */ public class ThorSession_Impl implements ThorSession, Remote { //private Exporter exp; private Branch root; private Branch_Impl handler; /** Creates new ThorSession_Impl */ public ThorSession_Impl() throws java.rmi.RemoteException { } public org.jini.projects.thor.handlers.Branch getRoot() throws java.rmi.RemoteException { if (root == null) { ExporterManager exp = DefaultExporterManager.getManager("default"); //exp = new BasicJeriExporter(HttpServerEndpoint.getInstance(0), new BasicILFactory()); handler = new Branch_Impl(StorageFactory.getBackend().getBranch("ROOT")); //Remote r = exp.export(handler); //root = ClientHandlerProxy.create((Branch) r, UuidFactory.generate()); root = (Branch) exp.exportProxy(handler, "ClientHandlers", UuidFactory.generate()); } return root; } /* @see java.lang.Object#finalize() */ protected void finalize() throws Throwable { // TODO Complete method stub for finalize System.out.println(this.getClass().getName() + " finalized"); } }
package coreJava_programs.Java_Programs; public class Bubble_Sort_logic_and_Program_6 { public static void doBubbleSort(int[] array) { int temp; for(int i = 0;i< array.length; i++) { for(int j = i+1;j< array.length; j++) { if(array[i] > array[j]) { temp = array[i]; array[i] = array[j]; array[j] = temp; } } } printLogic(array); } public static void printLogic(int[] array) { for(int a: array) { System.out.print(a+","); } } public static void main(String[] args) { int a[] = {6,4,9,2,1,5,3}; doBubbleSort(a); } }
// https://leetcode.com/problems/flood-fill/ // #dfs class Solution { public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { int target = image[sr][sc]; int m = image.length; int n = image[0].length; boolean[][] visited = new boolean[m][n]; Deque<Pixel> queue = new LinkedList<>(); // start pixel visited[sr][sc] = true; image[sr][sc] = newColor; queue.addLast(new Pixel(sr, sc)); int[] dx = {-1, 0, 0, 1}; int[] dy = {0, -1, 1, 0}; while (!queue.isEmpty()) { Pixel p = queue.pollFirst(); for (int i = 0; i < 4; i++) { int x = p.x + dx[i], y = p.y + dy[i]; if (validPixel(image, x, y, visited) && image[x][y] == target) { visited[x][y] = true; image[x][y] = newColor; queue.addLast(new Pixel(x, y)); } } } return image; } private boolean validPixel(int[][] image, int x, int y, boolean[][] visited) { if (x == -1 || x == image.length) return false; if (y == -1 || y == image[0].length) return false; if (visited[x][y]) return false; return true; } private class Pixel { int x, y; Pixel(int x, int y) { this.x = x; this.y = y; } } }
package day23encapsulationinheritance; public class Animal { public void eat() { System.out.println("They eat..."); } public void drink() { System.out.println("They drink..."); } } /* 1) Why do we need inheritance? 2) What are the benefits of inheritance? a)No repetition b)Less coding c)Easy update d)Easy maintenance 3) We store common class members (variables or methods) into Parent Class 4)We store specific class members into Child classes 5) Privateclass memebers in Parent Class cannot be used by Child Classes 6) If Child Class and Parent Class are in same package then Child Classes can use the default class members from in Parent Class 7) Child Classes can use all protected class members in Parent Class Note: For "public" and "protected" access modifiers inheritance works without any issue Note: For private access modifiers there is no inheritance. Note: For default access modifiers you should be careful. NOTE:Java doesn't support multiple inheritance. */
package training.employee.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; 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.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import training.employee.model.Data; import training.employee.model.Employee; import training.employee.model.EmployeeRepository; @Controller @RequestMapping public class EmployeeController { @Autowired private EmployeeRepository repository; @GetMapping("/") public ModelAndView index() { return new ModelAndView("add.html"); } // @PostMapping("/addemployee") // public @ResponseBody String addNewEmployee(@RequestBody Employee emp) { // System.out.println("mapped right"); // Employee newEmp = new Employee(); // newEmp.setMobile(emp.getMobile()); // newEmp.setName(emp.getName()); // // return "success : 'employee added'"; // } @PostMapping("/addemployee") public @ResponseBody String add(Data dataObject) { System.out.println("mapped rightly"); System.out.println(dataObject); return "<html><body>worked</body></html>"; } @GetMapping("/add") public ModelAndView add(@RequestParam String name,@RequestParam String mobile) { // Employee newEmployee = new Employee(); // newEmployee.setName("Hariharan"); // newEmployee.setMobile("123456789"); // // repository.save(newEmployee); // System.out.println("new emploee added"); // return "Employee added"; return new ModelAndView("success.html"); } @GetMapping("/all") public @ResponseBody Iterable<Employee> getAllEmployees() { return repository.findAll(); } }
public class Queue { private int[] numbers; private int front; private int rear; private int nElements; private int maxSize; public Queue(int size) { this.maxSize = size; this.numbers = new int[maxSize]; this.nElements = 0; this.front = 0; this.rear = -1; } public void insert(int x) { if (isFull()) { rear = -1; } rear++; numbers[rear] = x; nElements++; } public int remove() { int temp = numbers[front]; front++; if (front == maxSize) { front = 0; } nElements--; return temp; } public int peak() { return numbers[front]; } public boolean isFull() { return this.nElements == maxSize; } public boolean isEmpty() { return this.nElements == 0; } public void view() { System.out.print("["); for (int number : numbers) { System.out.print(number + " "); } System.out.print("]"); } }
package com.qst.dms.ui; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Random; import javax.swing.JLabel; /** * @author 陌意随影 TODO :验证码JLabel *2019年12月21日 上午12:48:29 */ public class CheckCodeLabel extends JLabel { private static final long serialVersionUID = 1L; private static Random random = new Random(); private int width = 60;//验证码的框宽 private int height =25;//验证码的框高 private int font_size = 20;//字体的大小 private int x = 0;//位置x private int y = 0;//位置y private int jam = 5;//干扰元素 建议使用 4~7 之间的数字 private String code = "";//保存验证码 @SuppressWarnings("javadoc") public CheckCodeLabel(){ super("验证码"); this.setPreferredSize(new Dimension(width,height)); this.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { repaint(); } }); } /** * * @return 获得随机颜色 */ public Color getRandomColor() { int R = random.nextInt(255), G = random.nextInt(255), B = random.nextInt(255); return new Color(R, G, B); } /** * 绘画验证码 绘画验证码 * @param g */ public void checkCode(Graphics g) { drawBorder(g); drawCode(g); drawJam(g); } /** * 绘画边框和背景 * @param g */ public void drawBorder(Graphics g) { Color gc = g.getColor(); g.setColor(Color.WHITE); g.fillRect(x, y, width, height); g.setColor(Color.BLACK); g.drawRect(x, y, width, height); g.setColor(gc); } /** * 绘画验证码内容 * @param g */ public void drawCode(Graphics g) { Color c = g.getColor(); g.setFont(new Font("微软雅黑", Font.BOLD, font_size)); char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwsyz0123456789".toCharArray(); int index = 0; int len = ch.length; Random r = new Random(); StringBuffer sb = new StringBuffer(); for(int i = 0;i < 4;i++){ index =r.nextInt(len); g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255))); g.drawString(ch[index]+"", i*12+2, font_size); sb.append(ch[index]); } g.setColor(c); this.code=sb.toString().trim(); } /** * 绘画干扰元素 * @param g */ public void drawJam(Graphics g) { Color gc = g.getColor(); for (int i = 0; i < jam; i++) { g.setColor(getRandomColor()); g.drawLine(x + random.nextInt(width), y + random.nextInt(height), x + random.nextInt(width), y + random.nextInt(height)); } g.setColor(gc); } public void paint(Graphics g) { Color c = g.getColor(); g.drawString("单击可刷新验证码", 30, 50); checkCode(g); g.setColor(c); } /** * @return 返回验证码 */ public String getCode() { return code.trim(); } }
package com.framgia.fsalon.data.source; import com.framgia.fsalon.data.model.CustomerReportResponse; import io.reactivex.Observable; /** * Created by THM on 8/25/2017. */ public interface ReportDataSource { Observable<CustomerReportResponse> getBookingReport(String type, long start, long end); }
package com.yea.loadbalancer; import com.google.common.annotations.VisibleForTesting; import com.netflix.servo.annotations.DataSourceType; import com.netflix.servo.annotations.Monitor; import com.yea.core.loadbalancer.BalancingNode; import com.yea.core.loadbalancer.INodeList; import com.yea.core.loadbalancer.INodeListFilter; import com.yea.core.loadbalancer.INodeListUpdater; import com.yea.core.loadbalancer.IPing; import com.yea.core.loadbalancer.IRule; import com.yea.loadbalancer.config.CommonClientConfigKey; import com.yea.loadbalancer.config.DefaultClientConfigImpl; import com.yea.loadbalancer.config.IClientConfig; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; /** * A LoadBalancer that has the capabilities to obtain the candidate list of * servers using a dynamic source. i.e. The list of servers can potentially be * changed at Runtime. It also contains facilities wherein the list of servers * can be passed through a Filter criteria to filter out servers that do not * meet the desired criteria. * * @author stonse * */ public class DynamicServerListLoadBalancer<T extends BalancingNode> extends BaseLoadBalancer { private static final Logger LOGGER = LoggerFactory.getLogger(DynamicServerListLoadBalancer.class); boolean isSecure = false; boolean useTunnel = false; // to keep track of modification of server lists protected AtomicBoolean serverListUpdateInProgress = new AtomicBoolean(false); volatile INodeList<T> serverListImpl; volatile INodeListFilter<T> filter; protected final INodeListUpdater.UpdateAction updateAction = new INodeListUpdater.UpdateAction() { @Override public void doUpdate() { updateListOfServers(); } }; protected volatile INodeListUpdater serverListUpdater; public DynamicServerListLoadBalancer() { super(); } @Deprecated public DynamicServerListLoadBalancer(IClientConfig clientConfig, IRule rule, IPing ping, INodeList<T> serverList, INodeListFilter<T> filter) { this(clientConfig, rule, ping, serverList, filter, new PollingServerListUpdater()); } public DynamicServerListLoadBalancer(IClientConfig clientConfig, IRule rule, IPing ping, INodeList<T> serverList, INodeListFilter<T> filter, INodeListUpdater serverListUpdater) { super(clientConfig, rule, ping); this.serverListImpl = serverList; this.filter = filter; this.serverListUpdater = serverListUpdater; if (filter instanceof AbstractNodeListFilter) { ((AbstractNodeListFilter) filter).setLoadBalancerStats(getLoadBalancerStats()); } restOfInit(clientConfig); } public DynamicServerListLoadBalancer(IClientConfig clientConfig) { initWithNiwsConfig(clientConfig); } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { try { super.initWithNiwsConfig(clientConfig); String niwsServerListClassName = clientConfig.getPropertyAsString( CommonClientConfigKey.NIWSServerListClassName, DefaultClientConfigImpl.DEFAULT_SEVER_LIST_CLASS); INodeList<T> niwsServerListImpl = (INodeList<T>) ClientFactory .instantiateInstanceWithClientConfig(niwsServerListClassName, clientConfig); this.serverListImpl = niwsServerListImpl; if (niwsServerListImpl instanceof AbstractNodeList) { AbstractNodeListFilter<T> niwsFilter = ((AbstractNodeList) niwsServerListImpl) .getFilterImpl(clientConfig); niwsFilter.setLoadBalancerStats(getLoadBalancerStats()); this.filter = niwsFilter; } String serverListUpdaterClassName = clientConfig.getPropertyAsString( CommonClientConfigKey.ServerListUpdaterClassName, DefaultClientConfigImpl.DEFAULT_SERVER_LIST_UPDATER_CLASS); this.serverListUpdater = (INodeListUpdater) ClientFactory .instantiateInstanceWithClientConfig(serverListUpdaterClassName, clientConfig); restOfInit(clientConfig); } catch (Exception e) { throw new RuntimeException("Exception while initializing NIWSDiscoveryLoadBalancer:" + clientConfig.getClientName() + ", niwsClientConfig:" + clientConfig, e); } } /** * 启动服务列表定时刷新机制,默认通过PollingServerListUpdater来刷新。默认每30秒刷新一次。 * 并且执行一次刷新。 * @param clientConfig */ void restOfInit(IClientConfig clientConfig) { enableAndInitLearnNewServersFeature(); updateListOfServers(); LOGGER.info("DynamicServerListLoadBalancer for client {} initialized: {}", clientConfig.getClientName(), this.toString()); } @Override public void setNodesList(Collection lsrv) { super.setNodesList(lsrv); Collection<T> serverList = (Collection<T>) lsrv; Map<String, Collection<BalancingNode>> serversInZones = new HashMap<String, Collection<BalancingNode>>(); for (BalancingNode server : serverList) { // make sure ServerStats is created to avoid creating them on hot // path getLoadBalancerStats().getSingleServerStat(server); String zone = server.getZone(); if (zone != null) { zone = zone.toLowerCase(); Collection<BalancingNode> servers = serversInZones.get(zone); if (servers == null) { servers = new ArrayList<BalancingNode>(); serversInZones.put(zone, servers); } servers.add(server); } } setServerListForZones(serversInZones); } protected void setServerListForZones(Map<String, Collection<BalancingNode>> zoneServersMap) { LOGGER.debug("Setting server list for zones: {}", zoneServersMap); getLoadBalancerStats().updateZoneServerMapping(zoneServersMap); } public INodeList<T> getServerListImpl() { return serverListImpl; } public void setServerListImpl(INodeList<T> niwsServerList) { this.serverListImpl = niwsServerList; } public INodeListFilter<T> getFilter() { return filter; } public void setFilter(INodeListFilter<T> filter) { this.filter = filter; } @Override /** * Makes no sense to ping an inmemory disc client * */ public void forceQuickPing() { // no-op } /** * Feature that lets us add new instances (from AMIs) to the list of * existing servers that the LB will use Call this method if you want this * feature enabled */ public void enableAndInitLearnNewServersFeature() { LOGGER.info("Using serverListUpdater {}", serverListUpdater.getClass().getSimpleName()); serverListUpdater.start(updateAction); } private String getIdentifier() { return this.getClientConfig().getClientName(); } public void stopServerListRefreshing() { if (serverListUpdater != null) { serverListUpdater.stop(); } } /** * 通过INodeList获得服务器列表,设置到负载均衡列表内 */ @VisibleForTesting public void updateListOfServers() { Collection<T> servers = new ArrayList<T>(); if (serverListImpl != null) { servers = serverListImpl.getUpdatedListOfNodes(); LOGGER.debug("List of Servers for {} obtained from Discovery client: {}", getIdentifier(), servers); if (filter != null) { servers = filter.getFilteredListOfNodes(servers); LOGGER.debug("Filtered List of Servers for {} obtained from Discovery client: {}", getIdentifier(), servers); } } updateAllServerList(servers); } /** * Update the AllServer list in the LoadBalancer if necessary and enabled * * @param ls */ protected void updateAllServerList(Collection<T> ls) { // other threads might be doing this - in which case, we pass if (serverListUpdateInProgress.compareAndSet(false, true)) { try { setNodesList(ls); super.forceQuickPing(); } finally { serverListUpdateInProgress.set(false); } } } @Override public String toString() { StringBuilder sb = new StringBuilder("DynamicServerListLoadBalancer:"); sb.append(super.toString()); sb.append("ServerList:" + String.valueOf(serverListImpl)); return sb.toString(); } @Override public void shutdown() { super.shutdown(); stopServerListRefreshing(); } @Monitor(name = "LastUpdated", type = DataSourceType.INFORMATIONAL) public String getLastUpdate() { return serverListUpdater.getLastUpdate(); } @Monitor(name = "DurationSinceLastUpdateMs", type = DataSourceType.GAUGE) public long getDurationSinceLastUpdateMs() { return serverListUpdater.getDurationSinceLastUpdateMs(); } @Monitor(name = "NumUpdateCyclesMissed", type = DataSourceType.GAUGE) public int getNumberMissedCycles() { return serverListUpdater.getNumberMissedCycles(); } @Monitor(name = "NumThreads", type = DataSourceType.GAUGE) public int getCoreThreads() { return serverListUpdater.getCoreThreads(); } }
package com.moviee.moviee.activities; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.view.KeyEvent; import android.view.WindowManager; import android.widget.ImageView; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import com.github.javiersantos.appupdater.AppUpdater; import com.moviee.moviee.Interfaces.ServiceCallback; import com.moviee.moviee.R; import com.moviee.moviee.activities.base.AdActivity; import com.moviee.moviee.adapters.base.BaseViewPagerAdapter; import com.moviee.moviee.fragments.HomeFragment; import com.moviee.moviee.fragments.LikeFragment; import com.moviee.moviee.fragments.SearchFragment; import com.moviee.moviee.fragments.SuggestFragment; import com.moviee.moviee.fragments.base.BaseTabFragment; import com.moviee.moviee.receivers.NotificationEventReceiver; import com.moviee.moviee.services.NotificationIntentService; import com.moviee.moviee.services.TheMovieDB; import com.moviee.moviee.utilities.Pref; import com.supersonic.mediationsdk.sdk.Supersonic; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; public class MainActivity extends AdActivity { @BindView(R.id.mainViewPager) ViewPager mMainViewPager; @BindView(R.id.tabLayout) TabLayout mTabLayout; private int lastSelectedPage = 1; private BaseViewPagerAdapter<BaseTabFragment> adapter; //Save in memory the 3 main fragments Supersonic mediationAgent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_main); ButterKnife.bind(this); SharedPreferences prefss = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); if(!prefss.contains("installDateO")) { Calendar c = Calendar.getInstance(); SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy"); prefss.edit().putString("installDateO", df.format(c.getTime())).commit(); } if(prefss.getBoolean("isFirst", false)) { showAd(); } else { prefss.edit().putBoolean("isFirst", true).apply(); } //Just start the IntentService for films notification if it's not already started if(!isMyServiceRunning(NotificationIntentService.class)){ if(Pref.loadBoolean(this, "pref", "setting_notification")){ NotificationEventReceiver.setupAlarm(getApplicationContext()); } } if(!Pref.keyExist(this, "pref", "setting_notification")) Pref.saveBoolean(this, "pref", "setting_notification", true); Pref.incrementNumber(this, "pref", "appOpened"); if(Pref.loadInt(this, "pref", "appOpened") == 4 || Pref.loadInt(this, "pref", "appOpened") == 12){ if(!Pref.loadBoolean(this, "pref", "hasAlreadyVoted")) { boolean wrapInScrollView = true; new MaterialDialog.Builder(this) .title(R.string.rate_dialog_title) .customView(R.layout.rate_dialog_view, wrapInScrollView) .positiveText(R.string.positive) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { String playStoreUrl = "https://play.google.com/store/apps/details?id=com.moviee.moviee"; Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(playStoreUrl)); startActivity(intent); Pref.saveBoolean(MainActivity.this, "pref", "hasAlreadyVoted", true); } }) .show(); } } final BaseTabFragment[] mainFragments = new BaseTabFragment[]{ new HomeFragment(), new LikeFragment(), new SearchFragment(), new SuggestFragment() }; SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); if(!prefs.contains("genres")) new TheMovieDB(new ServiceCallback() { @Override public void onResponse(List list) { // it saves the genres } }, getApplicationContext()).getGenreList(); adapter = new BaseViewPagerAdapter(getSupportFragmentManager(), mainFragments[0], mainFragments[1], mainFragments[2], mainFragments[3]); //Set the adapter for the viewpager mMainViewPager.setAdapter(adapter); //Connect ViewPager with tabLayout mTabLayout.setupWithViewPager(mMainViewPager); for(int i = 0; i < mainFragments.length; i++) { mTabLayout.getTabAt(i).setCustomView(R.layout.tab_custom_view); ((ImageView) mTabLayout.getTabAt(i).getCustomView().findViewById(R.id.icon)).setImageResource(mainFragments[i].getIconRes()); } ((ImageView) mTabLayout.getTabAt(0).getCustomView().findViewById(R.id.icon)).setImageResource(mainFragments[0].getActiveIconRes()); lastSelectedPage = 0; mMainViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { //Change color of the previews selected tab ((ImageView) mTabLayout.getTabAt(lastSelectedPage).getCustomView().findViewById(R.id.icon)).setImageResource(mainFragments[lastSelectedPage].getIconRes()); //Change color of the selected icon ((ImageView) mTabLayout.getTabAt(position).getCustomView().findViewById(R.id.icon)).setImageResource(mainFragments[position].getActiveIconRes()); lastSelectedPage = position; } @Override public void onPageScrollStateChanged(int state) { } }); AppUpdater appUpdater = new AppUpdater(this); appUpdater.start(); //Center tab as default mMainViewPager.setCurrentItem(0); mMainViewPager.setOffscreenPageLimit(3); } public BaseTabFragment getFragmentAt(int position){ return adapter.getRegisteredFragment(position); } public void fadeOutToolbar(){ mTabLayout.animate() .alpha(0f) .setDuration(200) .start(); } // Before 2.0 @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { moveTaskToBack(true); return true; } return super.onKeyDown(keyCode, event); } private boolean isMyServiceRunning(Class<?> serviceClass) { ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (serviceClass.getName().equals(service.service.getClassName())) { return true; } } return false; } @Override public void onBackPressed() { // If an interstitial is on screen, close it. moveTaskToBack(true); } }
package com.example.hante.newprojectsum.sqlite; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * 数据库操作 */ public class DBHelper extends SQLiteOpenHelper{ public static final String DATEBASE_NAME = "New.db"; public static final int DATEBASE_VERSION = 1; //TYPE: private static final String TEXT_TYPE = " TEXT"; private static final String NUMBER_TYPE = " INTEGER"; private static final String LONG_TYPE = " LONG"; private static final String COMMA_SEP = ","; private static final String USER_SQL = "CREATE TABLE IF NOT EXISTS " + DBEntry.UserTable.TABLE_NAME + " (" + DBEntry.UserTable._ID + NUMBER_TYPE + " PRIMARY KEY AUTOINCREMENT, " + DBEntry.UserTable.USER_NAME + TEXT_TYPE + COMMA_SEP + DBEntry.UserTable.USER_PASSWORD + TEXT_TYPE + COMMA_SEP + DBEntry.UserTable.USER_EMAIL + TEXT_TYPE + " )"; private static final String REMIND_SQL = "CREATE TABLE IF NOT EXISTS " + DBEntry.RemindTable.TABLE_NAME + " (" + DBEntry.RemindTable._ID + NUMBER_TYPE + " PRIMARY KEY AUTOINCREMENT, " + DBEntry.RemindTable.REMIND_TITLE + TEXT_TYPE + COMMA_SEP + DBEntry.RemindTable.REMIND_CONTENT + TEXT_TYPE + COMMA_SEP + DBEntry.RemindTable.REMIND_DATA + LONG_TYPE + " )"; public DBHelper (Context context) { super(context, DATEBASE_NAME, null, DATEBASE_VERSION); } @Override public void onCreate (SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL(USER_SQL); sqLiteDatabase.execSQL(REMIND_SQL); } @Override public void onUpgrade (SQLiteDatabase sqLiteDatabase, int i, int i1) { } }
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.expression.spel.testresources; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import org.springframework.util.ObjectUtils; ///CLOVER:OFF @SuppressWarnings("unused") public class Inventor { private String name; public String _name; public String _name_; public String publicName; private PlaceOfBirth placeOfBirth; private Date birthdate; private int sinNumber; private String nationality; private String[] inventions; public String randomField; public Map<String,String> testMap; private boolean wonNobelPrize; private PlaceOfBirth[] placesLived; private List<PlaceOfBirth> placesLivedList = new ArrayList<>(); public ArrayContainer arrayContainer; public boolean publicBoolean; private boolean accessedThroughGetSet; public List<Integer> listOfInteger = new ArrayList<>(); public List<Boolean> booleanList = new ArrayList<>(); public Map<String,Boolean> mapOfStringToBoolean = new LinkedHashMap<>(); public Map<Integer,String> mapOfNumbersUpToTen = new LinkedHashMap<>(); public List<Integer> listOfNumbersUpToTen = new ArrayList<>(); public List<Integer> listOneFive = new ArrayList<>(); public String[] stringArrayOfThreeItems = new String[]{"1","2","3"}; private String foo; public int counter; public Inventor(String name, Date birthdate, String nationality) { this.name = name; this._name = name; this._name_ = name; this.birthdate = birthdate; this.nationality = nationality; this.arrayContainer = new ArrayContainer(); testMap = new HashMap<>(); testMap.put("monday", "montag"); testMap.put("tuesday", "dienstag"); testMap.put("wednesday", "mittwoch"); testMap.put("thursday", "donnerstag"); testMap.put("friday", "freitag"); testMap.put("saturday", "samstag"); testMap.put("sunday", "sonntag"); listOneFive.add(1); listOneFive.add(5); booleanList.add(false); booleanList.add(false); listOfNumbersUpToTen.add(1); listOfNumbersUpToTen.add(2); listOfNumbersUpToTen.add(3); listOfNumbersUpToTen.add(4); listOfNumbersUpToTen.add(5); listOfNumbersUpToTen.add(6); listOfNumbersUpToTen.add(7); listOfNumbersUpToTen.add(8); listOfNumbersUpToTen.add(9); listOfNumbersUpToTen.add(10); mapOfNumbersUpToTen.put(1,"one"); mapOfNumbersUpToTen.put(2,"two"); mapOfNumbersUpToTen.put(3,"three"); mapOfNumbersUpToTen.put(4,"four"); mapOfNumbersUpToTen.put(5,"five"); mapOfNumbersUpToTen.put(6,"six"); mapOfNumbersUpToTen.put(7,"seven"); mapOfNumbersUpToTen.put(8,"eight"); mapOfNumbersUpToTen.put(9,"nine"); mapOfNumbersUpToTen.put(10,"ten"); } public void setPlaceOfBirth(PlaceOfBirth placeOfBirth2) { placeOfBirth = placeOfBirth2; this.placesLived = new PlaceOfBirth[] { placeOfBirth2 }; this.placesLivedList.add(placeOfBirth2); } public String[] getInventions() { return inventions; } public void setInventions(String[] inventions) { this.inventions = inventions; } public PlaceOfBirth getPlaceOfBirth() { return placeOfBirth; } public int throwException(int valueIn) throws Exception { counter++; if (valueIn==1) { throw new IllegalArgumentException("IllegalArgumentException for 1"); } if (valueIn==2) { throw new RuntimeException("RuntimeException for 2"); } if (valueIn==4) { throw new TestException(); } return valueIn; } @SuppressWarnings("serial") static class TestException extends Exception {} public String throwException(PlaceOfBirth pob) { return pob.getCity(); } public String getName() { return name; } public boolean getWonNobelPrize() { return wonNobelPrize; } public void setWonNobelPrize(boolean wonNobelPrize) { this.wonNobelPrize = wonNobelPrize; } public PlaceOfBirth[] getPlacesLived() { return placesLived; } public void setPlacesLived(PlaceOfBirth[] placesLived) { this.placesLived = placesLived; } public List<PlaceOfBirth> getPlacesLivedList() { return placesLivedList; } public void setPlacesLivedList(List<PlaceOfBirth> placesLivedList) { this.placesLivedList = placesLivedList; } public String echo(Object o) { return o.toString(); } public String sayHelloTo(String person) { return "hello " + person; } public String printDouble(Double d) { return d.toString(); } public String printDoubles(double[] d) { return ObjectUtils.nullSafeToString(d); } public List<String> getDoublesAsStringList() { List<String> result = new ArrayList<>(); result.add("14.35"); result.add("15.45"); return result; } public String joinThreeStrings(String a, String b, String c) { return a + b + c; } public String aVarargsMethod(String... strings) { return Arrays.toString(strings); } public String aVarargsMethod2(int i, String... strings) { return String.valueOf(i) + "-" + Arrays.toString(strings); } @SuppressWarnings("unchecked") public String optionalVarargsMethod(Optional<String>... values) { return Arrays.toString(values); } public String aVarargsMethod3(String str1, String... strings) { if (ObjectUtils.isEmpty(strings)) { return str1; } return str1 + "-" + String.join("-", strings); } public Inventor(String... strings) { } public boolean getSomeProperty() { return accessedThroughGetSet; } public void setSomeProperty(boolean b) { this.accessedThroughGetSet = b; } public Date getBirthdate() { return birthdate;} public String getFoo() { return foo; } public void setFoo(String s) { foo = s; } public String getNationality() { return nationality; } }
package com.proba.proba12.services; import com.proba.proba12.models.Country; import com.proba.proba12.repositories.CountryRepository; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.RequestBody; import java.util.List; @Service public class CountryService { private final CountryRepository countryRepository; public CountryService(CountryRepository countryRepository) { this.countryRepository = countryRepository; } public void addCountry(Country country) { countryRepository.save(country); } public List<Country> getCountries(){ return countryRepository.findAll(); } }
package br.com.fitNet.controller; import java.sql.SQLException; import java.util.Set; 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.servlet.ModelAndView; import br.com.fitNet.model.Instrutor; import br.com.fitNet.model.Treino; import br.com.fitNet.model.exception.TreinoInvalidoException; import br.com.fitNet.model.service.RegrasInstrutorServeice; //import org.springframework.web.servlet.ModelAndView; import br.com.fitNet.model.service.RegrasTreinoServeice; import br.com.fitNet.util.Mensagens; @Controller public class TreinoController { @Autowired RegrasTreinoServeice regraTreino; @Autowired RegrasInstrutorServeice regraIntrutor; Mensagens msg = new Mensagens(); @RequestMapping("areaClienteTreino") public ModelAndView execAreaClienteTreino(){ try { Set<Instrutor>listaInstrutores = regraIntrutor.consultarInstrutor(); ModelAndView modelo = new ModelAndView("cliente/areaClienteTreino"); modelo.addObject("listaInstrutores", listaInstrutores); return modelo; } catch (SQLException e) { msg.setMensagemErro("Erro ao Carregar Lista de Instrutor: "+e.getMessage()); return execMensagens(msg); } } @RequestMapping("adicionaTreino") public String execInserirTreino(Treino treino) { try { regraTreino.incluir(treino); } catch (TreinoInvalidoException | SQLException e) { System.out.println("cheguei!!!cath inserir"+e.getMessage()); e.printStackTrace(); } return "redirect:listarTreino"; } @RequestMapping("listarTreino") public String execListarTreino(Model modelo) { try { Set<Treino> listaDeTreinosConsultado; listaDeTreinosConsultado = regraTreino.consultar(); modelo.addAttribute("listaTreino", listaDeTreinosConsultado); } catch (SQLException e) { System.out.println("cheguei!!!cath inserir"+e.getMessage()); e.printStackTrace(); } return "cliente/areaDoClienteTreino"; } @RequestMapping("removerTreino") public String execRemoverTreino(Treino treino) { try { regraTreino.remover(treino); } catch (SQLException e) { System.out.println("cheguei!!!cath inserir"+e.getMessage()); e.printStackTrace(); } return "redirect:listarTreino"; } @RequestMapping("alteraTreino") public String execAlterarTreino(Treino treino) { try { regraTreino.remover(treino); } catch (SQLException e) { System.out.println("cheguei!!!cath inserir"+e.getMessage()); e.printStackTrace(); } return "redirect:listarTreino"; } //Mensagens Treino @RequestMapping("mostraMensagemTreino") public ModelAndView execMensagens(){ String paginaMensagem = ""; if(!msg.getMensagemSucesso().equals("")){ paginaMensagem = "/mensagemSucesso"; }else{ paginaMensagem = "/mensagemErro"; } ModelAndView modelo = new ModelAndView(paginaMensagem); modelo.addObject("msg", msg); return modelo; } //Fim Mensagens Treinos public ModelAndView execMensagens(Mensagens msg){ String paginaMensagem = ""; if(!msg.getMensagemSucesso().equals("")){ paginaMensagem = "/mensagemSucesso"; }else{ paginaMensagem = "/mensagemErro"; } ModelAndView modelo = new ModelAndView(paginaMensagem); modelo.addObject("msg", msg); return modelo; } public void execCarregaEspecialidadesInstrutor(int id){ } }
package com.ufc.br.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Instrumento { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String nome; private String tipo; private int quant; private float preco; public int getQuant() { return quant; } public void setQuant(int quant) { this.quant = quant; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getTipo() { return tipo; } public void setTipo(String tipo) { this.tipo = tipo; } public float getPreco() { return preco; } public void setPreco(float preco) { this.preco = preco; } }
/* * 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 Controller; import java.sql.*; import java.util.ArrayList; import java.util.List; import DB.DBConnection; import Model.Donation; /** * * @author MikyalN */ public class DonationDAO { static Connection conn; static PreparedStatement ps; static ResultSet rs; static String sql; public static int save(Donation d) { int status = 0; try { conn = new DBConnection().setConnection(); ps = conn.prepareStatement("insert into tbl_donasi(namaD,emailD,jumlahD,metodeD,pesanD) values(?,?,?,?,?)"); if ("on".equals(d.getAnonD())){ ps.setString(1, "Hamba Allah (Anonymous)"); ps.setString(2, d.getEmailD()); ps.setInt(3, d.getJumlahD()); ps.setString(4, d.getMetodeD()); ps.setString(5, d.getPesanD()); } else { ps.setString(1, d.getNamaD()); ps.setString(2, d.getEmailD()); ps.setInt(3, d.getJumlahD()); ps.setString(4, d.getMetodeD()); ps.setString(5, d.getPesanD()); } status = ps.executeUpdate(); } catch (Exception e) { System.out.println(e); } return status; } public static int update(Donation d) { int status = 0; try { conn = new DBConnection().setConnection(); ps = conn.prepareStatement("update tbl_donasi set namaD=?,emailD=?,jumlahD=?,metodeD=?,pesanD=? where idD=?"); ps.setString(1, d.getNamaD()); ps.setString(2, d.getEmailD()); ps.setInt(3, d.getJumlahD()); ps.setString(4, d.getMetodeD()); ps.setString(5, d.getPesanD()); ps.setInt(6, d.getIdD()); status = ps.executeUpdate(); } catch (Exception e) { System.out.println(e); } return status; } public static int delete(Donation d) { int status = 0; try { conn = new DBConnection().setConnection(); ps = conn.prepareStatement("delete from tbl_donasi where idD=?"); ps.setInt(1, d.getIdD()); status = ps.executeUpdate(); } catch (Exception e) { System.out.println(e); } return status; } public static List<Donation> getAllRecords() { List<Donation> list = new ArrayList<Donation>(); try { conn = new DBConnection().setConnection(); ps = conn.prepareStatement("select * from tbl_donasi"); ResultSet rs = ps.executeQuery(); while (rs.next()) { Donation u = new Donation(); u.setIdD(rs.getInt("idD")); u.setNamaD(rs.getString("namaD")); u.setEmailD(rs.getString("emailD")); u.setJumlahD(rs.getInt("jumlahD")); u.setMetodeD(rs.getString("metodeD")); u.setPesanD(rs.getString("pesanD")); list.add(u); } } catch (Exception e) { System.out.println(e); } return list; } public static List<Donation> getReversedAllRecords() { List<Donation> list = new ArrayList<Donation>(); try { conn = new DBConnection().setConnection(); ps = conn.prepareStatement("select * from tbl_donasi ORDER BY idD DESC"); ResultSet rs = ps.executeQuery(); while (rs.next()) { Donation u = new Donation(); u.setIdD(rs.getInt("idD")); u.setNamaD(rs.getString("namaD")); u.setEmailD(rs.getString("emailD")); u.setJumlahD(rs.getInt("jumlahD")); u.setMetodeD(rs.getString("metodeD")); u.setPesanD(rs.getString("pesanD")); list.add(u); } } catch (Exception e) { System.out.println(e); } return list; } public static Donation getRecordByIdD(int idD) { Donation u = null; try { conn = new DBConnection().setConnection(); ps = conn.prepareStatement("select * from tbl_donasi where idD=?"); ps.setInt(1, idD); ResultSet rs = ps.executeQuery(); while (rs.next()) { u.setIdD(rs.getInt("idD")); u.setNamaD(rs.getString("namaD")); u.setEmailD(rs.getString("emailD")); u.setJumlahD(rs.getInt("jumlahD")); u.setMetodeD(rs.getString("metodeD")); u.setPesanD(rs.getString("pesanD")); } } catch (Exception e) { System.out.println(e); } return u; } public static int getTotalDonations() { int total = 0; try { conn = new DBConnection().setConnection(); ps = conn.prepareStatement("SELECT SUM(jumlahD) from tbl_donasi"); ResultSet rs = ps.executeQuery(); rs.next(); total = rs.getInt(1); } catch (Exception e) { System.out.println(e); } return total; } }
/** * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved. */ package com.thinkgem.jeesite.modules.cms.web; import java.io.File; import java.net.URLEncoder; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.cloudinte.common.utils.CmsIndexDao; import com.cloudinte.common.utils.CreateHtml; import com.cloudinte.modules.xingzhengguanli.utils.JspToPdf; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.thinkgem.jeesite.common.mapper.JsonMapper; import com.thinkgem.jeesite.common.mapper.ResponseObject; import com.thinkgem.jeesite.common.persistence.Page; import com.thinkgem.jeesite.common.utils.CacheUtils; import com.thinkgem.jeesite.common.utils.Collections3; import com.thinkgem.jeesite.common.utils.FileUtils; import com.thinkgem.jeesite.common.utils.StringUtils; import com.thinkgem.jeesite.common.web.BaseController; import com.thinkgem.jeesite.common.web.Servlets; import com.thinkgem.jeesite.modules.cms.entity.Article; import com.thinkgem.jeesite.modules.cms.entity.ArticleData; import com.thinkgem.jeesite.modules.cms.entity.Category; import com.thinkgem.jeesite.modules.cms.entity.Site; import com.thinkgem.jeesite.modules.cms.service.ArticleDataService; import com.thinkgem.jeesite.modules.cms.service.ArticleService; import com.thinkgem.jeesite.modules.cms.service.CategoryService; import com.thinkgem.jeesite.modules.cms.service.FileTplService; import com.thinkgem.jeesite.modules.cms.service.SiteService; import com.thinkgem.jeesite.modules.cms.utils.TplUtils; import com.thinkgem.jeesite.modules.sys.entity.User; import com.thinkgem.jeesite.modules.sys.utils.SettingsUtils; import com.thinkgem.jeesite.modules.sys.utils.UserUtils; /** * 文章Controller * * @author ThinkGem * @version 2013-3-23 */ @Controller @RequestMapping(value = "${adminPath}/cms/article") public class ArticleController extends BaseController { @Autowired private ArticleService articleService; @Autowired private ArticleDataService articleDataService; @Autowired private CategoryService categoryService; @Autowired private FileTplService fileTplService; @Autowired private SiteService siteService; @Autowired private CmsIndexDao cmsIndexDao; @ModelAttribute public Article get(@RequestParam(required = false) String id) { if (StringUtils.isNotBlank(id)) { return articleService.get(id); } else { return new Article(); } } @RequiresPermissions("cms:article:view") @RequestMapping(value = { "list", "" }) public String list(Article article, HttpServletRequest request, HttpServletResponse response, Model model) { User opUser = UserUtils.getUser(); if("6".equals(opUser.getUserType())){//科室 article.setCreateBy(opUser); } Page<Article> page = articleService.findPage(new Page<Article>(request, response), article, true); model.addAttribute("page", page); setBase64EncodedQueryStringToEntity(request, article); model.addAttribute("categoryId", article.getCategory() != null ? article.getCategory().getId() : ""); model.addAttribute("ename", "article"); return "modules/cms/articleList"; } @RequiresPermissions("cms:article:view") @RequestMapping(value = "form") public String form(Article article, Model model) { // 关于页面初始化时,栏目选择框的勾选显示逻辑: // 1、修改文章的时候,勾选文章所属的栏目,有几个栏目就勾选几个。 // 2、添加文章的时候,如果参数携带了栏目id,且携带的栏目id对应数据库中存在,则勾选这个栏目;如果未携带栏目id或携带的栏目id对应数据库中不存在这个栏目,不勾选任何栏目。 Category category = article.getCategory(); // 如果当前传参有子节点,则选择取消传参选择。即:只有叶子节点栏目下才能有文章 if (category != null && StringUtils.isNotBlank(category.getId())) { List<Category> list = categoryService.findByParentId(category.getId(), Site.getCurrentSiteId()); if (list.size() > 0) { // 非叶子节点栏目 //article.setCategory(null); article.setCategory(new Category()); // 将栏目置空(无id无name) } else { category = categoryService.get(category); // 根据id获取更详细的栏目信息 if (category == null) {// 此栏目不存在 category = new Category(); } article.setCategory(category); } } // 文章所属栏目集合。 List<Category> categoryList; // 添加 if (StringUtils.isBlank(article.getId())) { // 如果指定了栏目,所属栏目集合即为此栏目 if (article.getCategory() != null && StringUtils.isNotBlank(article.getCategory().getId())) { categoryList = Lists.newArrayList(article.getCategory()); } else { categoryList = Lists.newArrayList(); } } // 修改 else { // 获取其所属栏目集合 categoryList = categoryService.findCategoryByArticle(article.getId()); } // 构建栏目选择框ztree的数据 List<String> categoryIdList = Lists.newArrayList(); List<String> categoryNameList = Lists.newArrayList(); if (!Collections3.isEmpty(categoryList)) { for (Category c : categoryList) { categoryIdList.add(c.getId()); categoryNameList.add(c.getName()); } } // 文章所属栏目id,多个以英文隔开 String categoryId = StringUtils.join(categoryIdList, ","); // 文章所属栏目name,多个以英文隔开 String categoryName = StringUtils.join(categoryNameList, ","); model.addAttribute("categoryId", categoryId); model.addAttribute("categoryName", categoryName); // 修改时,拉取文章副表内容 if (StringUtils.isNotBlank(article.getId())) { article.setArticleData(articleDataService.get(article.getId())); } // model.addAttribute("contentViewList", getTplContent()); model.addAttribute("article_DEFAULT_TEMPLATE", Article.DEFAULT_TEMPLATE); model.addAttribute("article", article); //CmsUtils.addViewConfigAttribute(model, article.getCategory()); model.addAttribute("ename", "article"); logger.debug("添加内容,栏目 article.getCategory().getId() ====>{}", article.getCategory()); if(article.getCategory().getId().equals(SettingsUtils.getSysConfig("red.file.id", "1f3508110a4d449180f163f1ef3d979c"))){ if(StringUtils.isBlank(article.getId())){ long count = articleService.findCount(article); String code = String.valueOf(count+1); article.setCode(code); } return "modules/cms/redFileForm"; } return "modules/cms/articleForm"; } @RequestMapping(value = "showRedFile") public String showRedFile(Article article, Model model,HttpServletRequest request,HttpServletResponse response) { if (StringUtils.isNotBlank(article.getId())) { article.setArticleData(articleDataService.get(article.getId())); } model.addAttribute("article", article); return "modules/cms/showRedFile"; } @RequestMapping(value = "createRedFile") public String createRedFile(Article article, Model model,HttpServletRequest request,HttpServletResponse response) { // 修改时,拉取文章副表内容 if (StringUtils.isNotBlank(article.getId())) { ArticleData articleDate = articleDataService.get(article.getId()); if(articleDate != null && StringUtils.isNotBlank(articleDate.getContent())){ String content = articleDate.getContent(); articleDate.setContent(content.replace("黑体", "simhei")); article.setArticleData(articleDate); } //article.setArticleData(articleDataService.get(article.getId())); } String path1 = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + (80 == request.getServerPort() ? "" : ":" + request.getServerPort()) + path1; String image = basePath+ "/static/images/timg.jpg"; Map<String, Object> map = Maps.newConcurrentMap(); map.put("article", article); String templateFile = "/WEB-INF/classes/templates/modules/pdf/applyPdf.html"; String filename = StringEscapeUtils.unescapeHtml4(article.getTitle()); String encodedFilename = null; String userAgent = request.getHeader("User-Agent"); boolean ifIE = userAgent.contains("MSIE") || userAgent.contains("Trident"); // 针对IE或者以IE为内核的浏览器: try { if (ifIE) { encodedFilename = URLEncoder.encode(filename, "UTF-8"); } else { // 非IE浏览器的处理: encodedFilename = new String(filename.getBytes("UTF-8"), "ISO-8859-1"); } response.setContentType("multipart/form-data"); response.setHeader("Content-Disposition", "attachment;filename=" + encodedFilename + ".pdf"); String path = request.getSession().getServletContext().getRealPath("/"); String filePath = path +"upload"+File.separator +"redFile"+File.separator + filename + ".pdf"; File file = new File(filePath); logger.debug("创建文件 : {}", filePath); // 指定font String simsunfontPath = Servlets.getRealPath(request, "/WEB-INF/classes/fonts/simsun.ttf"); String fasongfontPath = Servlets.getRealPath(request, "/WEB-INF/classes/fonts/仿宋_GB2312.ttf"); String simheifontPath = Servlets.getRealPath(request, "/WEB-INF/classes/fonts/simhei.ttf"); String calibrifontPath = Servlets.getRealPath(request, "/WEB-INF/classes/fonts/calibri.ttf"); JspToPdf.fontPath = new String[] { simsunfontPath,fasongfontPath,simheifontPath,calibrifontPath }; JspToPdf.exportToFile(filePath, Servlets.getRealPath(request, templateFile), map); // 输出文件 logger.debug("输出文件 : {}", filePath); FileUtils.copyFile(file, response.getOutputStream()); } catch (Exception e) { e.printStackTrace(); } return null; } @RequiresPermissions("cms:article:edit") @RequestMapping(value = "save") public String save(Article article, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) { if (!beanValidator(model, article)) { return form(article, model); } List<String> categoryIdList = Arrays.asList(article.getCategory().getId().split(",")); if (!Collections3.isEmpty(categoryIdList)) { article.setCategory(new Category(categoryIdList.get(0))); article.setCategoryIdList(categoryIdList); articleService.save(article); onArticleSaveOrUpdate(article); } // CacheUtils.removeAll("cmsCache"); String categoryId = Collections3.isEmpty(categoryIdList) ? null : categoryIdList.get(0); addMessage(redirectAttributes, "保存文章'" + StringUtils.abbr(article.getTitle(), 50) + "'成功"); return "redirect:" + adminPath + "/cms/?repage&module=article&category.id=" + (categoryId != null ? categoryId : ""); } @RequiresPermissions("cms:article:edit") @RequestMapping(value = "delete") public String delete(Article article, String categoryId, @RequestParam(required = false) Boolean isRe, RedirectAttributes redirectAttributes) { // 如果没有审核权限,则不允许删除或发布。 if (!UserUtils.getSubject().isPermitted("cms:article:audit")) { addMessage(redirectAttributes, "你没有删除或发布权限"); } articleService.delete(article); onArticleDelete(article); CacheUtils.removeAll("cmsCache"); addMessage(redirectAttributes, (isRe != null && isRe ? "发布" : "删除") + "文章成功"); //return "redirect:" + adminPath + "/cms/article/?repage&category.id=" + (categoryId != null ? categoryId : ""); return "redirect:" + adminPath + "/cms/article/?repage&" + getBase64DecodedQueryStringFromEntity(article); } private void onArticleSaveOrUpdate(final Article article) { final String basePathWithoutContextPath = Servlets.getBasePathWithoutContextPath(); final String basePath = Servlets.getBasePath(); final String baseDir = Servlets.getRealPath(SettingsUtils.getSysConfig("cms.static.baseDir", "/s")); new Thread(new Runnable() { @Override public void run() { try { // 索引 if (StringUtils.isBlank(article.getId())) { cmsIndexDao.save(article); } else { cmsIndexDao.update(article); } // 静态化:本文章、文章所在栏目、首页 if (SettingsUtils.getSysConfig("cms.static", false)) { CreateHtml.staticArticle(article, basePathWithoutContextPath, baseDir); CreateHtml.staticCategory(categoryService.get(article.getCategory()), basePathWithoutContextPath, baseDir); CreateHtml.staticIndex(basePath, baseDir); } } catch (Exception e) { e.printStackTrace(); } } }).start(); } private void onArticleDelete(final Article article) { final String basePathWithoutContextPath = Servlets.getBasePathWithoutContextPath(); final String basePath = Servlets.getBasePath(); final String baseDir = Servlets.getRealPath(SettingsUtils.getSysConfig("cms.static.baseDir", "/s")); new Thread(new Runnable() { @Override public void run() { try { // 索引 cmsIndexDao.delete(article.getId(), "article"); // 静态化 if (SettingsUtils.getSysConfig("cms.static", false)) { // 删除生成的html文件 FileUtils.deleteFile(baseDir + File.separator + article.getCategory().getId() + File.separator + "view-" + article.getId() + ".html"); CreateHtml.staticCategory(categoryService.get(article.getCategory()), basePathWithoutContextPath, baseDir); CreateHtml.staticIndex(basePath, baseDir); } } catch (Exception e) { e.printStackTrace(); } } }).start(); } /** * 文章选择列表 */ @RequiresPermissions("cms:article:view") @RequestMapping(value = "selectList") public String selectList(Article article, HttpServletRequest request, HttpServletResponse response, Model model) { list(article, request, response, model); return "modules/cms/articleSelectList"; } /** * 通过编号获取文章标题 */ @RequiresPermissions("cms:article:view") @ResponseBody @RequestMapping(value = "findByIds") public String findByIds(String ids) { List<Object[]> list = articleService.findByIds(ids); return JsonMapper.nonDefaultMapper().toJson(list); } private List<String> getTplContent() { List<String> tplList = fileTplService.getNameListByPrefix(siteService.get(Site.getCurrentSiteId()).getSolutionPath()); tplList = TplUtils.tplTrim(tplList, Article.DEFAULT_TEMPLATE, ""); return tplList; } /** * 生成指定文章的索引 */ @RequiresPermissions("cms:article:edit") @RequestMapping(value = "doIndex") @ResponseBody public ResponseObject doIndex(Article article) { try { cmsIndexDao.update(article); return ResponseObject.success().msg("生成索引成功"); } catch (Exception e) { e.printStackTrace(); return ResponseObject.failure().msg("生成索引失败"); } } /** * 生成指定文章的索引 */ @RequiresPermissions("cms:article:edit") @RequestMapping(value = "doIndexByIds") @ResponseBody public ResponseObject doIndexByIds(Article article) { List<Article> list = Lists.newArrayList(); for (String id : article.getIds()) { list.add(articleService.get(id)); } return index(list); } /** * 生成栏目下文章的索引 */ @RequiresPermissions("cms:article:edit") @RequestMapping(value = "doIndexByCatetory") @ResponseBody public ResponseObject doIndexByCatetory(Article article) { List<Article> list = null; Category category = article.getCategory(); if (category != null && !StringUtils.isBlank(category.getId())) { list = articleService.findList(article); } else { list = Lists.newArrayList(); } return index(list); } /** * 生成全部文章的索引 */ @RequiresPermissions("cms:article:edit") @RequestMapping(value = "doIndexAll") @ResponseBody public ResponseObject doIndexAll(Article article) { if (article.getCategory() == null) { article.setCategory(new Category()); } List<Article> list = articleService.findList(article); return index(list); } private ResponseObject index(List<Article> list) { try { for (Article a : list) { cmsIndexDao.update(a); } return ResponseObject.success().msg("生成索引成功,共【" + (list == null ? 0 : list.size()) + "】篇文章。"); } catch (Exception e) { e.printStackTrace(); return ResponseObject.failure().msg("生成索引失败"); } } /** * 全部静态化 */ @RequiresPermissions("cms:article:edit") @RequestMapping(value = "staticAll") @ResponseBody public ResponseObject staticAll(HttpServletRequest request) { try { //首页 CreateHtml.staticIndex(request); //栏目 Category category = new Category(); //category.setInList(Global.SHOW); staticCategoryAndArticle(categoryService.findList(category), request); return ResponseObject.success().msg("全部静态化成功"); } catch (Exception e) { e.printStackTrace(); return ResponseObject.failure().msg("全部静态化失败"); } } private void staticCategoryAndArticle(List<Category> categories, HttpServletRequest request) { for (Category category : categories) { //栏目 CreateHtml.staticCategory(categoryService.get(category), request); //内容 List<Article> articles = articleService.findList(new Article(category)); for (Article article : articles) { if (StringUtils.isBlank(article.getLink())) { CreateHtml.staticArticle(article, request); } } // 是否还有子栏目 List<Category> subCategories = categoryService.findByParentId(category.getId(), "1"); if (!Collections3.isEmpty(subCategories)) { staticCategoryAndArticle(subCategories, request); } } } /** * 首页静态化 */ @RequiresPermissions("cms:article:edit") @RequestMapping(value = "staticIndex") @ResponseBody public ResponseObject staticIndex(HttpServletRequest request) { try { CreateHtml.staticIndex(request); return ResponseObject.success().msg("首页静态化成功"); } catch (Exception e) { e.printStackTrace(); return ResponseObject.failure().msg("首页静态化失败"); } } /** * 栏目页静态化 */ @RequiresPermissions("cms:article:edit") @RequestMapping(value = "staticCategory") @ResponseBody public ResponseObject staticCategory(Article article, HttpServletRequest request) { try { Category category = categoryService.get(article.getCategory()); if (category != null) { CreateHtml.staticCategory(category, request); } return ResponseObject.success().msg("栏目页静态化成功"); } catch (Exception e) { e.printStackTrace(); } return ResponseObject.failure().msg("栏目页静态化失败"); } /** * 内容页静态化 */ @RequiresPermissions("cms:article:edit") @RequestMapping(value = "staticArticle") @ResponseBody public ResponseObject staticArticle(Article article, HttpServletRequest request) { try { List<Article> list = articleService.findList(article); for (Article a : list) { CreateHtml.staticArticle(a, request); } return ResponseObject.success().msg("内容页静态化成功"); } catch (Exception e) { e.printStackTrace(); return ResponseObject.failure().msg("内容页静态化失败"); } } }
package com.metoo.foundation.domain.virtual; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; /** * * <p> * Title: GoodsCompareView.java * </p> * * <p> * Description: 商品对比栏信息管理类,用来封装商品对比栏数据,用在商品对比页 * </p> * * <p> * Copyright: Copyright (c) 2015 * </p> * * <p> * Company: 沈阳网之商科技有限公司 www.koala.com * </p> * * @author erikzhang * * @date 2014-10-22 * * @version koala_b2b2c 2015 */ public class GoodsCompareView { private Long goods_id;// 商品id private String goods_img;// 商品图地址,使用中号尺寸图片 private String goods_name;// 商品名称 private BigDecimal goods_price;// 商品价格 private String goods_url;// 商品地址 private String goods_brand;// 商品品牌 private String tax_invoice;// 是否支持增值税发票 private String goods_cod;// 是否支持货到付款 private BigDecimal goods_weight;// 商品重量 private String well_evaluate;// 好评率 private String middle_evaluate;// 中评率 private String bad_evaluate;// 差评率 private Map props = new HashMap();// 商品相关属性键值对,如:颜色-红,黄,蓝 public Map getProps() { return props; } public void setProps(Map props) { this.props = props; } public Long getGoods_id() { return goods_id; } public void setGoods_id(Long goods_id) { this.goods_id = goods_id; } public String getGoods_img() { return goods_img; } public void setGoods_img(String goods_img) { this.goods_img = goods_img; } public String getGoods_name() { return goods_name; } public void setGoods_name(String goods_name) { this.goods_name = goods_name; } public BigDecimal getGoods_price() { return goods_price; } public void setGoods_price(BigDecimal goods_price) { this.goods_price = goods_price; } public String getGoods_url() { return goods_url; } public void setGoods_url(String goods_url) { this.goods_url = goods_url; } public String getGoods_brand() { return goods_brand; } public void setGoods_brand(String goods_brand) { this.goods_brand = goods_brand; } public String getTax_invoice() { return tax_invoice; } public void setTax_invoice(String tax_invoice) { this.tax_invoice = tax_invoice; } public String getGoods_cod() { return goods_cod; } public void setGoods_cod(String goods_cod) { this.goods_cod = goods_cod; } public BigDecimal getGoods_weight() { return goods_weight; } public void setGoods_weight(BigDecimal goods_weight) { this.goods_weight = goods_weight; } public String getWell_evaluate() { return well_evaluate; } public void setWell_evaluate(String well_evaluate) { this.well_evaluate = well_evaluate; } public String getMiddle_evaluate() { return middle_evaluate; } public void setMiddle_evaluate(String middle_evaluate) { this.middle_evaluate = middle_evaluate; } public String getBad_evaluate() { return bad_evaluate; } public void setBad_evaluate(String bad_evaluate) { this.bad_evaluate = bad_evaluate; } }
package Services; import Domain.Account; /** * Created by Emma on 8/12/2018. */ public interface AccountServices { Account create(Account acc); Account read(long id); Account update(Account acc); void delete(long accNo); Iterable<Account> findAll();//findall }
public class FullAdder { private final tuple Tuple; public FullAdder(boolean A, boolean B, boolean C){ //Full Adder consists of two HalfAdders and an OR Gate HalfAdder x = new HalfAdder(A,B); HalfAdder y = new HalfAdder(x.getHalfAdder().getSum(),C); OR z = new OR(); Tuple = new tuple(y.getHalfAdder().getSum(), z.logicOP(x.getHalfAdder().getCarry(), y.getHalfAdder().getCarry())); } //getter for Tuple public tuple getFullAdder() { return Tuple; } }
package br.edu.com.dados.repositories; import java.util.List; import br.edu.com.dados.dao.Dao; import br.edu.com.entities.Atividade; public class RepositoryAtividade implements IRepositoryAtividade { @Override public boolean salvarAtividade(Atividade atividade) { return Dao.getInstance().save(atividade); } @Override public boolean atualizarAtividade(Atividade atividade) { return Dao.getInstance().update(atividade); } @Override public boolean inativarAtividade(Atividade atividade) { return Dao.getInstance().delete(atividade); } @Override public List<Atividade> listarAtividade() { return (List<Atividade>) Dao.getInstance().list(Atividade.class); } @Override public List<Atividade> procurarAtividade(String query) { return (List<Atividade>) Dao.getInstance().createQuery(query); } }
package cs3500.animator.controller; import java.io.IOException; import cs3500.animator.model.IModel; import cs3500.animator.view.IView; public class ControllerSVG implements IController { private IModel model; private IView view; private int fps; public ControllerSVG(IModel m, IView v) { if (m == null || v == null) { throw new IllegalArgumentException("Bad view or model"); } this.view = v; this.model = m; } @Override public void run() { this.view.setFps(this.fps); try { this.view.drawForSVG(model.getListOfShapes()); } catch (IOException e) { e.printStackTrace(); } this.view.export(); } @Override public void setFPS(int fps) { this.fps = fps; } }
package com.github.bruce.thrift.connection.counter; import java.util.concurrent.atomic.AtomicInteger; public class SimpleCycleCounter extends CycleCounter { private AtomicInteger counter; public SimpleCycleCounter(int size) { super(size); counter = new AtomicInteger(0); } @Override public int next() { int value = Math.abs(counter.getAndIncrement()) % size; return value; } }
package com.mahang.weather.model.entity; import android.os.Parcel; import android.os.Parcelable; public class SuggestionInfo extends BaseInfo implements Parcelable { private String title; private String suggestion; private String index; protected SuggestionInfo(Parcel in) { title = in.readString(); suggestion = in.readString(); index = in.readString(); } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(title); dest.writeString(suggestion); dest.writeString(index); } @Override public int describeContents() { return 0; } public static final Creator<SuggestionInfo> CREATOR = new Creator<SuggestionInfo>() { @Override public SuggestionInfo createFromParcel(Parcel in) { return new SuggestionInfo(in); } @Override public SuggestionInfo[] newArray(int size) { return new SuggestionInfo[size]; } }; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSuggestion() { return suggestion; } public void setSuggestion(String suggestion) { this.suggestion = suggestion; } }
package subconsciouseye.eyetech; public class Reference { public static final String MOD_ID = "eyetech"; public static final String MOD_NAME = "EyeTech"; public static final String VERSION = "1.0"; public static final String CLIENT_PROXY_CLASS = "subconsciouseye.eyetech.proxy.ClientProxy"; public static final String SERVER_PROXY_CLASS = "subconsciouseye.eyetech.proxy.CommonProxy"; }
package com.chenjiawen.Dao; import com.chenjiawen.Model.Comment; import org.apache.ibatis.annotations.*; import java.util.List; @Mapper public interface CommentDao { String TABLE_NAME = "comment"; String INSERT_FIELD = " user_id,create_date,entity_id,entity_type,status,content "; String SELECT_FIELD = " id," + INSERT_FIELD; @Insert({"insert into ", TABLE_NAME, "(", INSERT_FIELD, ") values (#{userId},#{createDate},#{entityId},#{entityType},#{status},#{content})"}) int addComment(Comment comment); @Select({"select ", SELECT_FIELD, " from ", TABLE_NAME, " where entity_id=#{entityId} and entity_type=#{entityType}"}) List<Comment> selectByEntity(@Param("entityId") int entityId, @Param("entityType") int entityType); @Select({"select count(id) from ", TABLE_NAME, " where entity_id=#{entityId} and entity_type=#{entityType}"}) int getCommentCount(@Param("entityId") int entityId, @Param("entityType") int entityType); }
package com.uit.huydaoduc.hieu.chi.hhapp.Model.Trip; import android.os.Parcel; import android.os.Parcelable; import com.uit.huydaoduc.hieu.chi.hhapp.Model.RouteRequest.RouteRequest; public class Trip implements Parcelable { private String tripUId; private TripType tripType; private TripState tripState; private String passengerUId; private String driverUId; private String passengerRequestUId; private String routeRequestUId; public Trip() { } public Trip(String tripUId, TripType tripType, TripState tripState, String passengerUId, String driverUId, String passengerRequestUId, String routeRequestUId) { this.tripUId = tripUId; this.tripType = tripType; this.tripState = tripState; this.passengerUId = passengerUId; this.driverUId = driverUId; this.passengerRequestUId = passengerRequestUId; this.routeRequestUId = routeRequestUId; } public String getTripUId() { return tripUId; } public void setTripUId(String tripUId) { this.tripUId = tripUId; } public TripType getTripType() { return tripType; } public void setTripType(TripType tripType) { this.tripType = tripType; } public TripState getTripState() { return tripState; } public void setTripState(TripState tripState) { this.tripState = tripState; } public String getPassengerUId() { return passengerUId; } public void setPassengerUId(String passengerUId) { this.passengerUId = passengerUId; } public String getDriverUId() { return driverUId; } public void setDriverUId(String driverUId) { this.driverUId = driverUId; } public String getPassengerRequestUId() { return passengerRequestUId; } public void setPassengerRequestUId(String passengerRequestUId) { this.passengerRequestUId = passengerRequestUId; } public String getRouteRequestUId() { return routeRequestUId; } public void setRouteRequestUId(String routeRequestUId) { this.routeRequestUId = routeRequestUId; } public static final class Builder { private String tripUId; private TripType tripType; private TripState tripState; private String passengerUId; private String driverUId; private String passengerRequestUId; private String routeRequestUId; private Builder() { } public static Builder aTrip(String tripUId) { return new Builder().setTripUId(tripUId); } private Builder setTripUId(String tripUId) { this.tripUId = tripUId; return this; } public Builder setTripType(TripType tripType) { this.tripType = tripType; return this; } public Builder setTripState(TripState tripState) { this.tripState = tripState; return this; } public Builder setPassengerUId(String passengerUId) { this.passengerUId = passengerUId; return this; } public Builder setDriverUId(String driverUId) { this.driverUId = driverUId; return this; } public Builder setPassengerRequestUId(String passengerRequestUId) { this.passengerRequestUId = passengerRequestUId; return this; } public Builder setRouteRequestUId(String routeRequestUId) { this.routeRequestUId = routeRequestUId; return this; } public Trip build() { Trip trip = new Trip(); trip.setTripUId(tripUId); trip.setTripType(tripType); trip.setTripState(tripState); trip.setPassengerUId(passengerUId); trip.setDriverUId(driverUId); trip.setPassengerRequestUId(passengerRequestUId); trip.setRouteRequestUId(routeRequestUId); return trip; } } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.tripUId); dest.writeInt(this.tripType == null ? -1 : this.tripType.ordinal()); dest.writeInt(this.tripState == null ? -1 : this.tripState.ordinal()); dest.writeString(this.passengerUId); dest.writeString(this.driverUId); dest.writeString(this.passengerRequestUId); dest.writeString(this.routeRequestUId); } protected Trip(Parcel in) { this.tripUId = in.readString(); int tmpTripType = in.readInt(); this.tripType = tmpTripType == -1 ? null : TripType.values()[tmpTripType]; int tmpTripState = in.readInt(); this.tripState = tmpTripState == -1 ? null : TripState.values()[tmpTripState]; this.passengerUId = in.readString(); this.driverUId = in.readString(); this.passengerRequestUId = in.readString(); this.routeRequestUId = in.readString(); } public static final Creator<Trip> CREATOR = new Creator<Trip>() { @Override public Trip createFromParcel(Parcel source) { return new Trip(source); } @Override public Trip[] newArray(int size) { return new Trip[size]; } }; }
package de.digitalstreich.Manufact.controller.frontend; import de.digitalstreich.Manufact.db.ManufacturerRepository; import de.digitalstreich.Manufact.factory.*; import de.digitalstreich.Manufact.model.Manufacturer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("") public class HomeController { private UserFactory userFactory; private ProductFactory productFactory; private BranchFactory branchFactory; private CategoryFactory categoryFactory; private StateFactory stateFactory; private CountryFactory countryFactory; private TagFactory tagFactory; private ProductgroupFactory productgroupFactory; private ManufacturerRepository manufacturerRepository; @Autowired public HomeController(UserFactory userFactory, ProductFactory productFactory, BranchFactory branchFactory, CategoryFactory categoryFactory, StateFactory stateFactory, CountryFactory countryFactory, TagFactory tagFactory, ProductgroupFactory productgroupFactory, ManufacturerRepository manufacturerRepository) { this.userFactory = userFactory; this.productFactory = productFactory; this.branchFactory = branchFactory; this.categoryFactory = categoryFactory; this.stateFactory = stateFactory; this.countryFactory = countryFactory; this.tagFactory = tagFactory; this.productgroupFactory = productgroupFactory; this.manufacturerRepository = manufacturerRepository; } @GetMapping(value = {"", "/"}) public String index() { return "frontend/index/index"; } @GetMapping(value = {"/fake-data"}) public String fakerData(){ Manufacturer manufacturer = manufacturerRepository.getOne(1L); // countryFactory.createCountry(); // stateFactory.createStates(); // categoryFactory.createCategories(); // tagFactory.createTag(); // branchFactory.createBranches(); // userFactory.createManufacturer(); // productFactory.createProducts(1L); productgroupFactory.createProductgroup(manufacturer); return "frontend/index/index"; } }
package com.mredrock.freshmanspecial.data; /** * Created by 700-15isk on 2017/8/8. */ public class QQGroupNumber { private String GroupName; private String Number; public String getGroupName() { return GroupName; } public void setGroupName(String groupName) { GroupName = groupName; } public String getNumber() { return Number; } public void setNumber(String number) { Number = number; } }
package com.globallogic.dao; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.provisioning.UserDetailsManager; import org.springframework.stereotype.Service; import com.globallogic.model.User; @Service public class UserDetailsServiceImpl implements UserDetailsManager{ @Autowired(required=true) UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = null; // go to database user userdetails by username List<User> users = userRepository.findUserByUserName(username); if(!users.isEmpty()) user=users.get(0); System.out.println(user); return user; } @Override public void createUser(UserDetails user) { // TODO Auto-generated method stub } @Override public void updateUser(UserDetails user) { // TODO Auto-generated method stub } @Override public void deleteUser(String username) { // TODO Auto-generated method stub } @Override public void changePassword(String oldPassword, String newPassword) { // TODO Auto-generated method stub } @Override public boolean userExists(String username) { // TODO Auto-generated method stub System.out.println("User exists..."); return false; } }
package com.example.ontheleash; import android.content.Context; import android.content.SharedPreferences; import com.google.gson.Gson; import java.util.ArrayList; import java.util.List; public class MapSettings { private static MapSettings instance; public static synchronized MapSettings getInstance(Context context) { if (instance == null) instance = new MapSettings(context); return instance; } public enum MapStyle{ NORMAL, SATELLITE, HYBRID } private MapSettings(Context context){ SharedPreferences mSettings; mSettings = context.getSharedPreferences(Settings.APP_PREFERENCES, Context.MODE_PRIVATE); String mapSettingsJson = mSettings.getString(Settings.APP_PREFERENCES_MAP_SETTINGS_JSON, ""); // if shared prefs has mapSettings if (!mapSettingsJson.equals("")) { Gson g = new Gson(); MapSettings mapSettings = g.fromJson(mapSettingsJson, MapSettings.class); this.mapStyle = mapSettings.mapStyle; this.noDogsAreas = mapSettings.noDogsAreas; this.markerTypeList = mapSettings.markerTypeList; this.male = mapSettings.male; this.female = mapSettings.female; this.birthday = mapSettings.birthday; this.castration = mapSettings.castration; this.ready_to_mate = mapSettings.ready_to_mate; this.for_sale = mapSettings.for_sale; this.breeds = mapSettings.breeds; } // if shared prefs does not have mapSettings else{ // only dog markers markerTypeList.add(MyClusteringItem.MarkerType.DOG); } } public MapStyle mapStyle = MapStyle.NORMAL; public boolean noDogsAreas = false; public List<MyClusteringItem.MarkerType> markerTypeList = new ArrayList<>(); public boolean male = true; public boolean female = true; public String birthday = ""; public boolean castration = false; public boolean ready_to_mate = false; public boolean for_sale = false; public List<String> breeds = new ArrayList<>(); public void update(Context context) { Gson g = new Gson(); String json = g.toJson(this); SharedPreferences mSettings; mSettings = context.getSharedPreferences(Settings.APP_PREFERENCES, Context.MODE_PRIVATE); SharedPreferences.Editor editor = mSettings.edit(); editor.putString(Settings.APP_PREFERENCES_MAP_SETTINGS_JSON, json); editor.apply(); } }
package dao.prueba; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import static com.conexion.Conexion.*; public class daoPrueba { public static String cargarNombrePrueba(){ Connection cn =null; PreparedStatement pstm = null; ResultSet rs; String nom = null; try { cn = obtenerConexion(); System.out.println(">>>>>>>> cn : " + cn); if(cn!=null){ System.out.println("cn is open? : " + !cn.isClosed()); }else{ return "Es nulla"; } pstm = cn.prepareStatement("select * from cliente "); rs = pstm.executeQuery(); while (rs.next()) { nom = rs.getString(2); } } catch (Exception e) { e.printStackTrace(); return "catch > " + e.toString(); } finally { try { if (pstm != null) { pstm.close(); } if (cn != null) { cn.close(); } } catch (Exception e) { e.printStackTrace(); } pstm = null; rs = null; cn = null; } return nom; } }
package com.gaoshin.dao; import java.util.List; import com.gaoshin.dao.jpa.DaoComponent; import com.gaoshin.entity.PostEntity; public interface GroupDao extends DaoComponent { List<PostEntity> listLatestGroupPosts(Long groupId, Long beforeId, int size); List<PostEntity> listLatestUserPosts(Long userId, Long beforeId, int size); List<PostEntity> listByScores(Long groupId, int start, int size); }
package com.mkd.adtools.utils; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.stereotype.Component; import java.io.Serializable; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * JWT工具类 * */ @Component public class JwtTokenUtil implements Serializable { /** * */ private static final long serialVersionUID = 5372900910708033790L; /** * 密钥 */ private final static String secret = "kedouwo007"; /** * 从数据声明生成令牌 * * @param claims 数据声明 * @return 令牌 * 2592000L * 1000 =30天 * */ private static String generateToken(Map<String, Object> claims) { Date expirationDate = new Date(System.currentTimeMillis() + 2592000L * 1000); return Jwts.builder().setClaims(claims).setExpiration(expirationDate).signWith(SignatureAlgorithm.HS512, secret).compact(); } /** * 从令牌中获取数据声明 * * @param token 令牌 * @return * @return 数据声明 */ public static Claims getClaimsFromToken(String token) { Claims claims; try { claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody(); } catch (Exception e) { claims = null; } return claims; } /** * 生成令牌 * @return 令牌 */ public static String generateToken(String username,String userId) { Map<String, Object> claims = new HashMap<>(2); claims.put("username", username); claims.put("userId", userId); claims.put("created", new Date()); return generateToken(claims); } /** * 判断令牌是否过期 * * @param token 令牌 * @return 是否过期 */ public static Boolean isTokenExpired(String token) { try { Claims claims = getClaimsFromToken(token); Date expiration = claims.getExpiration(); return expiration.before(new Date()); } catch (Exception e) { return false; } } /** * 刷新令牌 * * @param token 原令牌 * @return 新令牌 */ public String refreshToken(String token) { String refreshedToken; try { Claims claims = getClaimsFromToken(token); claims.put("created", new Date()); refreshedToken = generateToken(claims); } catch (Exception e) { refreshedToken = null; } return refreshedToken; } public static void main(String[] args){ // String s = generateToken("151","111"); // System.out.println("s:"+s); Claims a = getClaimsFromToken("eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE1NjI4MzM0NzEsInBob25lIjoidGVzdCIsInVzZXJJZCI6IjEiLCJjcmVhdGVkIjoxNTYwMjQxNDcxNjcyfQ.U5BnbM2nWeDkxVtVfbIS3OT1xIsjJ37zTG0MbHdlYzb3KK-Qpll_aS-udN6A1imHsF2NLackMIF2aNxq9_I9ig") ; System.out.println(":"+a.get("phone")+":userID:"+a.get("userId") +" :"+a.get("created")); } }
package kr.co.shop.batch.kcp.job; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.JobScope; import org.springframework.batch.core.launch.support.RunIdIncrementer; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemWriter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import kr.co.shop.batch.kcp.model.master.RvKcpComparison; import kr.co.shop.common.util.UtilsText; import kr.co.shop.constant.MapperKcp; import kr.co.shop.support.BatchReaderAndWriter; import lombok.extern.slf4j.Slf4j; @Slf4j @Configuration public class KcpComparisonConfig extends BatchReaderAndWriter { public static final String JOB_NAME = "kcpComparisonJob"; public static final String STEP_NAME = UtilsText.concat(JOB_NAME, "-", "kcpComparisonStep"); public static final int CHUNK_SIZE = 50; @Bean public Job kcpComparisonJob() { return getJobBuilderFactory(JOB_NAME).start(kcpComparisonStep()).incrementer(new RunIdIncrementer()).build(); } @Bean @JobScope public Step kcpComparisonStep() { return getStepBuilderFactory(STEP_NAME).<RvKcpComparison, RvKcpComparison>chunk(CHUNK_SIZE) .reader(kcpComparisonJobReader()).processor(kcpComparisonJobProcessor()) .writer(kcpComparisonJobWriter()).build(); } public QueueItemReader<RvKcpComparison> kcpComparisonJobReader() { List<RvKcpComparison> param = getKcpSaleData(); return new QueueItemReader<>(param); } public ItemProcessor<RvKcpComparison, RvKcpComparison> kcpComparisonJobProcessor() { ItemProcessor<RvKcpComparison, RvKcpComparison> processor = new ItemProcessor<RvKcpComparison, RvKcpComparison>() { @Override public RvKcpComparison process(RvKcpComparison item) throws Exception { try { log.debug("#### ItemProcessor"); } catch (Exception e) { e.printStackTrace(); } return item; } }; return processor; } public ItemWriter<RvKcpComparison> kcpComparisonJobWriter() { ItemWriter<RvKcpComparison> writer = newMyBatisBatchItemWriter(MapperKcp.KCP_COMPARISON_INSERT); return writer; } public List<RvKcpComparison> getKcpSaleData() { List<RvKcpComparison> kcpSaleObj = new ArrayList<>(); // 어제 날짜 SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); Calendar cal = new GregorianCalendar(Locale.KOREA); cal.add(Calendar.DATE, -1); String dateStr = formatter.format(cal.getTime()); log.debug("############ dateStr: {}", dateStr); // 카드, 계좌이체, 가상계좌, 휴대폰 // "CARD", "ACNT", "VCNT", "MOBX" List<RvKcpComparison> cardDataArray = kcpSaleFileSaveData("CARD", dateStr); List<RvKcpComparison> acntDataArray = kcpSaleFileSaveData("ACNT", dateStr); List<RvKcpComparison> vcntDataArray = kcpSaleFileSaveData("VCNT", dateStr); List<RvKcpComparison> mobxDataArray = kcpSaleFileSaveData("MOBX", dateStr); log.debug("############ cardDataArray.size : {}", cardDataArray.size()); for (RvKcpComparison item : cardDataArray) { kcpSaleObj.add(item); } for (RvKcpComparison item : acntDataArray) { kcpSaleObj.add(item); } for (RvKcpComparison item : vcntDataArray) { kcpSaleObj.add(item); } for (RvKcpComparison item : mobxDataArray) { kcpSaleObj.add(item); } log.debug("############ kcpSaleObj.size : {}", kcpSaleObj.size()); return kcpSaleObj; } public List<RvKcpComparison> kcpSaleFileSaveData(String pay, String date) { /** * 결제 수단별 배열 순서 변경 하면 안됨. */ // 카드, 계좌이체, 가상계좌, 휴대폰 String[] pays = { "CARD", "ACNT", "VCNT", "MOBX" }; // 결제 종류 number, 공통적으로 사용가능 int paynum = Arrays.asList(pays).indexOf(pay); /** * kcp 정산 내역 파일 읽기 */ // 경로 String folderName = "C:\\parsing\\"; // if (Config.getString("server.host").contains("local.abcmart.co.kr")) { // folderName = "C:\\parsing\\"; // 로컬 // } else { // folderName = "/home/abcmart/logs/kcp/sale/"; //운영, 개발 // } // 사업자번호10자리_결제종류_파일종류(SALE=정산)_일자.txt String filePath = folderName + "2018176174_" + pay + "_SALE_" + date + ".txt"; FileInputStream fi = null; // 파일 스트림 InputStreamReader is = null; // 한글 깨짐 현상 해결 StringBuilder sb = new StringBuilder(); try { fi = new FileInputStream(filePath); is = new InputStreamReader(fi, "MS949"); // 메모장 기본 인코딩 int ch = 0; while ((ch = is.read()) != -1) { sb.append((char) ch); } } catch (FileNotFoundException e) { e.printStackTrace(); throw new RuntimeException("kcp 정산파일을 확인해주세요."); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("입출력 오류입니다."); } finally { try { // 파일 닫기 if (fi != null) { fi.close(); } if (is != null) { is.close(); } } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("입출력 오류입니다."); } } // -- kcp 정산 내역 파일 읽기 -- /** * 변수 초기화 필드명, 길이 = NHN KCP 파일송수신매뉴얼_V_2_3_0.pdf */ // 카드 시작지점, 길이 int[][] cardInt = { { 0, 1 }, { 1, 14 }, { 15, 14 }, { 29, 4 }, { 33, 20 }, { 53, 70 }, { 123, 9 }, { 132, 9 }, { 141, 9 }, { 150, 9 }, { 159, 9 }, { 168, 9 }, { 177, 9 }, { 186, 8 }, { 194, 8 }, { 202, 2 }, { 204, 16 }, { 220, 4 }, { 224, 12 }, { 236, 20 }, { 256, 13 }, { 269, 1 }, { 270, 30 } }; // 계좌이체 시작지점, 길이 int[][] acntInt = { { 0, 1 }, { 1, 14 }, { 15, 14 }, { 29, 4 }, { 33, 20 }, { 53, 70 }, { 123, 9 }, { 132, 9 }, { 141, 9 }, { 150, 9 }, { 159, 9 }, { 168, 9 }, { 177, 9 }, { 186, 8 }, { 194, 8 }, { 202, 98 } }; // 가상계좌 시작지점, 길이 int[][] vcntInt = { { 0, 1 }, { 1, 14 }, { 15, 14 }, { 29, 4 }, { 33, 20 }, { 53, 70 }, { 123, 9 }, { 132, 9 }, { 141, 9 }, { 150, 9 }, { 159, 9 }, { 168, 9 }, { 177, 9 }, { 186, 8 }, { 194, 8 }, { 202, 4 }, { 206, 16 }, { 222, 20 }, { 242, 20 }, { 262, 38 } }; // 휴대폰 시작지점, 길이 int[][] mobxInt = { { 0, 1 }, { 1, 14 }, { 15, 14 }, { 29, 4 }, { 33, 20 }, { 53, 70 }, { 123, 9 }, { 132, 9 }, { 141, 9 }, { 150, 9 }, { 159, 9 }, { 168, 9 }, { 177, 9 }, { 186, 8 }, { 194, 6 }, { 200, 8 }, { 208, 92 } }; /** * 필드명(AccountsKCP 모델로 변경후 활용, 추후 데이터 확인 및 기능 구분을 위해 사용) */ // 카드 필드명 String[] cardDataStr = { "레코드구분", "거래일시", "원거래일시", "거래구분", "KCP거래번호", "주문번호", "결제금액", "수수료", "무이자수수료", "부가세", "에스크로수수료", "에스크로부가세", "정산금액", "마감일자", "정산일자", "할부개월수", "승인번호", "매입카드사코드", "가맹점번호", "상품코드", "예외처리1", "예외처리2", "예비" }; // 계좌이체 필드명 String[] acntDataStr = { "레코드구분", "거래일시", "원거래일시", "거래구분", "KCP거래번호", "주문번호", "결제금액", "수수료", "예비", "부가세", "에스크로수수료", "에스크로부가세", "정산금액", "마감일자", "정산일자", "예비" }; // 가상계좌 필드명 String[] vcntDataStr = { "레코드구분", "입금/취소처리일시", "은행입금/취소일시", "거래구분", "KCP거래번호", "주문번호", "입금/취소금액", "수수료", "예비", "부가세", "에스크로수수료", "에스크로부가세", "정산금액", "마감일자", "정산일자", "은행코드", "가상계좌번호", "입금처리고유번호", "입금인성명", "예비" }; // 휴대폰 필드명 String[] mobxDataStr = { "레코드구분", "거래일시", "원거래일시", "거래구분", "KCP거래번호", "주문번호", "결제금액", "수수료", "예비", "부가세", "예비", "예비", "정산금액", "마감일자", "수납월", "정산일자", "예비" }; // String[][] strlist = {cardDataStr, acntDataStr, vcntDataStr, mobxDataStr}; /** * paynum 으로 인해 결제 수단별 위치 확인 String[] pays = {"CARD", "ACNT", "VCNT", "MOBX"}; */ int[][][] numlist = { cardInt, acntInt, vcntInt, mobxInt }; // 시작지점, 길이 // 위의 필드명 위치에서 해당 필요 정보만 추출 Map<String, int[]> needsMap = new HashMap<String, int[]>(); // 거래구분, 거래일시, 결제금액, 주문번호, KCP거래번호 needsMap.put(pays[0], new int[] { 3, 1, 6, 5, 4 }); // CARD needsMap.put(pays[1], new int[] { 3, 1, 6, 5, 4 }); // ACNT needsMap.put(pays[2], new int[] { 3, 1, 6, 5, 4 }); // VCNT needsMap.put(pays[3], new int[] { 3, 1, 6, 5, 4 }); // MOBX int[] cardAc = { -1, -1, 1, 2, -1, -1, 3, 4, 5, 6, 7, 8, 9, 12, 13, -1, 14, 10, 11, -1, -1, -1, -1, 15, 16, 17, 18, 19 }; int[] acntAc = { -1, -1, 1, 2, -1, -1, 3, 4, 5, 6, 7, -1, 9, 12, 13, -1, 14, 10, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; int[] vcntAc = { -1, -1, -1, -1, 1, 2, 3, 4, 5, 6, 7, -1, 9, 12, 13, -1, 14, 10, 11, 15, 16, 17, 18, -1, -1, -1, -1, -1 }; int[] mobxAc = { -1, -1, 1, 2, -1, -1, 3, 4, 5, 6, 7, -1, 9, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; int[][] acList = { cardAc, acntAc, vcntAc, mobxAc }; // --변수 초기화-- String[] strArr = sb.toString().split("\n"); // 한줄씩 확인하는 작업 List<RvKcpComparison> kcpList = new ArrayList<>(); // 데이터 정렬 // loop for (int i = 0; i < strArr.length; i++) { String sbLine = strArr[i]; // D가 아닌 경우는 다시 loop로 // if (!StringUtils.equals("D", sbLine.substring(0, 1))) { if (!UtilsText.equals("D", sbLine.substring(0, 1))) { continue; } int[][] num = numlist[paynum]; // 해당 결제수단의 byte수 배열 RvKcpComparison kcp = new RvKcpComparison(); for (int k = 0; k < acList[paynum].length; k++) { int ac = acList[paynum][k]; // accountsKCP 순서별 정리한 배열 if (ac == -1) { // -1은 사용하지 않는 변수 continue; } String str = sbLine.substring(num[ac][0], num[ac][0] + num[ac][1]).trim(); // 해당 기능의 글자 if (str.length() < 1) { // 내용이 없을 경우 continue; } if (k == 2) { // 거래일시 String pattern = "yyyyMMddHHmmss"; try { kcp.setPymntDtm(new Timestamp(new SimpleDateFormat(pattern).parse(str).getTime())); } catch (ParseException e) { e.printStackTrace(); throw new RuntimeException("거래일시 ParseException입니다."); } } else if (k == 3) { // 원거래일시 String pattern = "yyyyMMddHHmmss"; try { kcp.setPymntOrgDtm(new Timestamp(new SimpleDateFormat(pattern).parse(str).getTime())); } catch (ParseException e) { e.printStackTrace(); throw new RuntimeException("원거래일시 ParseException입니다."); } } else if (k == 4) { // 입금/취소처리일시 String pattern = "yyyyyMMddHHmmss"; try { kcp.setLgdDtm(new Timestamp(new SimpleDateFormat(pattern).parse(str).getTime())); } catch (ParseException e) { e.printStackTrace(); throw new RuntimeException("입금/취소처리일시 ParseException입니다."); } } else if (k == 5) { // 은행입금/취소일시 String pattern = "yyyyyMMddHHmmss"; try { kcp.setLgdBankDtm(new Timestamp(new SimpleDateFormat(pattern).parse(str).getTime())); } catch (ParseException e) { e.printStackTrace(); throw new RuntimeException("은행입금/취소일시 ParseException입니다."); } } else if (k == 6) { // 거래구분 kcp.setPymntStatCode(str); } else if (k == 7) { // KCP거래번호 kcp.setKcpDealNum(str); } else if (k == 8) { // 주문번호 kcp.setOrderNum(str); } else if (k == 9) { // 결제금액(입금/취소금액) kcp.setPymntAmt(Integer.valueOf(str)); } else if (k == 10) { // 수수료 kcp.setPymntCharge(Integer.valueOf(str)); } else if (k == 11) { // 무이자 수수료 kcp.setFreeCharge(Integer.valueOf(str)); } else if (k == 12) { // 부가세 kcp.setPymntSurTax(Integer.valueOf(str)); } else if (k == 13) { // 정산금액 kcp.setAccountsAmt(Integer.valueOf(str)); } else if (k == 14) { // 마감일자 String pattern = "yyyyMMdd"; try { kcp.setDeadlineDtm(new Timestamp(new SimpleDateFormat(pattern).parse(str).getTime())); } catch (ParseException e) { e.printStackTrace(); throw new RuntimeException("마감일자 ParseException입니다."); } } else if (k == 15) { // 수납월 kcp.setReceiveMonth(str); } else if (k == 16) { // 정산일자 String pattern = "yyyyMMdd"; try { kcp.setAccountsDtm(new Timestamp(new SimpleDateFormat(pattern).parse(str).getTime())); } catch (ParseException e) { e.printStackTrace(); throw new RuntimeException("정산일자 ParseException입니다."); } } else if (k == 17) { // 에스크로수수료 kcp.setEscrowCharge(Integer.valueOf(str)); } else if (k == 18) { // 에스크로부가세 kcp.setEscrowSurtax(Integer.valueOf(str)); } else if (k == 19) { // 은행코드 kcp.setBankCode(str); } else if (k == 20) { // 가상계좌번호 kcp.setLgdAccountnum(str); } else if (k == 21) { // 입금처리고유번호 kcp.setLgdCasseqno(str); } else if (k == 22) { // 입금인성명 kcp.setLgdPayer(str); } else if (k == 23) { // 할부개월수 kcp.setIstmtCount(str); } else if (k == 24) { // 승인번호 kcp.setPrmtNum(str); } else if (k == 25) { // 매입카드사코드 kcp.setCrdtCardCode(str); } else if (k == 26) { // 가맹점번호 kcp.setMerchantName(str); } else if (k == 27) { // 상품코드 kcp.setPrdtCode(str); } } kcp.setPymntMeans(pay); kcpList.add(kcp); } return kcpList; // DB 저장 // for (RvKcpComparison akcp : kcpList) { // this.orderDao.insertPaymentAccountsKCP(akcp); // } } }
package net.kalpas.pitta.repository; import net.kalpas.pitta.PittaApplication; import net.kalpas.pitta.domain.Event; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import java.util.List; import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = PittaApplication.class) @WebAppConfiguration @IntegrationTest public class EventRepositoryTest extends AbstractMongoDbTest { @Autowired private EventRepository repository; @Test public void mongoTest(){ repository.deleteAll(); Event event = new Event(); event.id = 1l; event.name = "name"; repository.save(event); List<Event> found = repository.findByName(event.name); assertNotNull(found); assertFalse(found.isEmpty()); } }
/* * 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 servlet.cart; import static common.Config.*; import common.ResouceDynamicMapping; import data.dao.OrderDao; import data.dto.OrderDetailDto; import data.dto.OrderDto; import java.io.IOException; import java.io.PrintWriter; import java.sql.Date; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import servlet.common.error.errorvalidator.CheckoutReqHandler; import servlet.common.sessionmodel.Cart; import servlet.common.sessionmodel.CartItem; import java.util.UUID; import sendmail.CheckoutEmail; import sendmail.CheckoutEmail.OrderConfirm; import sendmail.MailSenderApi; /** * * @author dangminhtien */ public class CheckoutServlet extends HttpServlet { protected void processRequest(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { CheckoutReqHandler reqHandler = new CheckoutReqHandler(); reqHandler.init(req); String htmlSuccessRes = "<h1>Thank you for your order</h1></br>"; ResouceDynamicMapping resourceMapping = (ResouceDynamicMapping) req.getServletContext().getAttribute(ResouceDynamicMapping.KEY); HashMap<String, String> roadMap = resourceMapping.getRoadMap(); try { if (!reqHandler.hasError()) { OrderDao orderDao = new OrderDao(); HttpSession session = req.getSession(false); if (session != null) { Cart cart = (Cart) session.getAttribute("CART"); // create order double totalOrderPrice = 0d; String orderId = UUID.randomUUID().toString(); ArrayList<OrderDetailDto> orderDetails = new ArrayList(); List<OrderConfirm> ordersMail = new ArrayList(); if (cart != null) { Map<String, CartItem> items = cart.getAll(); if (!items.isEmpty()) { for (CartItem item : items.values()) { totalOrderPrice += item.getPrice() * item.getQuantity(); String orderDetailId = UUID.randomUUID().toString(); orderDetails.add(new OrderDetailDto(orderDetailId, orderId, item.getQuantity(), item.getId(), item.getPrice() * item.getQuantity(), OrderDetailDto.Status.PENDING)); ordersMail.add(new OrderConfirm(item.getProductName(), item.getPrice(), item.getQuantity())); } } session.removeAttribute("CART"); CheckoutEmail mail = new CheckoutEmail(ordersMail, totalOrderPrice, reqHandler.getTxtEmail()); MailSenderApi sendMail = new MailSenderApi(); htmlSuccessRes = "<h1>Thank you for your order please check your email to see more detail</h1></br>"; htmlSuccessRes += mail.getHtml(); sendMail.send(mail); } OrderDto orderDto = new OrderDto(orderId, reqHandler.getTxtEmail(), reqHandler.getTxtAddress(), reqHandler.getTxtPhoneNumber(), totalOrderPrice, new Date(System.currentTimeMillis()), true, orderDetails); orderDao.add(orderDto); } } } catch (ClassNotFoundException ex) { log("CheckoutServlet error due to: " + ex.getMessage()); } catch (SQLException ex) { log("CheckoutServlet error due to: " + ex.getMessage()); } finally { if (reqHandler.hasError()) { req.setAttribute("UERROR", reqHandler.getError()); req.getRequestDispatcher(roadMap.get(CART_VIEW)).forward(req, res); } else { // forward to success page PrintWriter printer = res.getWriter(); htmlSuccessRes += "</br>" + "<a href=\"dispatchercontroller\">back</a>"; printer.print(htmlSuccessRes); } } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { processRequest(req, resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { processRequest(req, resp); } }
package org.davidmoten.io.extras; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import org.junit.Test; import com.github.davidmoten.guavamini.Lists; import com.github.davidmoten.junit.Asserts; public class IOUtilTest { @Test public void testRoundTripIdentity() throws IOException { testRoundTripIdentity("hi there", 128, 128); } @Test public void testRoundTripIdentityWithSmallBuffers() throws IOException { testRoundTripIdentity("hi there", 2, 3); } private void testRoundTripIdentity(String s, int bufferSizeLeft, int bufferSizeRight) throws IOException { InputStream a = new BufferedInputStream( new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)), bufferSizeLeft); InputStream b = IOUtil.pipe(a, o -> o, bufferSizeRight); List<String> list = new BufferedReader(new InputStreamReader(b, StandardCharsets.UTF_8)) .lines().collect(Collectors.toList()); assertEquals(s, list.get(0)); assertEquals(1, list.size()); } @Test public void testRoundTripGzip() throws IOException { testRoundTripGzip("hi there", 128); } @Test public void testRoundTripGzipLong() throws IOException { testRoundTripGzip(createLongString(), 8192); } @Test public void testWriteInConstructorAndWriteOnClose() throws IOException { byte[] m = new byte[] { 101, 102 }; ByteArrayInputStream a = new ByteArrayInputStream(m); InputStream b = IOUtil.pipe(a, o -> new SpecialOutputStream(o)); assertArrayEquals(new byte[] { 1, 2, 101, 102, 5 }, readAll(b)); } @Test public void isUtilityClass() { Asserts.assertIsUtilityClass(IOUtil.class); } private static String createLongString() { StringWriter w = new StringWriter(); for (int i = 0; i < 1000; i++) { w.write(UUID.randomUUID().toString()); } return w.toString(); } private void testRoundTripGzip(String s, int bufferSize) throws IOException { byte[] m = s.getBytes(StandardCharsets.UTF_8); ByteArrayOutputStream out = new ByteArrayOutputStream(); GZIPOutputStream g = new GZIPOutputStream(out); g.write(m); g.close(); ByteArrayInputStream a = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)); InputStream b = IOUtil.pipe(a, o -> new GZIPOutputStream(o, 8, false), bufferSize); assertArrayEquals(m, readAll(new GZIPInputStream(b))); } @Test public void testGzip() throws IOException { byte[] bytes = "hello there you how's things?".getBytes(); assertArrayEquals(bytes, readAll(IOUtil.gunzip(IOUtil.gzip(new ByteArrayInputStream(bytes))))); } @Test public void testMarkNotSupported() throws IOException { byte[] bytes = "hello there you how's things?".getBytes(); InputStream is = IOUtil.gzip(new ByteArrayInputStream(bytes)); assertFalse(is.markSupported()); } @Test public void testMarkDoesNothing() throws IOException { byte[] bytes = "hello there you how's things?".getBytes(); InputStream is = IOUtil.gzip(new ByteArrayInputStream(bytes)); is.mark(1); } @Test public void testSkip() throws IOException { byte[] bytes = new byte[] { -45, 62, 77 }; { InputStream is = IOUtil.gzip(new ByteArrayInputStream(bytes)); System.out.println(Arrays.toString(readAll(is))); } InputStream is = IOUtil.gzip(new ByteArrayInputStream(bytes)); assertEquals(31, is.read()); assertEquals(9, is.skip(9)); assertEquals(-69 & 0xff, is.read()); } @Test public void testReadOfLength0() throws IOException { byte[] bytes = new byte[] { 100, 101 }; InputStream is = IOUtil.pipe(new ByteArrayInputStream(bytes), o -> new ByByteOutputStream(o)); assertEquals(100, is.read()); assertEquals(0, is.read(new byte[2], 0, 0)); } @Test public void testOffsetUsedInRead() throws IOException { byte[] bytes = new byte[] { 100, 101}; InputStream is = IOUtil.pipe(new ByteArrayInputStream(bytes), o -> o); byte[] buffer = new byte[10]; is.read(buffer, 7, 2); assertEquals(buffer[7], 100); assertEquals(buffer[8], 101); } @Test public void testAvailable() throws IOException { byte[] bytes = new byte[] { 100, 101}; InputStream is = IOUtil.pipe(new ByteArrayInputStream(bytes), o -> o); assertEquals(0, is.available()); is.read(); assertEquals(1, is.available()); is.read(); assertEquals(0, is.available()); assertEquals(-1, is.read()); assertEquals(0, is.available()); } @Test public void testSkipToEnd() throws IOException { byte[] bytes = new byte[] { 100, 101 }; InputStream is = IOUtil.pipe(new ByteArrayInputStream(bytes), o -> new ByByteOutputStream(o)); assertEquals(2, is.skip(2)); assertEquals(-1, is.skip(1)); } @Test public void testSkipPastEnd() throws IOException { byte[] bytes = new byte[] { 100, 101 }; InputStream is = IOUtil.pipe(new ByteArrayInputStream(bytes), o -> new ByByteOutputStream(o)); assertEquals(2, is.skip(3)); assertEquals(-1, is.skip(1)); } @Test(expected = IOException.class) public void testResetThrows() throws IOException { byte[] bytes = new byte[] { 100, 101 }; InputStream is = IOUtil.pipe(new ByteArrayInputStream(bytes), o -> new ByByteOutputStream(o)); is.reset(); } @Test public void testByteByByte() throws IOException { byte[] bytes = new byte[] { 100, 101 }; InputStream is = IOUtil.pipe(new ByteArrayInputStream(bytes), o -> new ByByteOutputStream(o)); assertEquals(100, is.read()); assertEquals(101, is.read()); assertEquals(-1, is.read()); } @Test public void testReadAfterCloseThrows() throws IOException { byte[] bytes = new byte[] { 100, 101 }; InputStream is = IOUtil.pipe(new ByteArrayInputStream(bytes), o -> new ByByteOutputStream(o)); is.close(); try { is.read(); fail(); } catch (IOException e) { assertEquals("Stream closed", e.getMessage()); } } @Test public void testRoundTripGzipBytePerByte() throws IOException { String s = "hi there"; ByteArrayInputStream a = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8)); InputStream b = IOUtil.pipe(a, o -> new GZIPOutputStream(new ByByteOutputStream(o))); List<String> list = new BufferedReader( new InputStreamReader(new GZIPInputStream(b), StandardCharsets.UTF_8)).lines() .collect(Collectors.toList()); assertEquals("hi there", list.get(0)); assertEquals(1, list.size()); } @Test public void testInputStreamToStream() { ByteArrayInputStream b = new ByteArrayInputStream("hello\nthere".getBytes(StandardCharsets.UTF_8)); Stream<String> stream = new BufferedReader(new InputStreamReader(b, StandardCharsets.UTF_8)).lines(); assertEquals(Lists.newArrayList("hello", "there"), stream.collect(Collectors.toList())); } @Test public void testStreamToInputStream() { Stream<byte[]> stream = Stream.of("hello\n".getBytes(StandardCharsets.UTF_8), "there".getBytes(StandardCharsets.UTF_8)); InputStream in = IOUtil.toInputStream(stream); } private static byte[] readAll(InputStream is) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); byte[] buffer = new byte[8192]; int n; try { while ((n = is.read(buffer)) != -1) { bytes.write(buffer, 0, n); } bytes.close(); return bytes.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } } private static final class ByByteOutputStream extends OutputStream { private final OutputStream os; ByByteOutputStream(OutputStream os) { this.os = os; } @Override public void write(int b) throws IOException { os.write(b); } } private static final class SpecialOutputStream extends OutputStream { private final OutputStream os; SpecialOutputStream(OutputStream os) throws IOException { this.os = os; os.write(create(2)); } @Override public void write(int b) throws IOException { os.write(b); } @Override public void close() throws IOException { os.write((byte) 5); } } private static byte[] create(int length) { byte[] b = new byte[length]; for (int i = 0; i < length; i++) { b[i] = (byte) (i + 1); } return b; } }
package br.com.fatec.proximatrilha.repository; import org.springframework.data.repository.CrudRepository; import br.com.fatec.proximatrilha.model.Comment; public interface CommentRepository extends CrudRepository<Comment, Long> { }
package com.cheese.radio.ui.media.play.popup; import android.os.Bundle; import android.view.View; import com.binding.model.adapter.recycler.RecyclerSelectAdapter; import com.binding.model.model.ModelView; import com.binding.model.model.PopupRecyclerModel; import com.cheese.radio.R; import com.cheese.radio.base.cycle.BaseActivity; import com.cheese.radio.databinding.PopupPlayBinding; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import static com.binding.model.adapter.AdapterType.refresh; import static com.binding.model.adapter.IEventAdapter.NO_POSITION; /** * Created by 29283 on 2018/3/29. */ @ModelView(R.layout.popup_play) public class PopupPlayModel extends PopupRecyclerModel<BaseActivity,PopupPlayBinding,SelectPlayTimeEntity>{ @Inject PopupPlayModel(){super(new RecyclerSelectAdapter<>(1));} private List<SelectPlayTimeEntity> entities = new ArrayList<>(); @Override public void attachView(Bundle savedInstanceState, BaseActivity baseActivity) { super.attachView(savedInstanceState, baseActivity); //单选操作(在addEventAdapter里实现单选) entities.add(new SelectPlayTimeEntity("不开启",-1)); entities.add(new SelectPlayTimeEntity("15分钟后停止播放",900)); entities.add(new SelectPlayTimeEntity("30分钟后停止播放",1800)); entities.add(new SelectPlayTimeEntity("45分钟后停止播放",2700)); entities.add(new SelectPlayTimeEntity("60分钟后停止播放",3600)); getAdapter().setList(NO_POSITION,entities,refresh); } public void onDismissClick(View view){ getWindow().dismiss(); } }
package com.isg.iloan.validation; import org.zkoss.zk.ui.Component; import org.zkoss.zul.Tabpanel; public class CreditCardDetailPanelValidator { public static void addSaveSwipeValidation(Component window) { // getSaveAndSwipeNode(window); //window.getPage().getDesktop().getComponents() for(Component c: window.getPage().getDesktop().getComponents()){ System.out.println(c); } System.out.println(window.getPage().getDesktop().getComponentByUuid("")); } private static void getSaveAndSwipeNode(Component comp) { Component parent = comp.getParent(); if(parent instanceof Tabpanel){ parent.getSpaceOwner(); for(Component e: parent.getFellows()){ if("saveSwipePanel".equals(e.getId())){ System.out.println(e.getFellows().size()); // Include include = (Include) e.getFellow("saveSwipePanel"); // System.out.println(e.getFellows()); for(Component x:e.getFellows()){ System.out.println(x); // if(x.getId("saveSwipePanelInclude")){ // // } } break; } } } if(null !=parent){ getSaveAndSwipeNode(parent); } } }
package com.rahul.popularmovies.Adapter; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import com.rahul.popularmovies.Activities.MainActivity; import com.rahul.popularmovies.Activities.MovieDetailActivity; import com.rahul.popularmovies.Fragments.MovieDetailFragment; import com.rahul.popularmovies.Fragments.MoviesFragment; import com.rahul.popularmovies.Model.Movie; import com.rahul.popularmovies.R; import com.rahul.popularmovies.Utility.Constants; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.zip.Inflater; /** * Created by Rahul on 4/16/2016. */ public class MovieAdapter extends BaseAdapter { ArrayList<Movie> movieList; Context context; String TAG = "MovieAdapter"; MoviesFragment.Callback callback; public MovieAdapter(ArrayList<Movie> movieList, Context context, MoviesFragment.Callback callback) { this.movieList = movieList; this.context = context; this.callback = callback; } public interface AdapterCallback { public int x(); } @Override public int getCount() { return movieList.size(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { LayoutInflater li = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); if(convertView==null) { convertView = li.inflate(R.layout.movie_poster,parent,false); } if(movieList!=null) { if(movieList.size()==0) { return null; } final ImageView imageView = (ImageView)convertView.findViewById(R.id.imageView); String str = movieList.get(position).getPoster_path(); String img_path = str.substring(1); final String img_url = Constants.BASE_POSTER_URL+img_path; // Log.d(TAG,"Image url:"+img_url); Picasso.with(context).load(img_url).into(imageView); final String movie_title = movieList.get(position).getOriginal_title(); final String overview = movieList.get(position).getOverview(); final String release_date = movieList.get(position).getRelease_date(); final String rating = movieList.get(position).getVote_average(); final String movieId = movieList.get(position).getId(); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, MovieDetailActivity.class); intent.putExtra(Constants.MOVIE_TITLE,movie_title); intent.putExtra(Constants.OVERVIEW,overview); intent.putExtra(Constants.DATE,release_date); intent.putExtra(Constants.RATING,rating); intent.putExtra(Constants.POSTER_PATH,img_url); Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap(); intent.putExtra("image",bitmap); intent.putExtra(Constants.MOVIE_ID,movieList.get(position).getId()); // context.startActivity(intent); callback.onItemSelected(img_url, overview, release_date, movie_title, rating, movieId, bitmap); } }); } return convertView; } }
package com.miyatu.tianshixiaobai.activities.mine.moreFunction; import android.app.Activity; import android.content.Intent; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.PopupWindow; import android.widget.RelativeLayout; import com.miyatu.tianshixiaobai.R; import com.miyatu.tianshixiaobai.activities.BaseActivity; import com.miyatu.tianshixiaobai.utils.ScreenUtils; public class MoreFunctionActivity extends BaseActivity { private RelativeLayout userAgreement; //用户协议 private RelativeLayout privacyPolicy; //隐私政策 private RelativeLayout clearCache; //清除缓存 private RelativeLayout commentUs; //评价我们 private RelativeLayout aboutUs; //关于我们 private RelativeLayout businessCooperation; //商务合作 private PopupWindow popupWindow; public static void startActivity(Activity activity){ Intent intent = new Intent(activity, MoreFunctionActivity.class); activity.startActivity(intent); } @Override protected int getLayoutId() { return R.layout.activity_more_function; } @Override protected void initView() { initTitle(); userAgreement = findViewById(R.id.userAgreement); privacyPolicy = findViewById(R.id.privacyPolicy); clearCache = findViewById(R.id.clearCache); commentUs = findViewById(R.id.commentUs); aboutUs = findViewById(R.id.aboutUs); businessCooperation = findViewById(R.id.businessCooperation); } @Override protected void initData() { initClearCachePopWindow(); } @Override protected void initEvent() { userAgreement.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UserAgreementActivity.startActivity(MoreFunctionActivity.this); } }); privacyPolicy.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PrivacyPolicyActivity.startActivity(MoreFunctionActivity.this); } }); clearCache.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { popupWindow.showAtLocation(v, Gravity.CENTER,0,0); ScreenUtils.dimBackground((Activity)MoreFunctionActivity.this,1f,0.5f); //屏幕亮度变化 } }); commentUs.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); aboutUs.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AboutUsActivity.startActivity(MoreFunctionActivity.this); } }); businessCooperation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { BusinessCooperationActivity.startActivity(MoreFunctionActivity.this); } }); } @Override protected void updateView() { } @Override public void initTitle() { super.initTitle(); setTitleCenter("更多"); } private void initClearCachePopWindow() { View searchView = LayoutInflater.from(MoreFunctionActivity.this).inflate(R.layout.pop_clear_cache,null); popupWindow = new PopupWindow(searchView, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT); popupWindow.setFocusable(true); popupWindow.setOutsideTouchable(false); popupWindow.setClippingEnabled(false); popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { //屏幕亮度变化 ScreenUtils.dimBackground((Activity)MoreFunctionActivity.this,0.5f,1f); } }); } }
package kr.or.ddit.servlet.scope; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import kr.or.ddit.servlet.basic.BasicServlet; @WebServlet("/mulCalculation") public class mulCalculation extends HttpServlet{ private static final Logger logger = LoggerFactory.getLogger(BasicServlet.class); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getRequestDispatcher("/jsp/mulResult.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int start = Integer.parseInt(req.getParameter("param1")); int end = Integer.parseInt(req.getParameter("param2")); HttpSession session = req.getSession(); int mul = start * end; session.setAttribute("mulResult", mul); req.setAttribute("param1", start); req.setAttribute("param2", end); logger.debug("start : {} , end : {}, 두 숫자의 합 : {}", start, end, mul); req.getRequestDispatcher("/jsp/mulResult.jsp").forward(req, resp); } }
package controller; import ejb.NotaFacadeLocal; import ejb.PersonaFacadeLocal; import entity.Nota; import entity.Persona; import java.io.Serializable; import java.util.List; import javax.ejb.EJB; import javax.enterprise.context.SessionScoped; import javax.inject.Named; @Named(value = "notacontroller") @SessionScoped public class NotaController implements Serializable{ @EJB private NotaFacadeLocal notaEJB; private Nota nota; private List<Nota> lista; private PersonaFacadeLocal personaEJB; private Persona persona; private List<Persona> }
package com.unit; public interface Autowire { /** * 返回自动装配的配置值 * @return */ String getValue(); }
package com.xh.encryption; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; public class CreatKey { RSAPublicKey publicKey; RSAPrivateKey privateKey; public CreatKey() throws Exception{ // TODO Auto-generated constructor stub KeyPairGenerator keyPairGen = KeyPairGenerator .getInstance("RSA"); keyPairGen.initialize(1024); KeyPair keyPair = keyPairGen.generateKeyPair(); // 公钥 publicKey = (RSAPublicKey) keyPair.getPublic(); // 私钥 privateKey = (RSAPrivateKey) keyPair.getPrivate(); } /** * 取得私钥 * * @return * @throws Exception */ public String getPrivateKeyString() throws Exception { return Base64.encodeToString(getPrivateKeyByte(), 0); } /** * 取得私钥 * @return * @throws Exception */ public byte[] getPrivateKeyByte()throws Exception{ return privateKey.getEncoded(); } /** * 取得公钥 * * @return * @throws Exception */ public String getPublicKeyString() throws Exception { return Base64.encodeToString(getPublicKeybyte(), 0); } /** * 取得公钥 * @return * @throws Exception */ public byte[] getPublicKeybyte() throws Exception{ return publicKey.getEncoded(); } }
package com.ranpeak.ProjectX.activity.lobby; import android.util.Log; import io.reactivex.Observer; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; public class DefaultSubscriber<T> implements Observer<T> { Disposable disposable; @Override public void onSubscribe(@NonNull Disposable d) { disposable = d; } @Override public void onNext(@NonNull T t) { } @Override public void onError(@NonNull Throwable e) { Log.e("sds",e.getMessage()); } @Override public void onComplete() { } }
package com.sshfortress.common.securityutil; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; /** * <p> * 功能:AES128位对称加密类,该类参数需要16位字符串秘钥及待加/解密字符串 * <br/>参考文章: * http://blog.csdn.net/coyote1994/article/details/52368921 * <br/>http://jueyue.iteye.com/blog/1830792 * </p> * @ClassName: AES128 * @version V1.0 */ public class AES128 { /* * 定义一个初始向量,需要与iOS端的统一,使用CBC模式,需要一个向量iv,可增加加密算法的强度 */ private static final String IV_STRING = "16-Bytes--String"; public static final String KEY = "w1e2i3s4i5d6o7m8"; /** * <p class="detail"> * 功能:AES128加密方法 * </p> * @param content 待加密内容 * @param key 加密密钥(16位字符串) * @return 加密后的字符串(结果已经过base64加密) * @throws Exception */ public static String encryptAES(String content, String key) throws Exception { byte[] byteContent = content.getBytes("UTF-8"); // 注意,为了能与 iOS 统一 // 这里的 key 不可以使用 KeyGenerator、SecureRandom、SecretKey 生成 byte[] enCodeFormat = key.getBytes(); SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES"); byte[] initParam = IV_STRING.getBytes(); IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam); // 指定加密的算法、工作模式和填充方式 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec); byte[] encryptedBytes = cipher.doFinal(byteContent); // 同样对加密后数据进行 base64 编码 return Base64.encodeBase64String(encryptedBytes); } /** * <p class="detail"> * 功能:解密函数 * </p> * @param content 待解密字符串 * @param key 解密秘钥(16位字符串,需要与加密字符串一致) * @return * @throws Exception */ public static String decryptAES(String content, String key) throws Exception { // 先base64 解码 byte[] encryptedBytes = Base64.decodeBase64(content); byte[] enCodeFormat = key.getBytes(); SecretKeySpec secretKey = new SecretKeySpec(enCodeFormat, "AES"); byte[] initParam = IV_STRING.getBytes();//使用CBC模式,需要一个向量iv,可增加加密算法的强度 IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式" cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec); byte[] result = cipher.doFinal(encryptedBytes); return new String(result, "UTF-8"); } /* * 测试函数 */ public static void main(String[] args) throws Exception { String content="01234567891"; String key="7t3e506j9z10xbd4";//必须为16位 //String deContent="Z2pVoa509Z0OYKLRseCek7abpYVbFbKETdJoQI4Kv28="; String deKey="7t3e506j9z10xbd4"; String enstring = encryptAES(content, key); String destring = decryptAES(enstring,deKey); System.out.println("原始字符串:"+content); System.out.println("加密后字符串:"+enstring); System.out.println("长度:"+enstring.length()); //System.out.println("待解密字符串:"+deContent); System.out.println("解密后字符串:"+destring); } }
/** * Copyright 2016-2017 Shyam Bhimani */ package codelityChallange; class Solution { public int solution(int[] H) { // write your code in Java SE 8 int counter = H.length; int mid = H.length/2; int ownNeastHight = 0; int willHuntNeastHeight = 0; ownNeastHight = H[mid]; for (int i = 0; i < H.length; i++){ } return 0; } public static void main(String[] args){ } }
package com.bistel.test.service.hbaseImpl; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeSet; import org.apache.hadoop.hbase.util.Bytes; import org.junit.Test; import com.bistel.common.ProjectConstants; import com.bistel.common.ProjectUtils; import com.bistel.model.Functions; import com.bistel.model.SummaryParameterInfo; import com.bistel.service.exception.ServiceException; import com.bistel.service.hbaseImpl.TraceSummaryService; import com.bistel.test.service.TestConstants; /** * Unit test class for testing methods that are persisting trace summary data * @author abbas and punit * @since 02-Aug-2012 */ public class SensorTraceSummaryServiceWriteTest extends BaseHbaseServiceTest { public SensorTraceSummaryServiceWriteTest() { super(ProjectConstants.TRACE_SUMMARY_TABLE, new byte[][] { Bytes .toBytes(ProjectConstants.TRACE_SUMMARY_CF1)}); } /** * Method to test persistence of trace summary data by Lot * @throws ServiceException * @throws IOException */ @Test public void testSaveTraceSummaryByLOT() throws ServiceException, IOException { List<SummaryParameterInfo> subSummaryInput = new ArrayList<SummaryParameterInfo>(); List<SummaryParameterInfo> lotSummaryInput = new ArrayList<SummaryParameterInfo>(); populateTestData(null,subSummaryInput,lotSummaryInput); TraceSummaryService s = new TraceSummaryService(); s.saveTraceSummaryByLOT(lotSummaryInput); int expectedRowCount = lotSummaryInput.size(); int actualRowCount = countRows(); assertEquals(expectedRowCount, actualRowCount); } /** * Method to test persistence of trace summary data by Substrate * @throws ServiceException * @throws IOException */ @Test public void testSaveTraceSummaryBySubstrate() throws ServiceException, IOException { List<SummaryParameterInfo> subSummaryInput = new ArrayList<SummaryParameterInfo>(); List<SummaryParameterInfo> lotSummaryInput = new ArrayList<SummaryParameterInfo>(); populateTestData(null,subSummaryInput,lotSummaryInput); TraceSummaryService s = new TraceSummaryService(); s.saveTraceSummaryBySubstrate(subSummaryInput); int expectedRowCount = subSummaryInput.size(); int actualRowCount = countRows(); assertEquals(expectedRowCount, actualRowCount); } /** * Method to get test data * @param count * @return test data */ private void populateTestData(Set<String> lotDetails,List<SummaryParameterInfo> subSummary,List<SummaryParameterInfo> lotSummary ) { if(subSummary==null || lotSummary==null) return; if(lotDetails==null){ lotDetails = new TreeSet<String>(); SensorTraceReportServiceWriteTest testReport = new SensorTraceReportServiceWriteTest(); testReport.getTestData(lotDetails); } String[] values = { "100", "10", "5.63", "3.424", "5.23", "15.74", "7.327"}; Functions[] fs = Functions.values(); Map<String,String> functions = new HashMap<String,String>(); for (int j = 0; j < values.length; j++) { functions.put(fs[j].getValue(), values[j]); } for (String lotInfo : lotDetails) { for (int i = 1; i <= ProjectConstants.TOTAL_PARAMS; i++) { String details[] = lotInfo.split(ProjectConstants.ROWKEY_SEPARATOR); String lot = details[0]; long sTL=Long.parseLong(details[1]); long eTL=Long.parseLong(details[2]); String sub = (details.length==5)?details[details.length-1]:null; String param = "P0" + ProjectUtils.pad(i, 3); if(details.length==5) subSummary.add(new SummaryParameterInfo(TestConstants.stepId, TestConstants.toolId, TestConstants.moduleId, lot, sub,param,functions, sTL, eTL,TestConstants.recepieId)); else lotSummary.add(new SummaryParameterInfo(TestConstants.stepId, TestConstants.toolId, TestConstants.moduleId, lot, sub,param,functions, sTL, eTL,TestConstants.recepieId)); } } return; } /*public static void main(String[] args) throws ServiceException { //inserting trace report data Set<String> lotDetails = new TreeSet<String>(); List<SummaryParameterInfo> subSummaryInput = new ArrayList<SummaryParameterInfo>(); List<SummaryParameterInfo> lotSummaryInput = new ArrayList<SummaryParameterInfo>(); SensorTraceReportServiceWriteTest testReport = new SensorTraceReportServiceWriteTest(); SensorTraceSummaryServiceWriteTest testSummary = new SensorTraceSummaryServiceWriteTest(); List<ModuleTraceInfo> input = testReport.getTestData(lotDetails); TestConstants.trs.saveModuleTraceData(input); testSummary.populateTestData(lotDetails,subSummaryInput,lotSummaryInput); TestConstants.tss.saveTraceSummaryBySubstrate(subSummaryInput); TestConstants.tss.saveTraceSummaryByLOT(lotSummaryInput); }*/ }
package com.fasteque.pachubewidget; import android.app.Service; import android.appwidget.AppWidgetManager; import android.content.Context; import android.content.Intent; //import android.content.SharedPreferences; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.IBinder; import android.widget.RemoteViews; public class PachubeWidgetService extends Service { public static final String UPDATE = "update"; //private static final String PREFS_NAME = "com.fasteque.PachubeWdiget"; private NetworkInfo nwkInfo = null; @Override public void onStart(Intent intent, int startId) { String command = intent.getAction(); int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID); RemoteViews remoteView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.pachubewidget_layout); AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getApplicationContext()); //SharedPreferences prefs = getApplicationContext().getSharedPreferences(PREFS_NAME, 0); if(command.equals(UPDATE)) { if(isOnline()) { ParsedFeed feed = RestClient.connect("http://www.pachube.com/api/feeds/" + PachubeWidgetConfig.loadFeedIDKeyPref(getApplicationContext(), appWidgetId) + ".xml", PachubeWidgetConfig.loadPachubeApiKeyPref(getApplicationContext(), appWidgetId)); if(feed != null) { remoteView.setTextViewText(R.id.feed_title, feed.getFeedTitle()); remoteView.setTextViewText(R.id.feed_description, feed.getFeedDescription()); if(feed.getFeedStatus().equals("frozen")) remoteView.setTextColor(R.id.feed_status, Color.GRAY); if(feed.getFeedStatus().equals("live")) remoteView.setTextColor(R.id.feed_status, Color.GREEN); remoteView.setTextViewText(R.id.feed_status, feed.getFeedStatus()); // TODO : loop all over the data if(feed.feedData != null) { remoteView.setTextViewText(R.id.feed_data_tag, feed.feedData.get(0).getTag()); if(feed.feedData.get(0).getValue().equals("")) remoteView.setTextViewText(R.id.feed_data_value, "N/A"); else remoteView.setTextViewText(R.id.feed_data_value, feed.feedData.get(0).getValue()); remoteView.setTextViewText(R.id.feed_data_unit, feed.feedData.get(0).getUnitName()); } } } else { remoteView.setTextViewText(R.id.feed_title, String.valueOf(PachubeWidgetConfig.loadFeedIDKeyPref(getApplicationContext(), appWidgetId))); remoteView.setTextViewText(R.id.feed_status, getString(R.string.no_connection)); } // apply changes to widget appWidgetManager.updateAppWidget(appWidgetId, remoteView); } super.onStart(intent, startId); } @Override public IBinder onBind(Intent arg0) { return null; } private boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); nwkInfo = cm.getActiveNetworkInfo(); if((nwkInfo == null) || !nwkInfo.isConnected()) return false; // check if roaming: to disable internet while roaming, just return false. if(nwkInfo.isRoaming()) return true; return true; } }
package com.jd.rpc.model; import java.util.HashMap; import java.util.Map; public class ProviderBeanMapContext { private static Map<Class,Object> beanMapInfo=new HashMap<Class, Object>(); public static void register(Class key,Object bean){ beanMapInfo.put(key,bean); } public static Object getBean(Class key){ return beanMapInfo.get(key); } }
import java.io.*; class Palindrome{ public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the sentence"); String str; int count=0; str=br.readLine(); String output="", ar[]= str.split(" "); for(int i=0;i < ar.length;i++){ if(palindromeCheck(ar[i])){ count++; output += ar[i] + " "; } } System.out.println("The Palindromes in the sentences are "+output); System.out.println("Number of Palindromes is "+count); } public static boolean palindromeCheck(String str){ char ch; int len=str.length(),mid=len/2; for(int i=0;i < mid;i++){ if(str.charAt(i)!=str.charAt(len-i-1)) return false; } return true; } }
package com.leo_sanchez.columbiatennisladder.Models; /** * Created by ldjam on 3/24/2018. */ public class Player { public Player(String firstName, String lastName, int position){ this.firstName = firstName; this.lastName = lastName; this.position = position; } public String firstName; public String lastName; public int position; public String getFullName(){ return lastName + ", " + firstName; } }
package org.squonk.execution.steps.impl; import org.apache.camel.CamelContext; import org.squonk.dataset.Dataset; import org.squonk.dataset.DatasetMetadata; import org.squonk.execution.steps.AbstractStep; import org.squonk.execution.steps.StepDefinitionConstants; import org.squonk.execution.variable.VariableManager; import org.squonk.types.BasicObject; import java.util.HashSet; import java.util.Set; import java.util.UUID; import java.util.logging.Logger; import java.util.stream.Stream; /** * Created by timbo on 29/12/15. */ public class DatasetUUIDFilterStep extends AbstractStep { private static final Logger LOG = Logger.getLogger(DatasetUUIDFilterStep.class.getName()); public static final String OPTION_UUIDS = StepDefinitionConstants.DatasetUUIDFilter.OPTION_UUIDS; @Override public void execute(VariableManager varman, CamelContext context) throws Exception { statusMessage = MSG_PREPARING_INPUT; Dataset<? extends BasicObject> input = fetchMappedInput("input", Dataset.class, varman, true); String uuidsOpt = getOption(OPTION_UUIDS, String.class); if (uuidsOpt == null) { throw new IllegalStateException("UUIDs not defined. Should be present as option named " + OPTION_UUIDS); } LOG.info("UUIDs: " + uuidsOpt); Set<UUID> uuids = parseUUIDs(uuidsOpt); statusMessage = "Filtering ..."; Stream <? extends BasicObject>output = input.getStream().filter((bo) -> uuids.contains(bo.getUUID())); Dataset<? extends BasicObject> results = new Dataset(output, deriveOutputDatasetMetadata(input.getMetadata())); createMappedOutput("output", Dataset.class, results, varman); statusMessage = generateStatusMessage(input.getSize(), results.getSize(), -1); LOG.info("Results: " + results.getMetadata());; } protected Set<UUID> parseUUIDs(String s) { String[] parts = s.split("[,\\n\\s]+"); Set<UUID> set = new HashSet<>(); for (int i = 0; i < parts.length ; i++) { String uuid = parts[i].trim(); set.add(UUID.fromString(uuid)); } return set; } protected DatasetMetadata deriveOutputDatasetMetadata(DatasetMetadata input) { if (input == null) { return new DatasetMetadata(BasicObject.class); } else { return new DatasetMetadata(input.getType(), input.getValueClassMappings(), 0, input.getProperties()); } } }
/* * Copyright (c) 2008-2019 Haulmont. * * 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.haulmont.reports.libintegration.extraction.controller; import com.haulmont.cuba.core.Persistence; import com.haulmont.reports.app.service.ReportService; import com.haulmont.reports.entity.BandDefinition; import com.haulmont.reports.entity.DataSet; import com.haulmont.reports.entity.Report; import com.haulmont.reports.exception.TemplateGenerationException; import com.haulmont.reports.fixture.yml.YmlBandUtil; import com.haulmont.reports.util.ReportHelper; import com.haulmont.yarg.reporting.ReportOutputDocument; import org.apache.commons.collections4.CollectionUtils; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.junit.Assert; import org.junit.Ignore; import org.springframework.core.io.ResourceLoader; import javax.inject.Inject; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URISyntaxException; import java.util.*; @Ignore public abstract class AbstractControllerTestClass { @Inject protected ReportService reportService; @Inject protected ReportHelper reportHelper; @Inject protected Persistence persistence; @Inject protected ResourceLoader resourceLoader; protected ReportOutputDocument createDocument(String bandFile, String template) throws IOException, TemplateGenerationException, URISyntaxException { BandDefinition root = YmlBandUtil.bandFrom( resourceLoader .getResource(bandFile).getFile()); Map<String, Object> params = new HashMap<>(); processEntityType(root, params); Report report = reportHelper.create(root, resourceLoader .getResource(template).getFile()); return reportService.createReport(report, params); } protected void processEntityType(BandDefinition root, Map<String, Object> params) { Optional.ofNullable(root.getChildren()).orElse(Collections.emptyList()).forEach(b-> { if (CollectionUtils.isNotEmpty(b.getReportQueries())) { b.getReportQueries().stream() .map(DataSet.class::cast) .forEach(ds-> { switch (ds.getType()) { case SINGLE: params.put( ds.getEntityParamName(), persistence.callInTransaction(em-> em.createQuery(String.format("select e from %s e", ds.getScript())) .setMaxResults(1) .getFirstResult() )); break; case MULTI: params.put( ds.getListEntitiesParamName(), persistence.callInTransaction(em-> em.createQuery(String.format("select e from %s e", ds.getScript())) .getResultList() )); break; } }); } processEntityType((BandDefinition)b, params); }); } protected void assertCrossDataDocument(ReportOutputDocument document) throws IOException, InvalidFormatException { assertCrossDataDocument(persistence.callInTransaction(em -> em.createQuery("select e.login from test$User e", String.class).getResultList()), document); } protected void assertCrossDataDocument(List<String> users, ReportOutputDocument document) throws IOException, InvalidFormatException { Workbook workbook = WorkbookFactory.create(new ByteArrayInputStream(document.getContent())); Sheet sheet = workbook.getSheetAt(0); Set<String> months = persistence.callInTransaction(em -> new HashSet<>( em.createQuery("select e.name from test$Month e", String.class).getResultList())); Assert.assertEquals(users.size() + 1, sheet.getPhysicalNumberOfRows()); for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) { Assert.assertTrue(users.contains(sheet.getRow(i).getCell(0).getStringCellValue())); for (int j = 1; j <= months.size(); j++) { if (CellType.NUMERIC == sheet.getRow(i).getCell(j).getCellType()) { Assert.assertTrue(sheet.getRow(i).getCell(j).getNumericCellValue() >= 0); } } } for (int i = 1; i <= months.size(); i++) { Assert.assertTrue(months.contains(sheet.getRow(0).getCell(i).getStringCellValue())); } } }
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) package com.pointinside.android.piwebservices.service; import android.content.*; import android.database.Cursor; import android.net.Uri; import android.os.*; import android.util.Log; import com.pointinside.android.piwebservices.net.DealsClient; import com.pointinside.android.piwebservices.provider.PIWebServicesContract; import com.pointinside.android.piwebservices.util.BatchProcessorHelper; import java.util.*; // Referenced classes of package com.pointinside.android.piwebservices.service: // AbstractRESTServiceHelper public class DealsService extends AbstractRESTServiceHelper { public DealsService() { super(TAG); registerMethodHandler("com.pointinside.android.app.service.DealsService.GET_NEARBY_DEALS", 1, mNearbyDealsHandler); registerMethodHandler("com.pointinside.android.app.service.DealsService.GET_DESTINATION_DEALS", 2, mDestinationDealsHandler); } private static void addInsertDealOps(ArrayList arraylist, Uri uri, ArrayList arraylist1, String s) { Iterator iterator = arraylist1.iterator(); do { if(!iterator.hasNext()) return; com.pointinside.android.piwebservices.net.DealsClient.Deal deal = (com.pointinside.android.piwebservices.net.DealsClient.Deal)iterator.next(); android.content.ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(com.pointinside.android.piwebservices.provider.PIWebServicesContract.DealsResults.CONTENT_URI).withValue("request_type", s).withValue("title", deal.getTitle()).withValue("organization", deal.getPlaceName()).withValue("display_image", deal.getDisplayImage()); String s1; if(uri != null) builder.withValue("request_id", Long.valueOf(ContentUris.parseId(uri))); else builder.withValueBackReference("request_id", 0); s1 = getDataSource(deal.getDataSources()); builder.withValue("datasource", s1); builder.withValue("datasource_id", deal.getId(s1)); if(deal.hasType()) builder.withValue("type", deal.getType()); if(deal.hasDescription()) builder.withValue("description", deal.getDescription()); if(deal.hasDisplayStartDate()) builder.withValue("display_start_date", deal.getDisplayStartDate()); if(deal.hasDisplayEndDate()) builder.withValue("display_end_date", deal.getDisplayEndDate()); if(deal.hasStartDate()) builder.withValue("start_date", deal.getStartDate()); if(deal.hasEndDate()) builder.withValue("end_date", deal.getEndDate()); if(deal.hasThumbnailImage()) builder.withValue("thumbnail_image", deal.getThumbnailImage()); if(deal.hasBrand()) builder.withValue("brand", deal.getBrand()); if(deal.hasDescription()) builder.withValue("description", deal.getDescription()); if(deal.hasLatLong()) { builder.withValue("latitude", Double.valueOf(deal.getLatitude())); builder.withValue("longitude", Double.valueOf(deal.getLongitude())); } if(deal.hasPlaceUUID()) builder.withValue("place_uuid", deal.getPlaceUUID()); if(deal.hasVenueUUID()) builder.withValue("venue_uuid", deal.getVenueUUID()); if(deal.hasDistance()) builder.withValue("distance", deal.getDistance()); if(deal.hasCategory()) builder.withValue("category", deal.getCategory()); arraylist.add(builder.build()); } while(true); } private static void deleteDealsResults(ContentResolver contentresolver, BatchProcessorHelper batchprocessorhelper, Uri uri, String s, long l) throws OperationApplicationException, RemoteException { try { Cursor cursor = contentresolver.query(uri, null, (new StringBuilder("timestamp < ")).append(l).toString(), null, null); boolean flag = cursor.moveToNext(); while(flag) { long l1 = cursor.getLong(cursor.getColumnIndexOrThrow("_id")); batchprocessorhelper.add(ContentProviderOperation.newDelete(uri).withSelection((new StringBuilder("_id = ")).append(l1).toString(), null).build()); batchprocessorhelper.add(ContentProviderOperation.newDelete(com.pointinside.android.piwebservices.provider.PIWebServicesContract.DealsResults.makeResultsUriByRequest(l1, s)).build()); batchprocessorhelper.runWhenThresholdReached(); flag = cursor.moveToNext(); } cursor.close(); } catch(Exception exception) { //cursor.close(); //throw exception; } } private static String getDataSource(Set set) { if(set.size() != 1) throw new IllegalStateException("Deals should not have multiple data sources today"); Iterator iterator = set.iterator(); if(iterator.hasNext()) return (String)iterator.next(); else throw new AssertionError(); } public static void loadDestinationDeals(Context context, ResultReceiver resultreceiver, Bundle bundle, String s) { Intent intent = new Intent("com.pointinside.android.app.service.DealsService.GET_DESTINATION_DEALS", null, context, DealsService.class); intent.putExtra("result-receiver", resultreceiver); intent.putExtra("extras", bundle); intent.putExtra("venue", s); context.startService(intent); } public static void loadNearbyDeals(Context context, ResultReceiver resultreceiver, Bundle bundle, double d, double d1, int i) { Intent intent = new Intent("com.pointinside.android.app.service.DealsService.GET_NEARBY_DEALS", null, context, DealsService.class); intent.putExtra("result-receiver", resultreceiver); intent.putExtra("extras", bundle); intent.putExtra("latitude", d); intent.putExtra("longitude", d1); intent.putExtra("radius", i); context.startService(intent); } protected void onResultsCleanup() throws RemoteException, OperationApplicationException { long l = System.currentTimeMillis() - 0xa4cb800L; BatchProcessorHelper batchprocessorhelper = new BatchProcessorHelper(getContentResolver(), PIWebServicesContract.getAuthority()); deleteDealsResults(getContentResolver(), batchprocessorhelper, com.pointinside.android.piwebservices.provider.PIWebServicesContract.DestinationDealsRequests.CONTENT_URI, "destination", l); deleteDealsResults(getContentResolver(), batchprocessorhelper, com.pointinside.android.piwebservices.provider.PIWebServicesContract.NearbyDealsRequests.CONTENT_URI, "nearby", l); batchprocessorhelper.runBatch(); } public static final String ACTION_GET_DESTINATION_DEALS = "com.pointinside.android.app.service.DealsService.GET_DESTINATION_DEALS"; public static final String ACTION_GET_NEARBY_DEALS = "com.pointinside.android.app.service.DealsService.GET_NEARBY_DEALS"; private static final long DESTINATION_DEALS_CACHE_LENGTH = 0x36ee80L; public static final String EXTRA_CACHED_RESULT = "cached-result"; public static final String EXTRA_LATITUDE = "latitude"; public static final String EXTRA_LONGITUDE = "longitude"; public static final String EXTRA_RADIUS = "radius"; public static final String EXTRA_VENUE = "venue"; public static final int RESULT_GET_DESTINATION_DEALS = 2; public static final int RESULT_GET_NEARBY_DEALS = 1; private static final String TAG = DealsService.class.getSimpleName(); private final AbstractRESTServiceHelper.MethodHandler mDestinationDealsHandler = new AbstractRESTServiceHelper.MethodHandler() { private Uri queryRemoteService(Uri uri, String s) throws com.pointinside.android.api.net.JSONWebRequester.RestResponseException, OperationApplicationException, RemoteException { com.pointinside.android.piwebservices.net.DealsClient.DestinationDealsRequest destinationdealsrequest = new com.pointinside.android.piwebservices.net.DealsClient.DestinationDealsRequest(); destinationdealsrequest.venue = s; com.pointinside.android.piwebservices.net.DealsClient.DealsResult dealsresult = DealsClient.getInstance(DealsService.this).getDestinationDeals(destinationdealsrequest); ArrayList arraylist = new ArrayList(); android.content.ContentProviderOperation.Builder builder; ContentProviderResult acontentproviderresult[]; if(uri != null) builder = ContentProviderOperation.newUpdate(uri); else builder = ContentProviderOperation.newInsert(com.pointinside.android.piwebservices.provider.PIWebServicesContract.DestinationDealsRequests.CONTENT_URI).withValue("venue", destinationdealsrequest.venue); builder.withValue("timestamp", Long.valueOf(System.currentTimeMillis())); arraylist.add(builder.build()); if(uri != null) arraylist.add(ContentProviderOperation.newDelete(com.pointinside.android.piwebservices.provider.PIWebServicesContract.DealsResults.makeResultsUriByRequest(uri, "destination")).build()); DealsService.addInsertDealOps(arraylist, uri, dealsresult.deals, "destination"); acontentproviderresult = getContentResolver().applyBatch(PIWebServicesContract.getAuthority(), arraylist); if(uri == null) uri = acontentproviderresult[0].uri; return com.pointinside.android.piwebservices.provider.PIWebServicesContract.DealsResults.makeResultsUriByRequest(ContentUris.parseId(uri), "destination"); } public void executeMethod(int i, Intent intent, Bundle bundle) throws com.pointinside.android.api.net.JSONWebRequester.RestResponseException, OperationApplicationException, RemoteException { ResultReceiver resultreceiver; String s; Cursor cursor; long l; try { resultreceiver = (ResultReceiver)intent.getParcelableExtra("result-receiver"); s = intent.getStringExtra("venue"); cursor = getContentResolver().query(com.pointinside.android.piwebservices.provider.PIWebServicesContract.DestinationDealsRequests.CONTENT_URI, null, "venue = ?", new String[] { s }, null); l = 0L; boolean flag = cursor.moveToFirst(); Uri uri; Uri uri1; uri = null; uri1 = null; if(flag) { long l1; uri1 = com.pointinside.android.piwebservices.provider.PIWebServicesContract.DestinationDealsRequests.makeRequestUri(cursor.getLong(cursor.getColumnIndexOrThrow("_id"))); uri = com.pointinside.android.piwebservices.provider.PIWebServicesContract.DealsResults.makeResultsUriByRequest(uri1, "destination"); l1 = cursor.getLong(cursor.getColumnIndexOrThrow("timestamp")); l = l1; } cursor.close(); if(resultreceiver != null && uri != null) { Bundle bundle1 = createResultData(intent); bundle1.putBoolean("cached-result", true); bundle1.putParcelable("result-uri", uri); resultreceiver.send(i, bundle1); } long l2 = System.currentTimeMillis(); if(l == 0L || l2 > 0x36ee80L + l) { Log.d(DealsService.TAG, (new StringBuilder("Refreshing deals from remote service for venue=")).append(s).toString()); Uri uri2 = queryRemoteService(uri1, s); if(resultreceiver != null) { bundle.putParcelable("result-uri", uri2); resultreceiver.send(i, bundle); } } return; } catch(Exception exception) { //exception; //cursor.close(); //throw exception; } } final DealsService this$0; { this$0 = DealsService.this; // super(); } } ; private final AbstractRESTServiceHelper.MethodHandler mNearbyDealsHandler = new AbstractRESTServiceHelper.SimpleMethodHandler() { protected Uri onExecuteMethod(Intent intent) throws com.pointinside.android.api.net.JSONWebRequester.RestResponseException, OperationApplicationException, RemoteException { DealsClient.NearbyDealsRequest nearbydealsrequest = new DealsClient.NearbyDealsRequest(); nearbydealsrequest.latitude = intent.getDoubleExtra("latitude", 0.0D); nearbydealsrequest.longitude = intent.getDoubleExtra("longitude", 0.0D); nearbydealsrequest.radius = intent.getIntExtra("radius", 0); nearbydealsrequest.maxResults = 100; DealsClient.DealsResult dealsresult = DealsClient.getInstance(DealsService.this).getNearbyDeals(nearbydealsrequest); ArrayList arraylist = new ArrayList(); arraylist.add(ContentProviderOperation.newInsert(PIWebServicesContract.NearbyDealsRequests.CONTENT_URI).withValue("latitude", Double.valueOf(nearbydealsrequest.latitude)).withValue("longitude", Double.valueOf(nearbydealsrequest.longitude)).withValue("radius", Integer.valueOf(nearbydealsrequest.radius)).withValue("timestamp", Long.valueOf(System.currentTimeMillis())).build()); DealsService.addInsertDealOps(arraylist, null, dealsresult.deals, "nearby"); return PIWebServicesContract.DealsResults.makeResultsUriByRequest(getContentResolver().applyBatch(PIWebServicesContract.getAuthority(), arraylist)[0].uri, "nearby"); } final DealsService this$0; { this$0 = DealsService.this; // super(); } } ; }
/* * Project: OSMP * FileName: Cacheable.java * version: V1.0 */ package com.osmp.cache.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import com.osmp.cache.core.CacheKeyGenerator; import com.osmp.cache.core.CacheableDefine; import com.osmp.cache.core.DefaultCacheKeyGenerator; /** * Description: 缓存注解 * * @author: wangkaiping * @date: 2014年8月8日 上午10:47:10 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Cacheable { /** * 缓存方法的名称 * * @return */ public String name(); /** * 缓存key前缀 * * @return */ public String prefix() default ""; /** * 缓存key生成策略 * * @return */ public Class<? extends CacheKeyGenerator> cacheKeyGenerator() default DefaultCacheKeyGenerator.class; /** * 存活时间 单位为秒<br> * 即对象最新失效的最大时间 * * @return */ public int timeToLive() default 1800; /** * 空闲时间 单位为秒<br> * 即距离上一次访问该对象后空闲的时间,如果超过则失效.受timeToLive约束 * * @return */ public int timeToIdle() default 0; /** * 状态 CacheableDefine.STATE_OPEN, CacheableDefine.STATE_CLOSE; * * @return */ public int state() default CacheableDefine.STATE_OPEN; }
package com.example.rest.resource; import java.io.Serializable; public class BaseResource implements Serializable { }
package com.oa.role.form; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonBackReference; import com.oa.group.form.Group; import com.oa.user.form.UserInfo; @Entity @Table(name = "ROLE_INFO") public class RoleInfo { @Id @GeneratedValue @Column(name = "ROLE_ID") private Integer roleId; @Column(name = "ROLE_NAME") private String roleName; @Column(name = "ROLE_DESC") private String roleDesc; @Column(name = "ROLE_MARK") private String roleMark; @ManyToMany(mappedBy = "roles") @JsonBackReference private Set<UserInfo> users = new HashSet<UserInfo>(); @ManyToMany(mappedBy="groupRoles") @JsonBackReference private Set<Group> roleGroups = new HashSet<Group>(); public Set<Group> getRoleGroups() { return roleGroups; } public void setRoleGroups(Set<Group> roleGroups) { this.roleGroups = roleGroups; } public Set<UserInfo> getUsers() { return users; } public void setUsers(Set<UserInfo> users) { this.users = users; } public Integer getRoleId() { return roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getRoleDesc() { return roleDesc; } public void setRoleDesc(String roleDesc) { this.roleDesc = roleDesc; } public String getRoleMark() { return roleMark; } public void setRoleMark(String roleMark) { this.roleMark = roleMark; } }
package person.zhao.anno.mapbean; public class Test { public void p() throws Exception { System.out.println(new String("123").getClass() == String.class); if (new String("123") instanceof String) { System.out.println("ok ~~~~"); } else { System.out.println("ng ~~~~"); } Class<?> c = Person.class.getDeclaredField("age").getType(); System.out.println(c); System.out.println(c == int.class); System.out.println(c == Integer.class); System.out.println(c.equals(int.class)); } public static void main(String[] args) { try { new Test().p(); } catch (Exception e) { e.printStackTrace(); } } }
package controler; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import javax.faces.bean.ManagedBean; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.servlet.http.HttpServletResponse; import model.ArrayDeRetorno; import model.Localizacao; import util.RequisicaoWebService; @ManagedBean public class LocalizacaoEstaticaBean implements Serializable { private String enderecoOrigem; private String enderecoDestino; private ArrayDeRetorno arrayDeRetorno; public ArrayDeRetorno getArrayDeRetorno() { return arrayDeRetorno; } public void setArrayDeRetorno(ArrayDeRetorno arrayDeRetorno) { this.arrayDeRetorno = arrayDeRetorno; } public String getEnderecoOrigem() { return enderecoOrigem; } public void setEnderecoOrigem(String enderecoOrigem) { this.enderecoOrigem = enderecoOrigem; } public String getEnderecoDestino() { return enderecoDestino; } public void setEnderecoDestino(String enderecoDestino) { this.enderecoDestino = enderecoDestino; } public void acharCoordenadas() throws IOException{ RequisicaoWebService requisicaoWebService = new RequisicaoWebService(); this.setArrayDeRetorno(requisicaoWebService.request(this.enderecoOrigem, this.enderecoDestino)); HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse(); response.sendRedirect("paginaMapa.xhtml"); FacesContext.getCurrentInstance().responseComplete(); System.out.println(this.arrayDeRetorno.getArrayAPI1().get(0).getLatitudeDestino()); } }
package com.wentry.netty.handle; import io.netty.channel.ChannelDuplexHandler; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPromise; import java.util.concurrent.TimeUnit; /** * @author WJX * @title: SimpleDuplexHanlder * @projectName architecture-parent * @description: TODO * @date 2020/6/10 0010 */ @ChannelHandler.Sharable public class SimpleDuplexHandler extends ChannelDuplexHandler { @Override public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { super.close(ctx, promise); } @Override public void read(ChannelHandlerContext ctx) throws Exception { System.out.println("outbound read."); super.read(ctx); } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { System.out.println("outbound write:"+msg); super.write(ctx, msg, promise); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { super.channelInactive(ctx); } @Override public void handlerAdded(final ChannelHandlerContext ctx) { ctx.executor().schedule(() -> { ctx.channel().write("hello netty"); ctx.write("hello world"); }, 3, TimeUnit.SECONDS); } }
/** * FileName: UUid * Author: yangqinkuan * Date: 2019-1-13 17:59 * Description: */ package com.ice.find.util.codegenerate; import java.util.UUID; public class UUid { public final static synchronized String getUUID() { return UUID.randomUUID().toString().replace("-", ""); } }
/* * Copyright Verizon Media, Licensed under the terms of the Apache License, Version 2.0. See LICENSE file in project root for terms. */ package com.yahoo.cubed.json; import com.fasterxml.jackson.databind.ObjectMapper; import com.yahoo.cubed.App; import com.yahoo.cubed.settings.CLISettings; import com.yahoo.cubed.source.ConfigurationLoader; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Test update datamart class. */ public class UpdateDatamartTest { UpdateDatamart tg; String req; /** * Setup database. */ @BeforeClass public static void initialize() throws Exception { CLISettings.DB_CONFIG_FILE = "src/test/resources/database-configuration.properties"; App.prepareDatabase(); App.dropAllFields(); App.loadSchemas("src/test/resources/schemas/"); ConfigurationLoader.load(); } /** * Test UpdateDatamart with invalid query string (missing data). */ @Test public void testInvalidUpdateDatamartMissingDescription() throws Exception { req = "{" + "\"owner\":\"test\"," + "\"projections\":[{\"column_id\":\"9\",\"key\":\"\",\"alias\":\"bcookie\",\"aggregate\":\"NONE\", \"schema_name\":\"schema1\"}]," + "\"projectionVMs\":[[]]," + "\"filter\":{" + "\"condition\":\"AND\"," + "\"rules\":[" + "{\"id\":\"filter_tag\",\"field\":\"filter_tag\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"is_null\",\"value\":null}," + "{\"id\":\"network\",\"field\":\"network\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"on\"}," + "{\"id\":\"pty_family\",\"field\":\"pty_family\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"sports\"}," + "{\"id\":\"pty_device\",\"field\":\"pty_device\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"desktop\"}," + "{\"id\":\"pty_experience\",\"field\":\"pty_experience\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"web\"}," + "{\"id\":\"event_family\",\"field\":\"event_family\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"view\"}" + "]}," + "\"backfillEnabled\":true," + "\"backfillStartDate\":\"2018-03-13\"," + "\"endTimeEnabled\":false," + "\"endTimeDate\":null}"; ObjectMapper mapper = new ObjectMapper(); tg = mapper.readValue(req, UpdateDatamart.class); Assert.assertEquals(tg.isValid(), "Missing data mart description"); } /** * Test UpdateDatamart with invalid query string (missing owner). */ @Test public void testInvalidUpdateDatamartMissingOwner() throws Exception { req = "{" + "\"description\":\"test\"," + "\"projections\":[{\"column_id\":\"9\",\"key\":\"\",\"alias\":\"bcookie\",\"aggregate\":\"NONE\", \"schema_name\":\"schema1\"}]," + "\"projectionVMs\":[[]]," + "\"filter\":{" + "\"condition\":\"AND\"," + "\"rules\":[" + "{\"id\":\"filter_tag\",\"field\":\"filter_tag\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"is_null\",\"value\":null}," + "{\"id\":\"network\",\"field\":\"network\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"on\"}," + "{\"id\":\"pty_family\",\"field\":\"pty_family\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"sports\"}," + "{\"id\":\"pty_device\",\"field\":\"pty_device\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"desktop\"}," + "{\"id\":\"pty_experience\",\"field\":\"pty_experience\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"web\"}," + "{\"id\":\"event_family\",\"field\":\"event_family\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"view\"}" + "]}," + "\"backfillEnabled\":true," + "\"backfillStartDate\":\"2018-03-13\"," + "\"endTimeEnabled\":false," + "\"endTimeDate\":null}"; ObjectMapper mapper = new ObjectMapper(); tg = mapper.readValue(req, UpdateDatamart.class); Assert.assertEquals(tg.isValid(), "Missing data mart owner"); } /** * Test UpdateDatamart with invalid query string (invalid filter). */ @Test public void testInvalidUpdateDatamartWithInvalidFilter() throws Exception { req = "{" + "\"description\":\"test\"," + "\"owner\":\"test\"," + "\"projections\":[{\"column_id\":\"9\",\"key\":\"\",\"alias\":\"bcookie\",\"aggregate\":\"NONE\", \"schema_name\":\"schema1\"}]," + "\"projectionVMs\":[[]]," + "\"filter\":{" + "\"rules\":[" + "{\"id\":\"filter_tag\",\"field\":\"filter_tag\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"is_null\",\"value\":null}," + "{\"id\":\"network\",\"field\":\"network\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"on\"}," + "{\"id\":\"pty_family\",\"field\":\"pty_family\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"sports\"}," + "{\"id\":\"pty_device\",\"field\":\"pty_device\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"desktop\"}," + "{\"id\":\"pty_experience\",\"field\":\"pty_experience\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"web\"}," + "{\"id\":\"event_family\",\"field\":\"event_family\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"view\"}" + "]}," + "\"backfillEnabled\":true," + "\"backfillStartDate\":\"2018-03-13\"," + "\"endTimeEnabled\":false," + "\"endTimeDate\":null}"; ObjectMapper mapper = new ObjectMapper(); tg = mapper.readValue(req, UpdateDatamart.class); Assert.assertEquals(tg.isValid(), "filter must have junction operation at the top level."); } /** * Test UpdateDatamart with invalid query string (invalid backfill). */ @Test public void testInvalidUpdateDatamartWithInvalidBackfill() throws Exception { req = "{" + "\"description\":\"test\"," + "\"owner\":\"test\"," + "\"projections\":[{\"column_id\":\"9\",\"key\":\"\",\"alias\":\"bcookie\",\"aggregate\":\"NONE\", \"schema_name\":\"schema1\"}]," + "\"projectionVMs\":[[]]," + "\"filter\":{" + "\"condition\":\"AND\"," + "\"rules\":[" + "{\"id\":\"filter_tag\",\"field\":\"filter_tag\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"is_null\",\"value\":null}," + "{\"id\":\"network\",\"field\":\"network\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"on\"}," + "{\"id\":\"pty_family\",\"field\":\"pty_family\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"sports\"}," + "{\"id\":\"pty_device\",\"field\":\"pty_device\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"desktop\"}," + "{\"id\":\"pty_experience\",\"field\":\"pty_experience\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"web\"}," + "{\"id\":\"event_family\",\"field\":\"event_family\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"view\"}" + "]}," + "\"backfillEnabled\":true," + "\"endTimeEnabled\":false," + "\"endTimeDate\":null}"; ObjectMapper mapper = new ObjectMapper(); tg = mapper.readValue(req, UpdateDatamart.class); Assert.assertEquals(tg.isValid(), "Missing backfill start date"); } /** * Test UpdateDatamart with invalid query string (missing endDate). */ @Test public void testInvalidUpdateDatamartMissingEndDate() throws Exception { req = "{" + "\"description\":\"test\"," + "\"owner\":\"test\"," + "\"projections\":[{\"column_id\":\"9\",\"key\":\"\",\"alias\":\"bcookie\",\"aggregate\":\"NONE\", \"schema_name\":\"schema1\"}]," + "\"projectionVMs\":[[]]," + "\"filter\":{" + "\"condition\":\"AND\"," + "\"rules\":[" + "{\"id\":\"filter_tag\",\"field\":\"filter_tag\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"is_null\",\"value\":null}," + "{\"id\":\"network\",\"field\":\"network\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"on\"}," + "{\"id\":\"pty_family\",\"field\":\"pty_family\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"sports\"}," + "{\"id\":\"pty_device\",\"field\":\"pty_device\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"desktop\"}," + "{\"id\":\"pty_experience\",\"field\":\"pty_experience\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"web\"}," + "{\"id\":\"event_family\",\"field\":\"event_family\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"view\"}" + "]}," + "\"backfillEnabled\":true," + "\"backfillStartDate\":\"2018-03-13\"," + "\"endTimeEnabled\":true," + "\"endTimeDate\":null}"; ObjectMapper mapper = new ObjectMapper(); tg = mapper.readValue(req, UpdateDatamart.class); Assert.assertEquals(tg.isValid(), "Missing end time date"); } /** * Test UpdateDatamart with invalid query string (invalid format). */ @Test public void testInvalidUpdateDatamartInvalidVMFormat() throws Exception { req = "{" + "\"description\":\"test\"," + "\"owner\":\"test\"," + "\"projections\":[{\"column_id\":\"9\",\"key\":\"\",\"alias\":\"bcookie\",\"aggregate\":\"NONE\", \"schema_name\":\"schema1\"}]," + "\"projectionVMs\":[[[\"testv\"]]]," + "\"filter\":{" + "\"condition\":\"AND\"," + "\"rules\":[" + "{\"id\":\"filter_tag\",\"field\":\"filter_tag\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"is_null\",\"value\":null}," + "{\"id\":\"network\",\"field\":\"network\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"on\"}," + "{\"id\":\"pty_family\",\"field\":\"pty_family\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"sports\"}," + "{\"id\":\"pty_device\",\"field\":\"pty_device\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"desktop\"}," + "{\"id\":\"pty_experience\",\"field\":\"pty_experience\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"web\"}," + "{\"id\":\"event_family\",\"field\":\"event_family\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"view\"}" + "]}," + "\"backfillEnabled\":true," + "\"backfillStartDate\":\"2018-03-13\"," + "\"endTimeEnabled\":false," + "\"endTimeDate\":null}"; ObjectMapper mapper = new ObjectMapper(); tg = mapper.readValue(req, UpdateDatamart.class); Assert.assertEquals(tg.isValid(), "Wrong format of value mapping"); } /** * Test UpdateDatamart with invalid query string (ambiguous VM). */ @Test public void testInvalidUpdateDatamartAmbiguousVM() throws Exception { req = "{" + "\"description\":\"test\"," + "\"owner\":\"test\"," + "\"projections\":[{\"column_id\":\"9\",\"key\":\"\",\"alias\":\"bcookie\",\"aggregate\":\"NONE\", \"schema_name\":\"schema1\"}]," + "\"projectionVMs\":[[[\"testv\", \"testa\", \"equal\"], [\"testv\", \"testb\", \"equal\"]]]," + "\"filter\":{" + "\"condition\":\"AND\"," + "\"rules\":[" + "{\"id\":\"filter_tag\",\"field\":\"filter_tag\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"is_null\",\"value\":null}," + "{\"id\":\"network\",\"field\":\"network\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"on\"}," + "{\"id\":\"pty_family\",\"field\":\"pty_family\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"sports\"}," + "{\"id\":\"pty_device\",\"field\":\"pty_device\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"desktop\"}," + "{\"id\":\"pty_experience\",\"field\":\"pty_experience\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"web\"}," + "{\"id\":\"event_family\",\"field\":\"event_family\",\"type\":\"string\",\"input\":\"text\",\"operator\":\"equal\",\"value\":\"view\"}" + "]}," + "\"backfillEnabled\":true," + "\"backfillStartDate\":\"2018-03-13\"," + "\"endTimeEnabled\":false," + "\"endTimeDate\":null}"; ObjectMapper mapper = new ObjectMapper(); tg = mapper.readValue(req, UpdateDatamart.class); Assert.assertEquals(tg.isValid(), "Ambiguous value mapping for value:testv"); } }
package com.mglowinski.restaurants.model.dto; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import java.util.List; @Data @Builder @NoArgsConstructor @AllArgsConstructor public class RestaurantCreateDto { private String name; private MenuDto menuDto; private List<TableDto> tableDtos; }
/* SimpleWebApp.java Purpose: Description: History: Tue Feb 27 09:27:03 2007, Created by tomyeh Copyright (C) 2007 Potix Corporation. All Rights Reserved. {{IS_RIGHT This program is distributed under LGPL Version 2.1 in the hope that it will be useful, but WITHOUT ANY WARRANTY. }}IS_RIGHT */ package org.zkoss.zk.ui.http; import java.util.Map; import java.util.Set; import java.util.Iterator; import java.util.Enumeration; import java.net.URL; import java.net.MalformedURLException; import java.io.InputStream; import javax.servlet.ServletContext; import org.zkoss.util.CollectionsX; import org.zkoss.web.servlet.xel.AttributesMap; import org.zkoss.zk.ui.Executions; import org.zkoss.zk.ui.Execution; import org.zkoss.zk.ui.WebApp; import org.zkoss.zk.ui.UiException; import org.zkoss.zk.ui.util.Configuration; import org.zkoss.zk.ui.ext.ScopeListener; import org.zkoss.zk.ui.impl.AbstractWebApp; import org.zkoss.zk.ui.impl.ScopeListeners; /** * A servlet-based Web application. * * @author tomyeh */ public class SimpleWebApp extends AbstractWebApp { private ServletContext _ctx; private final ScopeListeners _scopeListeners = new ScopeListeners(this); public SimpleWebApp() { } //super// public void init(Object context, Configuration config) { if (context == null) throw new IllegalArgumentException("context"); _ctx = (ServletContext)context; super.init(context, config); } private final Map _attrs = new AttributesMap() { protected Enumeration getKeys() { return _ctx.getAttributeNames(); } protected Object getValue(String key) { return _ctx.getAttribute(key); } protected void setValue(String key, Object val) { _ctx.setAttribute(key, val); } protected void removeValue(String key) { _ctx.removeAttribute(key); } }; public Object getAttribute(String name) { return _ctx.getAttribute(name); } public boolean hasAttribute(String name) { return getAttribute(name) != null; //Servlet limitation } public Object setAttribute(String name, Object value) { Object old = _ctx.getAttribute(name); _ctx.setAttribute(name, value); return old; } public Object removeAttribute(String name) { Object old = _ctx.getAttribute(name); _ctx.removeAttribute(name); return old; } public Map getAttributes() { return _attrs; } public boolean addScopeListener(ScopeListener listener) { return _scopeListeners.addScopeListener(listener); } public boolean removeScopeListener(ScopeListener listener) { return _scopeListeners.removeScopeListener(listener); } /** Returns all scope listeners. */ /*package*/ ScopeListeners getScopeListeners() { return _scopeListeners; } public String getUpdateURI() { return getUpdateURI(true); } public String getUpdateURI(boolean encode) { final String uri = getWebManager().getUpdateURI(); return encode ? Executions.getCurrent().encodeURL(uri): uri; } private WebManager getWebManager() { return WebManager.getWebManager(this); } public WebApp getWebApp(String uripath) { final ServletContext another = _ctx.getContext(uripath); if (another != null) { final WebManager webman = WebManager.getWebManagerIfAny(another); if (webman != null) return webman.getWebApp(); } return null; } public String getDirectory() { return null; } public URL getResource(String path) { if (path.startsWith("~./")) return getWebManager() .getClassWebResource().getResource(path.substring(2)); try { return _ctx.getResource(path); } catch (MalformedURLException ex) { throw new UiException("Failed to retrieve "+path, ex); } } public InputStream getResourceAsStream(String path) { if (path.startsWith("~./")) return getWebManager() .getClassWebResource().getResourceAsStream(path.substring(2)); return _ctx.getResourceAsStream(path); } public String getInitParameter(String name) { return _ctx.getInitParameter(name); } public Iterator getInitParameterNames() { return new CollectionsX.EnumerationIterator( _ctx.getInitParameterNames()); } public String getRealPath(String path) { return _ctx.getRealPath(path); } public String getMimeType(String file) { return _ctx.getMimeType(file); } public Set getResourcePaths(String path) { return _ctx.getResourcePaths(path); } public Object getNativeContext() { return _ctx; } }
package symap.mapper; import java.awt.geom.Point2D; import java.awt.Color; import java.awt.Point; import symap.contig.Clone; import symap.contig.Contig; import symap.block.Block; import symap.marker.MarkerTrack; class BESHit { private Clone clone; public BESHit() { } public void clear(Hit parent) { if (clone != null) clone.removeHit(parent); } public void set(Hit parent, MarkerTrack mt, String name, int contig) { if (clone != null) clone.removeHit(parent); if (mt instanceof Contig) clone = ((Contig)mt).getClone(name); else clone = null; if (clone != null) clone.addHit(parent); } public boolean isFiltered(MarkerTrack track, HitFilter filter, int contig) { if (track instanceof Block) return !((Block)track).isContigVisible(contig); return clone == null || !clone.isInRange(); } public boolean isVisible(MarkerTrack track, int contig) { if (track instanceof Block) return ((Block)track).isContigVisible(contig); return clone != null && clone.isVisible(); } public Point2D getCPoint(MarkerTrack track, int orientation, Point loc, int contig, int pos, byte bes) { Point2D p; Point2D cpoint = new Point2D.Double(); if (track instanceof Block) { p = ((Block)track).getPoint(pos,orientation,contig); cpoint.setLocation(p.getX()+loc.getX(),p.getY()+loc.getY()); } else { p = clone.getEndPoint(bes); cpoint.setLocation(p.getX()+loc.getX(),p.getY()+loc.getY()); } return cpoint; } public boolean isHighlighted() { return (clone != null && clone.isHover()); } public Color getCColor(boolean colorByStrand, boolean orientation) { if (clone != null && clone.isHover()) return Mapper.besLineHighlightColor; if (colorByStrand) return orientation ? Mapper.posOrientLineColor : Mapper.negOrientLineColor; return Mapper.besLineColor; } }
package com; public class Some { public static void main(String[] args) { System.out.println("Yes"); System.out.println("I`m new branch"); } }
package com.register.manager.model; public enum Login { GUFFAW, HITHERTO, LIGATURE, GUIDON, HOARY, LIMNER, GUILLOCHE, HOBBLEDEHOY, TITMOUSE, HOLYSTONE }
package com.company.core.checker; import com.company.tax.user.entity.User; /** * 用户权限验证 * @author Dongfuming * @date 2016-5-13 下午9:51:11 */ public interface UserPrivilegeChecker { /** 判断用户是否有该权限。一个用户,多个角色,一个角色,多个权限 */ public boolean isPrivilegeAccessible(User user, String privilege); }
package pocketserver.packets; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.DatagramPacket; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.logging.Level; import java.util.logging.Logger; import pocketserver.Hex; import pocketserver.PacketHandler; public class Packet84 extends Packet { private int packetType; private byte[] count = new byte[3]; private byte[] buffer; private Queue customPackets = new LinkedList(); private int packetLength; private int len; public Packet84(DatagramPacket packet) { ByteBuffer b = ByteBuffer.wrap(packet.getData()); packetType = Hex.byteToInt((int) b.get()); if (packetType != 0x84) { return; } b.get(count); len = packet.getLength()-4; buffer = new byte[len]; b.get(buffer); } @Override public DatagramPacket getPacket() { return null; } @Override public void process(PacketHandler handler) { splitPacket(); Iterator it = customPackets.iterator(); byte[] response = null; System.out.println("Packets todo: " + customPackets.size()); ByteArrayOutputStream f = new ByteArrayOutputStream(); f.write((byte)0x84); f.write(Hex.intToBytes(0, 3),0,3); while (it.hasNext()) { DatagramPacket packet = (DatagramPacket)customPackets.poll(); DataPacket dp = new DataPacket(packet); response = dp.getResponse(handler); if (response != null) { f.write(response,0,response.length); } } if (f.size() > 4) { System.out.println("Response: " + Hex.getHexString(f.toByteArray(), true)); System.out.println("Write!"); DatagramPacket p = new DatagramPacket(f.toByteArray(),f.size()); handler.write(p); } handler.process(getACK()); } public DatagramPacket getACK() { ByteBuffer rData = ByteBuffer.allocate(5); rData.put((byte) 0xc0); rData.put((byte) 0x01); rData.put(count); return new DatagramPacket(rData.array(), 5); } public void splitPacket() { ByteBuffer data = ByteBuffer.wrap(buffer); int i = 0; int length = 0; while (i < buffer.length) { if (buffer[i] == 0x00) { length = (data.getShort(i+1) / 8) + 3; } else if (buffer[i] == 0x40) { length = (data.getShort(i+1) / 8) + 6; } else if (buffer[i] == 0x60) { length = (data.getShort(i+1) / 8) + 10; } data.position(i); byte[] b = new byte[length]; data.get(b); System.out.println("split: " + Hex.getHexString(b, true) + " Size: " + length); DatagramPacket split = new DatagramPacket(b, b.length); customPackets.add(split); i += length; } } }
package quizapp.restapi; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import quizapp.core.User; import quizapp.json.JsonHandler; import quizapp.json.UsernameHandler; import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.http.MediaType; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.nio.charset.StandardCharsets; import java.nio.file.Paths; import java.util.Collection; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; @AutoConfigureMockMvc @ContextConfiguration(classes = { UserController.class, UserService.class }) @WebMvcTest public class UserControllerTest { private final static String TEST_USER_ID = "user-id-123"; @Autowired MockMvc mockMvc; private User user1 = new User("Test", "Testville"); private User user2 = new User("Post", "User"); private final static String pathStarter = "../core/src/main/resources/quizapp/json/"; private final String userPath = Paths.get(pathStarter + "JSONHandler.json").toString(); private final String usernamePath = Paths.get(pathStarter + "activeUser.json").toString(); private JsonHandler jsonHandler = new JsonHandler( userPath); private UsernameHandler usernameHandler = new UsernameHandler( usernamePath); // Adds User before each test to ensure independent testing @BeforeEach public void setUp() { user1 = new User("Test", "Testville"); jsonHandler.addUser(user1); } @Test public void postUser() { try { testPostUser(user2); jsonHandler.loadUserFromString("Post"); } catch (Exception e) { fail("Couldn't post user"); e.printStackTrace(); } // Removing the user Collection<User> users = jsonHandler.loadFromFile(); users.remove(users.stream().filter(user -> user.equals(user2)).findAny().orElse(null)); jsonHandler.writeToFile(users); } @Test public void correctUserIsRetrieved() { try { testGetUser(user1, "Test"); } catch (Exception e) { e.printStackTrace(); fail("Couldn't recieve user Test"); } } @Test public void putChangedTestUser() { try { testPutUser(user1); } catch (Exception e) { fail("Could not change User"); } } @Test public void getAllUsers() { try { assertEquals(testGetUsers(), jsonHandler.loadFromFile()); } catch (Exception e) { fail("Could not change User"); } } @Test public void putNewActiveUsername() { try { testPutUsername(user1.getUsername()); } catch (Exception e) { fail("could not put username"); } usernameHandler.saveActiveUser("Hallvard", userPath); } @Test public void getActiveUser() { try { testGetActiveUser(); } catch (Exception e) { fail("Could not retrive active user"); e.printStackTrace(); } } // Removes user created before each test @AfterEach public void deleteTestUser() { Collection<User> users = jsonHandler.loadFromFile(); users.remove(users.stream().filter(user -> user.getUsername().equals(user1.getUsername())).findAny().orElse(null)); jsonHandler.writeToFile(users); } private void testGetUser(User user, String username) throws Exception { Gson gson = new Gson(); MvcResult result = mockMvc .perform(MockMvcRequestBuilders.get("/api/user/" + username).with(user(TEST_USER_ID)).with(csrf()) .content(username).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andReturn(); byte[] resultUserByte = result.getResponse().getContentAsByteArray(); String resultUser = new String(resultUserByte, StandardCharsets.UTF_8); assertNotNull(resultUser); assertEquals(user, gson.fromJson(resultUser, new TypeToken<User>() { }.getType())); } private void testGetActiveUser() throws Exception { Gson gson = new Gson(); MvcResult result = mockMvc .perform(MockMvcRequestBuilders.get("/api/user/active").with(user(TEST_USER_ID)).with(csrf()) .content("").contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andReturn(); byte[] resultUserByte = result.getResponse().getContentAsByteArray(); String resultUser = new String(resultUserByte, StandardCharsets.UTF_8); assertNotNull(resultUser); assertEquals(jsonHandler.loadActiveUser(), gson.fromJson(resultUser, new TypeToken<User>() { }.getType())); } private Collection<User> testGetUsers() throws Exception { Gson gson = new Gson(); MvcResult result = mockMvc .perform(MockMvcRequestBuilders.get("/api/user/users").with(user(TEST_USER_ID)).with(csrf()).content("users") .contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andReturn(); byte[] resultUserByte = result.getResponse().getContentAsByteArray(); String resultUser = new String(resultUserByte, StandardCharsets.UTF_8); assertNotNull(resultUser); return gson.fromJson(resultUser, new TypeToken<Collection<User>>() { }.getType()); } private void testPostUser(User user) throws Exception { Gson gson = new GsonBuilder().setPrettyPrinting().create(); MvcResult result = mockMvc .perform(MockMvcRequestBuilders.post("/api/user/" + user.getUsername()).with(user(TEST_USER_ID)).with(csrf()) .content(gson.toJson(user)).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andReturn(); System.out.println(result); } private void testPutUser(User user) throws Exception { Gson gson = new GsonBuilder().setPrettyPrinting().create(); MvcResult result = mockMvc .perform(MockMvcRequestBuilders.put("/api/user/" + user.getUsername()).with(user(TEST_USER_ID)).with(csrf()) .content(gson.toJson(user)).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andReturn(); System.out.println("RESULT:" + result.toString()); } private void testPutUsername(String username) throws Exception { MvcResult result = mockMvc .perform(MockMvcRequestBuilders.put("/api/user/updateActive/" + username).with(user(TEST_USER_ID)).with(csrf()) .content(username).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()).andReturn(); System.out.println("RESULT:" + result.toString()); } }
package com.self.modules.sys.typehandle; import org.apache.commons.collections.CollectionUtils; import org.apache.ibatis.type.BaseTypeHandler; import org.apache.ibatis.type.JdbcType; import org.apache.ibatis.type.MappedJdbcTypes; import org.apache.ibatis.type.MappedTypes; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; @MappedJdbcTypes(JdbcType.VARCHAR) @MappedTypes(List.class) public class StringToListHandle extends BaseTypeHandler { @Override public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException { System.out.println("使用中。。。。1"); } @Override public Object getNullableResult(ResultSet rs, String columnName) throws SQLException { System.out.println("使用中。。。。2"); List<String> list = new ArrayList<>(); CollectionUtils.addAll(list,rs.getString(columnName).split(",")); return list; } @Override public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException { System.out.println("使用中。。。。3"); return null; } @Override public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { System.out.println("使用中。。。。4"); return null; } }
package com.pickup.pickup.controller; import android.widget.Toast; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by zachschlesinger on 3/4/17. */ public class CredentialVerification { private static final Pattern p = Pattern.compile("(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x07\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x07\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])"); public static boolean verifyEmail(String email) { Matcher m = p.matcher(email); return m.matches(); } public static String verifyPassword(String password) { String message = ""; boolean length = password.length() >= 8; boolean hasUppercase = !password.equals(password.toLowerCase()); boolean hasLowercase = !password.equals(password.toUpperCase()); boolean hasNumber = password.matches(".*\\d+.*"); message += (!length) ? "Password is too short" : ""; message += (!hasUppercase) ? "\nPassword does not contain an uppercase" : ""; message += (!hasLowercase) ? "\nPassword does not contain a lowercase" : ""; message += (!hasNumber) ? "\nPassword does not contain a number" : ""; return message; } }
//file: Problem_9_1.java //author: Victoria Cameron //course: CMPT 220 //assignment:Lab 6 //due date: April 20, 2017 //version: 1.0 //Print the aria and perimater od a rectangle using a rectangle class public class Problem_9_1{ /** Main method */ public static void main(String[] args) { //Make the two rectangles (4.40) (3.5,35.9) Rectangle rectangle = new Rectangle(4, 40); Rectangle rectangle1 = new Rectangle(3.5, 35.9); // Display the width, height, area, and perimeter of rectangle System.out.println("\n First Rectangle"); System.out.println("-------------"); System.out.println("Width: " + rectangle.width); System.out.println("Height: " + rectangle.height); System.out.println("Area: " + rectangle.getArea()); System.out.println("Perimeter: " + rectangle.getPerimeter()); // Display the width, height, area, and perimeter of rectangle2 System.out.println("\n Second Rectangle"); System.out.println("-------------"); System.out.println("Width: " + rectangle1.width); System.out.println("Height: " + rectangle1.height); System.out.println("Area: " + rectangle1.getArea()); System.out.println("Perimeter: " + rectangle1.getPerimeter()); } }
package Fichier_circuit; import java.util.Scanner; public class SauvegarderFichier { private Scanner scanner; private String url_fichier_circuit; private String nom_fichier_circuit; private FichierCircuit fichier_circuit; private String contenu; public SauvegarderFichier(String contenu) { this.setContenu(contenu); this.setScanner(new Scanner(System.in)); System.out.println("Saisissez oł vous souhaitez enregistrer votre fichier de circuit : "); this.setUrl_fichier_circuit(this.getScanner().nextLine()); System.out.println("Saisissez le nom de votre fichier de circuit : "); this.setNom_fichier_circuit(this.getScanner().nextLine()); this.setFichier_circuit(new FichierCircuit(this.getNom_fichier_circuit(), this.getUrl_fichier_circuit(), contenu)); this.getFichier_circuit().sauvegarder(this.getUrl_fichier_circuit(), this.getNom_fichier_circuit()); } //-------------------------------------------------- accesseurs et mutateurs --------------------------------------------------// public Scanner getScanner() { return scanner; } public void setScanner(Scanner scanner) { this.scanner = scanner; } public String getUrl_fichier_circuit() { return url_fichier_circuit + "/"; } public void setUrl_fichier_circuit(String url_fichier_circuit) { this.url_fichier_circuit = url_fichier_circuit; } public String getNom_fichier_circuit() { return nom_fichier_circuit; } public void setNom_fichier_circuit(String nom_fichier_circuit) { this.nom_fichier_circuit = nom_fichier_circuit; } public FichierCircuit getFichier_circuit() { return fichier_circuit; } public void setFichier_circuit(FichierCircuit fichier_circuit) { this.fichier_circuit = fichier_circuit; } public String getContenu() { return contenu; } public void setContenu(String contenu) { this.contenu = contenu; } }
import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.catalina.Session; /** * Servlet implementation class SkillServlet */ @WebServlet("/SkillServlet") public class SkillServlet extends HttpServlet { private static final long serialVersionUID = 1L; private Connection connect = null; private Statement statement = null; private PreparedStatement preparedStatement = null; private ResultSet resultSet = null; public SkillServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String skill1=request.getParameter("skill1"); String skillLevel1=request.getParameter("skillLevel1"); String skill2=request.getParameter("skill2"); String skillLevel2=request.getParameter("skillLevel2"); String skill3=request.getParameter("skill3"); String skillLevel3=request.getParameter("skillLevel3"); String skill4=request.getParameter("skill4"); String skillLevel4=request.getParameter("skillLevel4"); String skill5=request.getParameter("skill5"); String skillLevel5=request.getParameter("skillLevel5"); String skill6=request.getParameter("skill6"); String skillLevel6=request.getParameter("skillLevel6"); String skill7=request.getParameter("skill7"); String skillLevel7=request.getParameter("skillLevel7"); String skill8=request.getParameter("skill8"); String skillLevel8=request.getParameter("skillLevel8"); String skill9=request.getParameter("skill9"); String skillLevel9=request.getParameter("skillLevel9"); String skill10=request.getParameter("skill10"); String skillLevel10=request.getParameter("skillLevel10"); ArrayList <String>skills= new ArrayList<String>(); skills.add(skill1+","+skillLevel1+"\n"); skills.add(skill2+","+skillLevel2+"\n"); skills.add(skill3+","+skillLevel3+"\n"); skills.add(skill4+","+skillLevel4+"\n"); skills.add(skill5+","+skillLevel5+"\n"); skills.add(skill6+","+skillLevel6+"\n"); skills.add(skill7+","+skillLevel7+"\n"); skills.add(skill8+","+skillLevel8+"\n"); skills.add(skill9+","+skillLevel9+"\n"); skills.add(skill10+","+skillLevel10+"\n"); String nextUrl="/Output.jsp"; HttpSession session = request.getSession(); Jobs job =new Jobs(); job= (Jobs)session.getAttribute("jobs"); int joblength= job.getLength(); String jobsData=""; //This will go to the database for (int i=0;i<joblength;i++){ jobsData+=(job.getJob().get(i))+"<br>"; } Education edu =new Education(); edu= (Education)session.getAttribute("education"); int edulength= edu.getLength(); String eduData=""; //This will go to the database for (int i=0;i<edulength;i++){ eduData+=(edu.getEdu().get(i))+"<br>"; } String skillData=""; int skillSize=skills.size(); for (int i=0;i<joblength;i++){ if (skills.get(i)!=null) skillData+=(skills.get(i))+"<br>"; } session.setAttribute("eduData", eduData); session.setAttribute("jobsData", jobsData); session.setAttribute("skillData", skillData); try { // This will load the MySQL driver, each DB has its own driver // The MySQL driver is a JAR file that must be in the Build Path Class.forName("com.mysql.jdbc.Driver"); // Setup the connection with the DB connect = DriverManager.getConnection("jdbc:mysql://localhost/Resume?user=root&password=password"); String name= (String) session.getAttribute("name"); String email= (String) session.getAttribute("email"); preparedStatement = connect .prepareStatement("INSERT INTO UserInfo (Name, Email,Education,WorkExperience,Skill) VALUES(?,?,?,?,?)"); // "myuser, webpage, , summary, COMMENTS from feedback.comments"); // Parameters start with 1 preparedStatement.setString(1, name); preparedStatement.setString(2, email); preparedStatement.setString(3, eduData); preparedStatement.setString(4, jobsData); preparedStatement.setString(5, skillData); preparedStatement.executeUpdate(); Statement st = connect.createStatement(); String sql = ("SELECT * FROM UserInfo ;"); ResultSet rs = st.executeQuery(sql); String databaseName=""; String databaseEmail="" ; String databaseWorkExperience="" ; String databaseEducation="" ; String databaseSkills=""; if(rs.next()) { databaseName = rs.getString("Name"); databaseEmail = rs.getString("Email"); databaseWorkExperience= rs.getString("WorkExperience"); databaseEducation=rs.getString("Education"); databaseSkills=rs.getString("Skill"); } /*preparedStatement=connect.prepareStatement("select * from UserInfo Where UserID=1 "); resultSet = preparedStatement.executeQuery(); String databaseName = resultSet.getString("Name"); String databaseEmail = resultSet.getString("Email"); String databaseWorkExperience = resultSet.getString("WorkExperience"); String databaseEducation = resultSet.getString("Education"); String databaseSkills = resultSet.getString("Skill"); */ //This is where I set the session variable to be used to print on resume. The data is retrieved from the database. session.setAttribute("resumeName", databaseName); session.setAttribute("resumeEmail", databaseEmail); session.setAttribute("resumeWork", databaseWorkExperience); session.setAttribute("resumeEdu", databaseEducation); session.setAttribute("resumeSkill", databaseSkills); } catch (Exception e) { try { throw e; } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } finally { close(); } //--------------------------------------------------------------- getServletContext().getRequestDispatcher(nextUrl).forward(request,response); } private void close() { try { if (resultSet != null) { resultSet.close(); } if (statement != null) { statement.close(); } if (connect != null) { connect.close(); } } catch (Exception e) { } } }
package saboteur.view; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.*; import javafx.scene.input.MouseEvent; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.SVGPath; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import saboteur.tools.Icon; public class NewPlayerHBox extends HBox { private final static int MAX_LENGTH = 10; private SVGPath svg = new SVGPath(); private TextField playerName; private ComboBox<String> selectPlayerMenu; private Pane svgContainerPane; private int playerNumber; public NewPlayerHBox(int nbplayer, boolean isHuman) { this.playerNumber = nbplayer; initBox(); this.playerName.setText("Joueur " + this.playerNumber); if(isHuman) { this.selectPlayerMenu.setValue("Humain"); this.svg.setContent(Icon.user); } else { this.selectPlayerMenu.setValue("IA Facile"); this.svg.setContent(Icon.computer); } } private void initBox(){ // Image this.svg.setFill(Color.WHITE); HBox.setMargin(this.svg,new Insets(5,70,5,25)); // Name this.playerName = new TextField(); this.playerName.setFont(Font.font("System", FontPosture.REGULAR, 24)); this.playerName.setAlignment(Pos.CENTER_LEFT); this.playerName.setPrefSize(215, 25); this.playerName.setMaxSize(Control.USE_COMPUTED_SIZE, Control.USE_COMPUTED_SIZE); this.playerName.setMinSize(Control.USE_COMPUTED_SIZE, Control.USE_COMPUTED_SIZE); this.playerName.textProperty().addListener((ov, oldValue, newValue) -> { if (playerName.getText().length() > MAX_LENGTH) { String s = playerName.getText().substring(0, MAX_LENGTH); playerName.setText(s); } }); // Split Menu this.selectPlayerMenu = new ComboBox<>(); this.selectPlayerMenu.valueProperty().addListener((observable, oldValue, newValue) -> { if (newValue.equals("Humain")){ svg.setContent(Icon.user); } else{ svg.setContent(Icon.computer); } }); this.selectPlayerMenu.setPrefSize(255, 25); this.selectPlayerMenu.setMaxSize(Control.USE_COMPUTED_SIZE, Control.USE_COMPUTED_SIZE); this.selectPlayerMenu.setMinSize(Control.USE_COMPUTED_SIZE, Control.USE_COMPUTED_SIZE); this.selectPlayerMenu.setStyle("-fx-font-size: 24px"); HBox.setMargin(this.selectPlayerMenu, new Insets(0,200,0,30)); this.selectPlayerMenu.getItems().addAll("Humain", "IA Facile", "IA Difficile"); // HBox (container) this.setPrefSize(840, Control.USE_COMPUTED_SIZE); this.setMaxSize(Control.USE_COMPUTED_SIZE, Control.USE_COMPUTED_SIZE); this.setMinSize(Control.USE_COMPUTED_SIZE, Control.USE_COMPUTED_SIZE); this.setPadding(new Insets(5,0,5,0)); this.setAlignment(Pos.CENTER_RIGHT); this.getChildren().addAll(this.svg, this.playerName, this.selectPlayerMenu); VBox.setMargin(this, new Insets(25,0,25,0)); // if more than 3 player if(this.playerNumber > 3) { SVGPath svgTrash = new SVGPath(); svgTrash.setContent(Icon.trash); svgTrash.setFill(Color.WHITE); this.svgContainerPane = new Pane(svgTrash); this.getChildren().add(this.svgContainerPane); HBox.setMargin(this.svgContainerPane,new Insets(10,80,5,0)); HBox.setMargin(this.selectPlayerMenu, new Insets(0,98,0,30)); } } public void setRemovePlayerAction(EventHandler<MouseEvent> event) { this.svgContainerPane.setOnMousePressed(event); } public TextField getPlayerName(){ return this.playerName; } public ComboBox<String> getSelectPlayerMenu(){ return this.selectPlayerMenu; } }
package com.sushenbiswas.javacode; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; public class Main4Activity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main4); goToMain(); configureArrays(); configureRandomResultArrays(); configureArraysAndLoop(); configureArrayBound(); configuregoToActivety5(); configureStringLoopArrays(); configureEquealTo(); configure2Darrays(); configureNestedLoops(); configureNestedLoopsWith2dArrays(); } // this for Button to go main Activety private void goToMain() { Button btn = (Button) findViewById(R.id.goToMainBtn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); Toast.makeText(getApplicationContext(),"I am Going to main activety",Toast.LENGTH_LONG) .show(); } }); } // This is for Go to Break private void configureBreak(){ Button nextButton = (Button) findViewById(R.id.goBreak); nextButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { Log.i("MyApps","I am happy"); Toast.makeText(getApplicationContext(),"I am in Break",Toast.LENGTH_SHORT) .show(); // Lonch The Multiple Parimiter Activety Intent intent = new Intent(Main4Activity.this,Break.class); startActivity(intent); } }); } // This is for Go to Arrays private void configureArrays(){ Button nextButton = (Button) findViewById(R.id.goArrays); nextButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { Log.i("MyApps","I am happy"); Toast.makeText(getApplicationContext(),"I am in Arrays",Toast.LENGTH_SHORT) .show(); // Lonch The Multiple Parimiter Activety Intent intent = new Intent(Main4Activity.this,Arrays.class); startActivity(intent); } }); } // This is for Go to Random Result Using Arrays private void configureRandomResultArrays(){ Button nextButton = (Button) findViewById(R.id.goRandomResultArrays); nextButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { Log.i("MyApps","I am happy"); Toast.makeText(getApplicationContext(),"I am in Result Using Arrays",Toast.LENGTH_SHORT) .show(); // Lonch The Multiple Parimiter Activety Intent intent = new Intent(Main4Activity.this,RandomResultArrays.class); startActivity(intent); } }); } // This is for Go to Arrays and Loop private void configureArraysAndLoop(){ Button nextButton = (Button) findViewById(R.id.goArraysAndLoop); nextButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { Log.i("MyApps","I am happy"); Toast.makeText(getApplicationContext(),"I am in Arrays and Loop",Toast.LENGTH_SHORT) .show(); // Lonch The Multiple Parimiter Activety Intent intent = new Intent(Main4Activity.this,ArraysAndLoop.class); startActivity(intent); } }); } // This is for Go to String Loop Arrays private void configureStringLoopArrays(){ Button nextButton = (Button) findViewById(R.id.goStringLoopArrays); nextButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { Log.i("MyApps","I am happy"); Toast.makeText(getApplicationContext(),"I am in String Loop Arrays",Toast.LENGTH_SHORT) .show(); // Lonch The Multiple Parimiter Activety Intent intent = new Intent(Main4Activity.this,StringLoopArray.class); startActivity(intent); } }); } // This is for Go to Arrays Bound private void configureArrayBound(){ Button nextButton = (Button) findViewById(R.id.goArrayBound); nextButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { Log.i("MyApps","I am happy"); Toast.makeText(getApplicationContext(),"I am in Arrays Bound",Toast.LENGTH_SHORT) .show(); // Lonch The Multiple Parimiter Activety Intent intent = new Intent(Main4Activity.this,ArrayBound.class); startActivity(intent); } }); } // This is for Go to Use <, > or <=, >= private void configureEquealTo(){ Button nextButton = (Button) findViewById(R.id.goEquealTo); nextButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { Log.i("MyApps","I am happy"); Toast.makeText(getApplicationContext(),"I am in Use <, > or <=, >=",Toast.LENGTH_SHORT) .show(); // Lonch The Multiple Parimiter Activety Intent intent = new Intent(Main4Activity.this,LessAndGreterEquealOrLessAndGreater.class); startActivity(intent); } }); } // This is 2D Array private void configure2Darrays(){ Button nextButton = (Button) findViewById(R.id.go2Darrays); nextButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { Log.i("MyApps","I am happy"); Toast.makeText(getApplicationContext(),"I am in 2D Array",Toast.LENGTH_SHORT) .show(); // Lonch The Multiple Parimiter Activety Intent intent = new Intent(Main4Activity.this,twoDarray.class); startActivity(intent); } }); } // This is Nested Loops private void configureNestedLoops(){ Button nextButton = (Button) findViewById(R.id.goNestedLoops); nextButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { Log.i("MyApps","I am happy"); Toast.makeText(getApplicationContext(),"I am in Nested Loops",Toast.LENGTH_SHORT) .show(); // Lonch The Multiple Parimiter Activety Intent intent = new Intent(Main4Activity.this,NestedLoopWith2dArrays.class); startActivity(intent); } }); } // This is Nested Loops With 2d Arrays private void configureNestedLoopsWith2dArrays(){ Button nextButton = (Button) findViewById(R.id.goNestedLoopsWith2dArrays); nextButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { Log.i("MyApps","I am happy"); Toast.makeText(getApplicationContext(),"I am in Nested Loops With 2d Arrays",Toast.LENGTH_SHORT) .show(); // Lonch The Multiple Parimiter Activety Intent intent = new Intent(Main4Activity.this,NestedLoopWith2dArrays.class); startActivity(intent); } }); } // This is for Go to Next page private void configuregoToActivety5(){ Button nextButton = (Button) findViewById(R.id.goToActivety5); nextButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { Log.i("MyApps","I am happy"); Toast.makeText(getApplicationContext(),"I am not Creat Yet",Toast.LENGTH_SHORT) .show(); // // Lonch The Print Line Activety // Intent intent = new Intent(Main3Activity.this,Main4Activity.class); // startActivity(intent); } }); } }
package org.rs.core.beans; import javax.validation.constraints.NotNull; import java.util.Date; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import org.rs.core.utils.MyJsonDateSerializer; import org.rs.core.utils.MyJsonDateDeserializer; public class RsUser { @NotNull(message = "用户编号不能为空") private String yhbh; @NotNull(message = "登录名称不能为空") private String dlmc; @NotNull(message = "用户名称不能为空") private String yhmc; @NotNull(message = "部门编号不能为空") private String bmbh; private String phone; private String email; private String address; @NotNull(message = "用户是否复核,0-正常,1-待复核不能为空") private Integer sffh; @NotNull(message = "用户类型,0-默认用户,1-普通用户,其它值为自定义用户类型不能为空") private Integer yhlx; @NotNull(message = "用户状态,0-正常,1-锁定,2-删除不能为空") private Integer yhzt; @NotNull(message = "记录登录失败的次数,登录成功后清零不能为空") private Integer dlcs; @NotNull(message = "密码超期检测,0-不检测,1-检测不能为空") private Integer cqjc; @NotNull(message = "创建时间不能为空") private Date cjsj; @NotNull(message = "创建人编号不能为空") private String cjrbh; @NotNull(message = "创建人名称不能为空") private String cjrmc; /** * 用户编号 */ public String getYhbh(){ return this.yhbh; } /** * 用户编号 */ public void setYhbh( String yhbh ){ this.yhbh=yhbh; } /** * 登录名称 */ public String getDlmc(){ return this.dlmc; } /** * 登录名称 */ public void setDlmc( String dlmc ){ this.dlmc=dlmc; } /** * 用户名称 */ public String getYhmc(){ return this.yhmc; } /** * 用户名称 */ public void setYhmc( String yhmc ){ this.yhmc=yhmc; } /** * 部门编号 */ public String getBmbh(){ return this.bmbh; } /** * 部门编号 */ public void setBmbh( String bmbh ){ this.bmbh=bmbh; } /** * 手机号码 */ public String getPhone(){ return this.phone; } /** * 手机号码 */ public void setPhone( String phone ){ this.phone=phone; } /** * 邮件地址 */ public String getEmail(){ return this.email; } /** * 邮件地址 */ public void setEmail( String email ){ this.email=email; } /** * 用户地址 */ public String getAddress(){ return this.address; } /** * 用户地址 */ public void setAddress( String address ){ this.address=address; } /** * 用户是否复核,0-正常,1-待复核 */ public Integer getSffh(){ return this.sffh; } /** * 用户是否复核,0-正常,1-待复核 */ public void setSffh( Integer sffh ){ this.sffh=sffh; } /** * 用户类型,0-默认用户,1-普通用户,其它值为自定义用户类型 */ public Integer getYhlx(){ return this.yhlx; } /** * 用户类型,0-默认用户,1-普通用户,其它值为自定义用户类型 */ public void setYhlx( Integer yhlx ){ this.yhlx=yhlx; } /** * 用户状态,0-正常,1-锁定,2-删除 */ public Integer getYhzt(){ return this.yhzt; } /** * 用户状态,0-正常,1-锁定,2-删除 */ public void setYhzt( Integer yhzt ){ this.yhzt=yhzt; } /** * 记录登录失败的次数,登录成功后清零 */ public Integer getDlcs(){ return this.dlcs; } /** * 记录登录失败的次数,登录成功后清零 */ public void setDlcs( Integer dlcs ){ this.dlcs=dlcs; } /** * 密码超期检测,0-不检测,1-检测 */ public Integer getCqjc(){ return this.cqjc; } /** * 密码超期检测,0-不检测,1-检测 */ public void setCqjc( Integer cqjc ){ this.cqjc=cqjc; } /** * 创建时间 */ @JsonSerialize(using = MyJsonDateSerializer.class) public Date getCjsj(){ return this.cjsj; } /** * 创建时间 */ @JsonDeserialize(using = MyJsonDateDeserializer.class) public void setCjsj( Date cjsj ){ this.cjsj=cjsj; } /** * 创建人编号 */ public String getCjrbh(){ return this.cjrbh; } /** * 创建人编号 */ public void setCjrbh( String cjrbh ){ this.cjrbh=cjrbh; } /** * 创建人名称 */ public String getCjrmc(){ return this.cjrmc; } /** * 创建人名称 */ public void setCjrmc( String cjrmc ){ this.cjrmc=cjrmc; } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.resource; import java.io.IOException; import java.net.URLDecoder; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.EmbeddedValueResolverAware; import org.springframework.core.io.Resource; import org.springframework.core.io.UrlResource; import org.springframework.core.log.LogFormatUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpRange; import org.springframework.http.MediaType; import org.springframework.http.MediaTypeFactory; import org.springframework.http.converter.ResourceHttpMessageConverter; import org.springframework.http.converter.ResourceRegionHttpMessageConverter; import org.springframework.http.server.ServletServerHttpRequest; import org.springframework.http.server.ServletServerHttpResponse; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.ResourceUtils; import org.springframework.util.StringUtils; import org.springframework.util.StringValueResolver; import org.springframework.web.HttpRequestHandler; import org.springframework.web.accept.ContentNegotiationManager; import org.springframework.web.context.request.ServletWebRequest; import org.springframework.web.context.support.ServletContextResource; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.CorsConfigurationSource; import org.springframework.web.servlet.HandlerMapping; import org.springframework.web.servlet.support.WebContentGenerator; import org.springframework.web.util.UrlPathHelper; /** * {@code HttpRequestHandler} that serves static resources in an optimized way * according to the guidelines of Page Speed, YSlow, etc. * * <p>The properties {@linkplain #setLocations "locations"} and * {@linkplain #setLocationValues "locationValues"} accept locations from which * static resources can be served by this handler. This can be relative to the * root of the web application, or from the classpath, e.g. * "classpath:/META-INF/public-web-resources/", allowing convenient packaging * and serving of resources such as .js, .css, and others in jar files. * * <p>This request handler may also be configured with a * {@link #setResourceResolvers(List) resourcesResolver} and * {@link #setResourceTransformers(List) resourceTransformer} chains to support * arbitrary resolution and transformation of resources being served. By default, * a {@link PathResourceResolver} simply finds resources based on the configured * "locations". An application can configure additional resolvers and transformers * such as the {@link VersionResourceResolver} which can resolve and prepare URLs * for resources with a version in the URL. * * <p>This handler also properly evaluates the {@code Last-Modified} header * (if present) so that a {@code 304} status code will be returned as appropriate, * avoiding unnecessary overhead for resources that are already cached by the client. * * @author Keith Donald * @author Jeremy Grelle * @author Juergen Hoeller * @author Arjen Poutsma * @author Brian Clozel * @author Rossen Stoyanchev * @since 3.0.4 */ public class ResourceHttpRequestHandler extends WebContentGenerator implements HttpRequestHandler, EmbeddedValueResolverAware, InitializingBean, CorsConfigurationSource { private static final Log logger = LogFactory.getLog(ResourceHttpRequestHandler.class); private static final String URL_RESOURCE_CHARSET_PREFIX = "[charset="; private final List<String> locationValues = new ArrayList<>(4); private final List<Resource> locationResources = new ArrayList<>(4); private final List<Resource> locationsToUse = new ArrayList<>(4); private final Map<Resource, Charset> locationCharsets = new HashMap<>(4); private final List<ResourceResolver> resourceResolvers = new ArrayList<>(4); private final List<ResourceTransformer> resourceTransformers = new ArrayList<>(4); @Nullable private ResourceResolverChain resolverChain; @Nullable private ResourceTransformerChain transformerChain; @Nullable private ResourceHttpMessageConverter resourceHttpMessageConverter; @Nullable private ResourceRegionHttpMessageConverter resourceRegionHttpMessageConverter; @Nullable private ContentNegotiationManager contentNegotiationManager; private final Map<String, MediaType> mediaTypes = new HashMap<>(4); @Nullable private CorsConfiguration corsConfiguration; @Nullable private UrlPathHelper urlPathHelper; private boolean useLastModified = true; private boolean optimizeLocations = false; @Nullable private StringValueResolver embeddedValueResolver; public ResourceHttpRequestHandler() { super(HttpMethod.GET.name(), HttpMethod.HEAD.name()); } /** * Configure String-based locations to serve resources from. * <p>For example, {{@code "/"}, {@code "classpath:/META-INF/public-web-resources/"}} * allows resources to be served both from the web application root and * from any JAR on the classpath that contains a * {@code /META-INF/public-web-resources/} directory, with resources in the * web application root taking precedence. * <p>For {@link org.springframework.core.io.UrlResource URL-based resources} * (e.g. files, HTTP URLs, etc) this method supports a special prefix to * indicate the charset associated with the URL so that relative paths * appended to it can be encoded correctly, for example * {@code "[charset=Windows-31J]https://example.org/path"}. * @since 4.3.13 * @see #setLocations(List) */ public void setLocationValues(List<String> locations) { Assert.notNull(locations, "Locations list must not be null"); this.locationValues.clear(); this.locationValues.addAll(locations); } /** * Configure locations to serve resources from as pre-resourced Resource's. * @see #setLocationValues(List) */ public void setLocations(List<Resource> locations) { Assert.notNull(locations, "Locations list must not be null"); this.locationResources.clear(); this.locationResources.addAll(locations); } /** * Return the configured {@code List} of {@code Resource} locations including * both String-based locations provided via * {@link #setLocationValues(List) setLocationValues} and pre-resolved * {@code Resource} locations provided via {@link #setLocations(List) setLocations}. * <p>Note that the returned list is fully initialized only after * initialization via {@link #afterPropertiesSet()}. * <p><strong>Note:</strong> As of 5.3.11 the list of locations may be filtered to * exclude those that don't actually exist and therefore the list returned from this * method may be a subset of all given locations. See {@link #setOptimizeLocations}. * @see #setLocationValues * @see #setLocations */ public List<Resource> getLocations() { if (this.locationsToUse.isEmpty()) { // Possibly not yet initialized, return only what we have so far return this.locationResources; } return this.locationsToUse; } /** * Configure the list of {@link ResourceResolver ResourceResolvers} to use. * <p>By default {@link PathResourceResolver} is configured. If using this property, * it is recommended to add {@link PathResourceResolver} as the last resolver. */ public void setResourceResolvers(@Nullable List<ResourceResolver> resourceResolvers) { this.resourceResolvers.clear(); if (resourceResolvers != null) { this.resourceResolvers.addAll(resourceResolvers); } } /** * Return the list of configured resource resolvers. */ public List<ResourceResolver> getResourceResolvers() { return this.resourceResolvers; } /** * Configure the list of {@link ResourceTransformer ResourceTransformers} to use. * <p>By default no transformers are configured for use. */ public void setResourceTransformers(@Nullable List<ResourceTransformer> resourceTransformers) { this.resourceTransformers.clear(); if (resourceTransformers != null) { this.resourceTransformers.addAll(resourceTransformers); } } /** * Return the list of configured resource transformers. */ public List<ResourceTransformer> getResourceTransformers() { return this.resourceTransformers; } /** * Configure the {@link ResourceHttpMessageConverter} to use. * <p>By default a {@link ResourceHttpMessageConverter} will be configured. * @since 4.3 */ public void setResourceHttpMessageConverter(@Nullable ResourceHttpMessageConverter messageConverter) { this.resourceHttpMessageConverter = messageConverter; } /** * Return the configured resource converter. * @since 4.3 */ @Nullable public ResourceHttpMessageConverter getResourceHttpMessageConverter() { return this.resourceHttpMessageConverter; } /** * Configure the {@link ResourceRegionHttpMessageConverter} to use. * <p>By default a {@link ResourceRegionHttpMessageConverter} will be configured. * @since 4.3 */ public void setResourceRegionHttpMessageConverter(@Nullable ResourceRegionHttpMessageConverter messageConverter) { this.resourceRegionHttpMessageConverter = messageConverter; } /** * Return the configured resource region converter. * @since 4.3 */ @Nullable public ResourceRegionHttpMessageConverter getResourceRegionHttpMessageConverter() { return this.resourceRegionHttpMessageConverter; } /** * Configure a {@code ContentNegotiationManager} to help determine the * media types for resources being served. If the manager contains a path * extension strategy it will be checked for registered file extension. * @since 4.3 * @deprecated as of 5.2.4 in favor of using {@link #setMediaTypes(Map)} * with mappings possibly obtained from * {@link ContentNegotiationManager#getMediaTypeMappings()}. */ @Deprecated public void setContentNegotiationManager(@Nullable ContentNegotiationManager contentNegotiationManager) { this.contentNegotiationManager = contentNegotiationManager; } /** * Return the configured content negotiation manager. * @since 4.3 * @deprecated as of 5.2.4 */ @Nullable @Deprecated public ContentNegotiationManager getContentNegotiationManager() { return this.contentNegotiationManager; } /** * Add mappings between file extensions, extracted from the filename of a * static {@link Resource}, and corresponding media type to set on the * response. * <p>Use of this method is typically not necessary since mappings are * otherwise determined via * {@link jakarta.servlet.ServletContext#getMimeType(String)} or via * {@link MediaTypeFactory#getMediaType(Resource)}. * @param mediaTypes media type mappings * @since 5.2.4 */ public void setMediaTypes(Map<String, MediaType> mediaTypes) { mediaTypes.forEach((ext, mediaType) -> this.mediaTypes.put(ext.toLowerCase(Locale.ENGLISH), mediaType)); } /** * Return the {@link #setMediaTypes(Map) configured} media types. * @since 5.2.4 */ public Map<String, MediaType> getMediaTypes() { return this.mediaTypes; } /** * Specify the CORS configuration for resources served by this handler. * <p>By default this is not set in which allows cross-origin requests. */ public void setCorsConfiguration(CorsConfiguration corsConfiguration) { this.corsConfiguration = corsConfiguration; } /** * Return the specified CORS configuration. */ @Override @Nullable public CorsConfiguration getCorsConfiguration(HttpServletRequest request) { return this.corsConfiguration; } /** * Provide a reference to the {@link UrlPathHelper} used to map requests to * static resources. This helps to derive information about the lookup path * such as whether it is decoded or not. * @since 4.3.13 */ public void setUrlPathHelper(@Nullable UrlPathHelper urlPathHelper) { this.urlPathHelper = urlPathHelper; } /** * The configured {@link UrlPathHelper}. * @since 4.3.13 */ @Nullable public UrlPathHelper getUrlPathHelper() { return this.urlPathHelper; } /** * Set whether we should look at the {@link Resource#lastModified()} when * serving resources and use this information to drive {@code "Last-Modified"} * HTTP response headers. * <p>This option is enabled by default and should be turned off if the metadata * of the static files should be ignored. * @since 5.3 */ public void setUseLastModified(boolean useLastModified) { this.useLastModified = useLastModified; } /** * Return whether the {@link Resource#lastModified()} information is used * to drive HTTP responses when serving static resources. * @since 5.3 */ public boolean isUseLastModified() { return this.useLastModified; } /** * Set whether to optimize the specified locations through an existence * check on startup, filtering non-existing directories upfront so that * they do not have to be checked on every resource access. * <p>The default is {@code false}, for defensiveness against zip files * without directory entries which are unable to expose the existence of * a directory upfront. Switch this flag to {@code true} for optimized * access in case of a consistent jar layout with directory entries. * @since 5.3.13 */ public void setOptimizeLocations(boolean optimizeLocations) { this.optimizeLocations = optimizeLocations; } /** * Return whether to optimize the specified locations through an existence * check on startup, filtering non-existing directories upfront so that * they do not have to be checked on every resource access. * @since 5.3.13 */ public boolean isOptimizeLocations() { return this.optimizeLocations; } @Override public void setEmbeddedValueResolver(StringValueResolver resolver) { this.embeddedValueResolver = resolver; } @Override public void afterPropertiesSet() throws Exception { resolveResourceLocations(); if (this.resourceResolvers.isEmpty()) { this.resourceResolvers.add(new PathResourceResolver()); } initAllowedLocations(); // Initialize immutable resolver and transformer chains this.resolverChain = new DefaultResourceResolverChain(this.resourceResolvers); this.transformerChain = new DefaultResourceTransformerChain(this.resolverChain, this.resourceTransformers); if (this.resourceHttpMessageConverter == null) { this.resourceHttpMessageConverter = new ResourceHttpMessageConverter(); } if (this.resourceRegionHttpMessageConverter == null) { this.resourceRegionHttpMessageConverter = new ResourceRegionHttpMessageConverter(); } ContentNegotiationManager manager = getContentNegotiationManager(); if (manager != null) { setMediaTypes(manager.getMediaTypeMappings()); } @SuppressWarnings("deprecation") org.springframework.web.accept.PathExtensionContentNegotiationStrategy strategy = initContentNegotiationStrategy(); if (strategy != null) { setMediaTypes(strategy.getMediaTypes()); } } private void resolveResourceLocations() { List<Resource> result = new ArrayList<>(); if (!this.locationValues.isEmpty()) { ApplicationContext applicationContext = obtainApplicationContext(); for (String location : this.locationValues) { if (this.embeddedValueResolver != null) { String resolvedLocation = this.embeddedValueResolver.resolveStringValue(location); if (resolvedLocation == null) { throw new IllegalArgumentException("Location resolved to null: " + location); } location = resolvedLocation; } Charset charset = null; location = location.trim(); if (location.startsWith(URL_RESOURCE_CHARSET_PREFIX)) { int endIndex = location.indexOf(']', URL_RESOURCE_CHARSET_PREFIX.length()); if (endIndex == -1) { throw new IllegalArgumentException("Invalid charset syntax in location: " + location); } String value = location.substring(URL_RESOURCE_CHARSET_PREFIX.length(), endIndex); charset = Charset.forName(value); location = location.substring(endIndex + 1); } Resource resource = applicationContext.getResource(location); if (location.equals("/") && !(resource instanceof ServletContextResource)) { throw new IllegalStateException( "The String-based location \"/\" should be relative to the web application root " + "but resolved to a Resource of type: " + resource.getClass() + ". " + "If this is intentional, please pass it as a pre-configured Resource via setLocations."); } result.add(resource); if (charset != null) { if (!(resource instanceof UrlResource)) { throw new IllegalArgumentException("Unexpected charset for non-UrlResource: " + resource); } this.locationCharsets.put(resource, charset); } } } result.addAll(this.locationResources); if (isOptimizeLocations()) { result = result.stream().filter(Resource::exists).toList(); } this.locationsToUse.clear(); this.locationsToUse.addAll(result); } /** * Look for a {@code PathResourceResolver} among the configured resource * resolvers and set its {@code allowedLocations} property (if empty) to * match the {@link #setLocations locations} configured on this class. */ protected void initAllowedLocations() { if (CollectionUtils.isEmpty(getLocations())) { return; } for (int i = getResourceResolvers().size() - 1; i >= 0; i--) { if (getResourceResolvers().get(i) instanceof PathResourceResolver pathResolver) { if (ObjectUtils.isEmpty(pathResolver.getAllowedLocations())) { pathResolver.setAllowedLocations(getLocations().toArray(new Resource[0])); } if (this.urlPathHelper != null) { pathResolver.setLocationCharsets(this.locationCharsets); pathResolver.setUrlPathHelper(this.urlPathHelper); } break; } } } /** * Initialize the strategy to use to determine the media type for a resource. * @deprecated as of 5.2.4 this method returns {@code null}, and if a * subclass returns an actual instance, the instance is used only as a * source of media type mappings, if it contains any. Please, use * {@link #setMediaTypes(Map)} instead, or if you need to change behavior, * you can override {@link #getMediaType(HttpServletRequest, Resource)}. */ @Nullable @Deprecated @SuppressWarnings("deprecation") protected org.springframework.web.accept.PathExtensionContentNegotiationStrategy initContentNegotiationStrategy() { return null; } /** * Processes a resource request. * <p>Finds the requested resource under one of the configured locations. * If the resource does not exist, {@link NoResourceFoundException} is raised. * If the resource exists, the request will be checked for the presence of the * {@code Last-Modified} header, and its value will be compared against the last-modified * timestamp of the given resource, returning a {@code 304} status code if the * {@code Last-Modified} value is greater. If the resource is newer than the * {@code Last-Modified} value, or the header is not present, the content resource * of the resource will be written to the response with caching headers * set to expire one year in the future. */ @Override public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // For very general mappings (e.g. "/") we need to check 404 first Resource resource = getResource(request); if (resource == null) { logger.debug("Resource not found"); throw new NoResourceFoundException(HttpMethod.valueOf(request.getMethod()), getPath(request)); } if (HttpMethod.OPTIONS.matches(request.getMethod())) { response.setHeader(HttpHeaders.ALLOW, getAllowHeader()); return; } // Supported methods and required session checkRequest(request); // Header phase if (isUseLastModified() && new ServletWebRequest(request, response).checkNotModified(resource.lastModified())) { logger.trace("Resource not modified"); return; } // Apply cache settings, if any prepareResponse(response); // Check the media type for the resource MediaType mediaType = getMediaType(request, resource); setHeaders(response, resource, mediaType); // Content phase ServletServerHttpResponse outputMessage = new ServletServerHttpResponse(response); if (request.getHeader(HttpHeaders.RANGE) == null) { Assert.state(this.resourceHttpMessageConverter != null, "Not initialized"); if (HttpMethod.HEAD.matches(request.getMethod())) { this.resourceHttpMessageConverter.addDefaultHeaders(outputMessage, resource, mediaType); outputMessage.flush(); } else { this.resourceHttpMessageConverter.write(resource, mediaType, outputMessage); } } else { Assert.state(this.resourceRegionHttpMessageConverter != null, "Not initialized"); ServletServerHttpRequest inputMessage = new ServletServerHttpRequest(request); try { List<HttpRange> httpRanges = inputMessage.getHeaders().getRange(); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); this.resourceRegionHttpMessageConverter.write( HttpRange.toResourceRegions(httpRanges, resource), mediaType, outputMessage); } catch (IllegalArgumentException ex) { response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes */" + resource.contentLength()); response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); } } } @Nullable protected Resource getResource(HttpServletRequest request) throws IOException { String path = getPath(request); path = processPath(path); if (!StringUtils.hasText(path) || isInvalidPath(path)) { return null; } if (isInvalidEncodedPath(path)) { return null; } Assert.state(this.resolverChain != null, "ResourceResolverChain not initialized."); Assert.state(this.transformerChain != null, "ResourceTransformerChain not initialized."); Resource resource = this.resolverChain.resolveResource(request, path, getLocations()); if (resource != null) { resource = this.transformerChain.transform(request, resource); } return resource; } private static String getPath(HttpServletRequest request) { String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); if (path == null) { throw new IllegalStateException("Required request attribute '" + HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE + "' is not set"); } return path; } /** * Process the given resource path. * <p>The default implementation replaces: * <ul> * <li>Backslash with forward slash. * <li>Duplicate occurrences of slash with a single slash. * <li>Any combination of leading slash and control characters (00-1F and 7F) * with a single "/" or "". For example {@code " / // foo/bar"} * becomes {@code "/foo/bar"}. * </ul> * @since 3.2.12 */ protected String processPath(String path) { path = StringUtils.replace(path, "\\", "/"); path = cleanDuplicateSlashes(path); return cleanLeadingSlash(path); } private String cleanDuplicateSlashes(String path) { StringBuilder sb = null; char prev = 0; for (int i = 0; i < path.length(); i++) { char curr = path.charAt(i); try { if ((curr == '/') && (prev == '/')) { if (sb == null) { sb = new StringBuilder(path.substring(0, i)); } continue; } if (sb != null) { sb.append(path.charAt(i)); } } finally { prev = curr; } } return (sb != null ? sb.toString() : path); } private String cleanLeadingSlash(String path) { boolean slash = false; for (int i = 0; i < path.length(); i++) { if (path.charAt(i) == '/') { slash = true; } else if (path.charAt(i) > ' ' && path.charAt(i) != 127) { if (i == 0 || (i == 1 && slash)) { return path; } return (slash ? "/" + path.substring(i) : path.substring(i)); } } return (slash ? "/" : ""); } /** * Check whether the given path contains invalid escape sequences. * @param path the path to validate * @return {@code true} if the path is invalid, {@code false} otherwise */ private boolean isInvalidEncodedPath(String path) { if (path.contains("%")) { try { // Use URLDecoder (vs UriUtils) to preserve potentially decoded UTF-8 chars String decodedPath = URLDecoder.decode(path, StandardCharsets.UTF_8); if (isInvalidPath(decodedPath)) { return true; } decodedPath = processPath(decodedPath); if (isInvalidPath(decodedPath)) { return true; } } catch (IllegalArgumentException ex) { // May not be possible to decode... } } return false; } /** * Identifies invalid resource paths. By default, rejects: * <ul> * <li>Paths that contain "WEB-INF" or "META-INF" * <li>Paths that contain "../" after a call to * {@link org.springframework.util.StringUtils#cleanPath}. * <li>Paths that represent a {@link org.springframework.util.ResourceUtils#isUrl * valid URL} or would represent one after the leading slash is removed. * </ul> * <p><strong>Note:</strong> this method assumes that leading, duplicate '/' * or control characters (e.g. white space) have been trimmed so that the * path starts predictably with a single '/' or does not have one. * @param path the path to validate * @return {@code true} if the path is invalid, {@code false} otherwise * @since 3.0.6 */ protected boolean isInvalidPath(String path) { if (path.contains("WEB-INF") || path.contains("META-INF")) { if (logger.isWarnEnabled()) { logger.warn(LogFormatUtils.formatValue( "Path with \"WEB-INF\" or \"META-INF\": [" + path + "]", -1, true)); } return true; } if (path.contains(":/")) { String relativePath = (path.charAt(0) == '/' ? path.substring(1) : path); if (ResourceUtils.isUrl(relativePath) || relativePath.startsWith("url:")) { if (logger.isWarnEnabled()) { logger.warn(LogFormatUtils.formatValue( "Path represents URL or has \"url:\" prefix: [" + path + "]", -1, true)); } return true; } } if (path.contains("..") && StringUtils.cleanPath(path).contains("../")) { if (logger.isWarnEnabled()) { logger.warn(LogFormatUtils.formatValue( "Path contains \"../\" after call to StringUtils#cleanPath: [" + path + "]", -1, true)); } return true; } return false; } /** * Determine the media type for the given request and the resource matched * to it. This implementation tries to determine the MediaType using one of * the following lookups based on the resource filename and its path * extension: * <ol> * <li>{@link jakarta.servlet.ServletContext#getMimeType(String)} * <li>{@link #getMediaTypes()} * <li>{@link MediaTypeFactory#getMediaType(String)} * </ol> * @param request the current request * @param resource the resource to check * @return the corresponding media type, or {@code null} if none found */ @Nullable protected MediaType getMediaType(HttpServletRequest request, Resource resource) { MediaType result = null; String mimeType = request.getServletContext().getMimeType(resource.getFilename()); if (StringUtils.hasText(mimeType)) { result = MediaType.parseMediaType(mimeType); } if (result == null || MediaType.APPLICATION_OCTET_STREAM.equals(result)) { MediaType mediaType = null; String filename = resource.getFilename(); String ext = StringUtils.getFilenameExtension(filename); if (ext != null) { mediaType = this.mediaTypes.get(ext.toLowerCase(Locale.ENGLISH)); } if (mediaType == null) { List<MediaType> mediaTypes = MediaTypeFactory.getMediaTypes(filename); if (!CollectionUtils.isEmpty(mediaTypes)) { mediaType = mediaTypes.get(0); } } if (mediaType != null) { result = mediaType; } } return result; } /** * Set headers on the given servlet response. * Called for GET requests as well as HEAD requests. * @param response current servlet response * @param resource the identified resource (never {@code null}) * @param mediaType the resource's media type (never {@code null}) * @throws IOException in case of errors while setting the headers */ protected void setHeaders(HttpServletResponse response, Resource resource, @Nullable MediaType mediaType) throws IOException { if (mediaType != null) { response.setContentType(mediaType.toString()); } if (resource instanceof HttpResource httpResource) { HttpHeaders resourceHeaders = httpResource.getResponseHeaders(); resourceHeaders.forEach((headerName, headerValues) -> { boolean first = true; for (String headerValue : headerValues) { if (first) { response.setHeader(headerName, headerValue); } else { response.addHeader(headerName, headerValue); } first = false; } }); } response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes"); } @Override public String toString() { return "ResourceHttpRequestHandler " + locationToString(getLocations()); } private String locationToString(List<Resource> locations) { return locations.toString() .replaceAll("class path resource", "classpath") .replaceAll("ServletContext resource", "ServletContext"); } }