text
stringlengths
10
2.72M
package com.yahoo.algos; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class AllSubstringOfString { /** * Why O(N^2) ?? has to be O(N) NOTE: O(n) is suffix and N^2 is Substrings. * You can find suffix and sort the array now easy to find max repeated string by comparing i and i+1 in your array * Java String internally maintains char[] hence the substring call is a linear time and space call */ private void subStrings(String str){ List<String> sList = new ArrayList<String>(); for(int i=0;i<=str.length();i++){ for(int j=i+1;j<=str.length();j++){ //System.out.println(str.substring(i, j)); sList.add(str.substring(i,j)); } } Collections.sort(sList); System.out.println(sList); } private void suffix(String str){ int length = str.length(); String[] subStrings = new String[str.length()]; for(int i=0;i<length;i++){ subStrings[i] = str.substring(i, length); System.out.println(str.substring(i, length)); } System.out.println("all Subs Sorted----------"); Arrays.sort(subStrings); for(int i=0;i<subStrings.length;i++){ System.out.println(subStrings[i]); } } public static void main(String[] args) { new AllSubstringOfString().subStrings("aasasatb"); System.out.println("----------"); new AllSubstringOfString().suffix("aasasatb"); } }
package a4adept; public class IndirectFrame2DImpl implements IndirectFrame2D { private Frame2D source; private int xOffset; private int yOffset; private int height; private int width; private Frame2D f; public IndirectFrame2DImpl(Frame2D source, int xOffset, int yOffset, int width, int height) { if(source.equals(null)) throw new IllegalArgumentException("Source is null."); this.source = source; if(xOffset >= source.getWidth() || xOffset < 0 || yOffset >= source.getHeight() || yOffset < 0) throw new IllegalFrame2DGeometryException(); this.xOffset = xOffset; this.yOffset = yOffset; if(width < 0 || width > source.getWidth()) this.height = height; this.width = width; f = new MutableFrame2D(height, width); } public IndirectFrame2D extract(int xOffset, int yOffset, int width, int height) { for(int x=0; x < f.getWidth(); x++) { for(int y=0; y < f.getHeight(); y++) { f.setPixel(x, y, source.getPixel(x + xOffset, y + yOffset)); } } return (IndirectFrame2D)f; } @Override public int getWidth() { return this.width; } @Override public int getHeight() { return this.height; } @Override public Pixel getPixel(int x, int y) { return source.getPixel(x + xOffset, y + yOffset); } @Override public Frame2D setPixel(int x, int y, Pixel p) { return source.setPixel(x, y, p); } @Override public Frame2D lighten(double factor) { return source.lighten(factor); } @Override public Frame2D darken(double factor) { return source.darken(factor); } @Override public GrayFrame2D toGrayFrame() { return source.toGrayFrame(); } @Override public Frame2D getSource() { return this.source; } @Override public int getXOffset() { return this.xOffset; } @Override public int getYOffset() { return this.yOffset; } }
package ru.brainworkout.braingym.strup_test; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.os.SystemClock; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.Chronometer; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import java.util.ArrayList; import java.util.Random; import ru.brainworkout.braingym.MainActivity; import ru.brainworkout.braingym.R; public class StrupActivity_ver1 extends AppCompatActivity { private Chronometer mChronometer; private boolean mChronometerIsWorking = false; private long mChronometerCount = 0; private final int mStrupExamples = 8; private ArrayList<String> alphabetWords = new ArrayList<>(); private ArrayList<Integer> alphabetColors = new ArrayList<>(); private ArrayList<Integer> arrColors = new ArrayList<>(); private ArrayList<Integer> arrWords = new ArrayList<>(); private int answer; private int mCountRightAnswers = 0; private int mCountAllAnswers = 0; //настройки private String mStrupLang; private int mStrupMaxTime; private int mStrupExampleTime; private String mStrupExampleType; private int mTextSize = 0; private int mStrupVer1FontSizeChange; private int indexLastColor; private int indexLastWord; private long mStrupExBeginTime = 0; private long elapsedMillis; private enum typeExample { WORD, COLOR } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_strup_ver1); mChronometer = (Chronometer) findViewById(R.id.chronometer_strup_ver1); } private void drawStrupVer1Test() { for (Integer i = 1; i <= mStrupExamples; i++) { int resID = getResources().getIdentifier("tvStrupVer1Color" + String.valueOf(i), "id", getPackageName()); TextView txt = (TextView) findViewById(resID); if (txt != null) { int curColor = alphabetColors.get(arrColors.get(i - 1)); String curWord = alphabetWords.get(arrWords.get(i - 1)); txt.setTextSize(mTextSize); txt.setText(curWord); txt.setTextColor(curColor); } } } public void strupVer1Clear_onClick(View view) { timerStop(false); } private void timerStop(boolean auto) { mChronometer.setBase(SystemClock.elapsedRealtime()); mChronometer.stop(); mChronometerCount = 0; mChronometerIsWorking = false; mCountRightAnswers = 0; mCountAllAnswers = 0; mStrupExBeginTime = 0; ChangeButtonText("buttonStrupVer1StartPause", "Старт"); int timerMaxID = getResources().getIdentifier("tvStrupVer1TimerMaxTime", "id", getPackageName()); TextView txtTimerMaxTime = (TextView) findViewById(timerMaxID); if (txtTimerMaxTime != null) { txtTimerMaxTime.setTextSize(mTextSize); String txt; if (!auto) { txt = "Тест: " + String.valueOf(mStrupMaxTime); } else { txt = "Тест окончен"; } txtTimerMaxTime.setText(txt); } int answerID = getResources().getIdentifier("tvStrupVer1Answers", "id", getPackageName()); TextView txtAnswer = (TextView) findViewById(answerID); if (txtAnswer != null) { txtAnswer.setTextSize(mTextSize); if (!auto) { txtAnswer.setText(""); } } int typeID = getResources().getIdentifier("tvStrupVer1Type", "id", getPackageName()); TextView txtType = (TextView) findViewById(typeID); if (txtType != null) { txtType.setText(""); } int exID = getResources().getIdentifier("tvStrupVer1Example", "id", getPackageName()); TextView txtEx = (TextView) findViewById(exID); if (txtEx != null) { txtEx.setText(""); } for (int i = 1; i <= 8; i++) { int resID = getResources().getIdentifier("tvStrupVer1Color" + String.valueOf(i), "id", getPackageName()); TextView txt = (TextView) findViewById(resID); if (txt != null) { txt.setText(" "); txt.setTextSize(mTextSize); } } if (mStrupExampleTime != 0) { int timerExID = getResources().getIdentifier("tvStrupVer1TimerExTime", "id", getPackageName()); TextView txtTimerExTime = (TextView) findViewById(timerExID); if (txtTimerExTime != null) { String txt; if (!auto) { txt = "Пример: " + String.valueOf(mStrupExampleTime); } else { txt = ""; } txtTimerExTime.setText(txt); txtTimerExTime.setTextSize(mTextSize); } } } private void strupVer1Clear() { // int exID = getResources().getIdentifier("tvStrupVer1Example", "id", getPackageName()); // TextView txt1 = (TextView) findViewById(exID); // // if (txt1 != null) { // txt1.setText(" "); // txt1.setBackgroundResource(R.drawable.rounded_corners1); // txt1.setTextSize(mTextSize); // // } // // int typeID = getResources().getIdentifier("tvStrupVer1Type", "id", getPackageName()); // TextView txt2 = (TextView) findViewById(typeID); // // if (txt2 != null) { // txt2.setText(" "); // txt2.setBackgroundResource(R.drawable.rounded_corners1); // txt2.setTextSize(mTextSize); // } int trowID = getResources().getIdentifier("trowStrupVer1", "id", getPackageName()); TableRow trow1 = (TableRow) findViewById(trowID); if (trow1 != null) { trow1.setBackgroundResource(R.drawable.rounded_corners1); } for (int i = 1; i <= 8; i++) { int ansID = getResources().getIdentifier("tvStrupVer1Color"+String.valueOf(i), "id", getPackageName()); TextView txtAns = (TextView) findViewById(ansID); if (txtAns != null) { txtAns.setText(" "); txtAns.setBackgroundResource(R.drawable.rounded_corners2); txtAns.setTextSize(mTextSize); txtAns.setPadding(0,mTextSize,0,mTextSize); } } // int table1ID = getResources().getIdentifier("tableStrupVer1", "id", getPackageName()); // TableLayout table1 = (TableLayout) findViewById(table1ID); // // if (table1 != null) { // table1.setBackgroundResource(R.drawable.rounded_corners1); // } } private void createStrupVer1Examples() { Random random = new Random(); arrColors.clear(); arrWords.clear(); boolean doItWord = true; while (arrColors.size() != 8) { int indexColor = Math.abs(random.nextInt() % 8); if (!arrColors.contains(indexColor)) { int indPlace = Math.abs((arrColors.size() == 0 ? random.nextInt() : random.nextInt(arrColors.size()))); // strupExamples.add((strupExamples.size() == 0 ? 0 : indPlace % strupExamples.size()), newEx); arrColors.add((arrColors.size() == 0 ? 0 : indPlace % arrColors.size()), indexColor); } } while (arrWords.size() != 8) { while (doItWord) { int indexWord = Math.abs(random.nextInt() % 8); if (!arrWords.contains(indexWord)) { int indPlace = Math.abs((arrWords.size() == 0 ? random.nextInt() : random.nextInt(arrWords.size()))); //проверяем, не находится ли на том же месте в массиве цветов этот же цвет indPlace = (arrWords.size() == 0 ? 0 : indPlace % arrWords.size()); if (indPlace != arrColors.indexOf(indexWord)) { arrWords.add(indPlace, indexWord); doItWord = false; } } } doItWord = true; } } private void changeTimer(long elapsedMillis) { int timerMaxID = getResources().getIdentifier("tvStrupVer1TimerMaxTime", "id", getPackageName()); TextView txtTimerMaxTime = (TextView) findViewById(timerMaxID); if (txtTimerMaxTime != null) { int time = (int) (mStrupMaxTime - (elapsedMillis / 1000)); String txt = "Тест: " + String.valueOf(time); txtTimerMaxTime.setText(txt); txtTimerMaxTime.setTextSize(mTextSize); } if (mStrupExampleTime != 0) { int timerExID = getResources().getIdentifier("tvStrupVer1TimerExTime", "id", getPackageName()); TextView txtTimerExTime = (TextView) findViewById(timerExID); if (txtTimerExTime != null) { int time = (mStrupExampleTime - ((int) (((elapsedMillis - mStrupExBeginTime) / 1000)) % mStrupExampleTime)); //System.out.println("mStrupeExampleTime=" + mStrupExampleTime + ", time=" + time + ", elapsed millis=" + elapsedMillis + ", mStrupExBeginTime=" + mStrupExBeginTime); if (time == mStrupExampleTime) { //новый пример String txt = "Пример: " + String.valueOf(time); txtTimerExTime.setText(txt); txtTimerExTime.setTextSize(mTextSize); mCountAllAnswers++; int answerID = getResources().getIdentifier("tvStrupVer1Answers", "id", getPackageName()); TextView txtAnswer = (TextView) findViewById(answerID); if (txtAnswer != null) { String txt1 = String.valueOf(mCountRightAnswers) + "/" + String.valueOf(mCountAllAnswers); txtAnswer.setText(txt1); txtAnswer.setTextSize(mTextSize); } showNextExample(); } else { String txt = "Пример: " + String.valueOf(time); txtTimerExTime.setText(txt); txtTimerExTime.setTextSize(mTextSize); } } } else { int timerExID = getResources().getIdentifier("tvStrupVer1TimerExTime", "id", getPackageName()); TextView txtTimerExTime = (TextView) findViewById(timerExID); if (txtTimerExTime != null) { txtTimerExTime.setText(" "); txtTimerExTime.setTextSize(mTextSize); } } } public void startPauseStrupVer1_onClick(View view) { start_pause(); } private void start_pause() { if (!mChronometerIsWorking) { if (mChronometerCount == 0) { mChronometer.setBase(SystemClock.elapsedRealtime()); TableLayout frame = (TableLayout) findViewById(R.id.groundStrup_ver1); int mWidth; int mHeight; if (frame != null) { mWidth = frame.getWidth(); mHeight = frame.getHeight(); } else { mWidth = 0; mHeight = 0; } mTextSize = (int) (Math.min(mWidth, mHeight) / 18 / getApplicationContext().getResources().getDisplayMetrics().density)+mStrupVer1FontSizeChange; strupVer1Clear(); getPreferencesFromFile(); // createStrupExamples(); // drawStrupTest(); int timerID = getResources().getIdentifier("tvStrupVer1TimerMaxTime", "id", getPackageName()); TextView txtTimerMaxTime = (TextView) findViewById(timerID); if (txtTimerMaxTime != null) { txtTimerMaxTime.setTextSize(mTextSize); String txt = "Тест: " + String.valueOf(mStrupMaxTime); txtTimerMaxTime.setText(txt); txtTimerMaxTime.setTextSize(mTextSize); } mChronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() { @Override public void onChronometerTick(Chronometer chronometer) { elapsedMillis = SystemClock.elapsedRealtime() - mChronometer.getBase(); if (mStrupMaxTime - (elapsedMillis / 1000) < 1) { timerStop(true); } if (elapsedMillis > 1000) { changeTimer(elapsedMillis); //elapsedMillis=0; } } }); showNextExample(); } else { mChronometer.setBase(SystemClock.elapsedRealtime() - mChronometerCount); } mChronometer.start(); mChronometerIsWorking = true; ChangeButtonText("buttonStrupVer1StartPause", "Пауза"); } else { //mChronometerBase=mChronometer.getBase(); mChronometerCount = SystemClock.elapsedRealtime() - mChronometer.getBase(); mChronometer.stop(); mChronometerIsWorking = false; ChangeButtonText("buttonStrupVer1StartPause", "Старт"); } } private void showNextExample() { createStrupVer1Examples(); drawStrupVer1Test(); Random random = new Random(); int indexType = Math.abs(random.nextInt() % 2); typeExample type = null; switch (mStrupExampleType) { case "RANDOM": switch (indexType) { case 0: type = typeExample.WORD; break; case 1: type = typeExample.COLOR; break; } break; case "COLOR": type = typeExample.COLOR; break; case "WORD": type = typeExample.WORD; break; } int typeID = getResources().getIdentifier("tvStrupVer1Type", "id", getPackageName()); TextView txtType = (TextView) findViewById(typeID); if (txtType != null) { //тип операции рандомно if (type == typeExample.COLOR) { txtType.setText("От цвета ищем слово"); } else { txtType.setText("От слова ищем цвет"); } txtType.setTextSize(mTextSize); } //type = typeExample.COLOR; int indexColor = 0; int indexWord = 0; boolean doIt = true; while (doIt) { indexColor = Math.abs(random.nextInt() % 8); indexWord = Math.abs(random.nextInt() % 8); //цвет не равен прошлом, слово не равно прошлому, и цвет не равен слову сейчас if (indexColor!=indexLastColor && indexWord!=indexLastWord && indexColor != indexWord) { doIt = false; } } indexLastColor=indexColor; indexLastWord=indexWord; int exampleID = getResources().getIdentifier("tvStrupVer1Example", "id", getPackageName()); TextView txtExample = (TextView) findViewById(exampleID); if (txtExample != null) { //тип операции рандомно // indexWord=0; // indexColor=7; txtExample.setText(alphabetWords.get(indexWord)); txtExample.setTextSize(mTextSize); txtExample.setTextColor(alphabetColors.get(indexColor)); if (type == typeExample.WORD) { answer = arrColors.indexOf(indexWord); } else if (type == typeExample.COLOR) { answer = arrWords.indexOf(indexColor); } } } public void txt_onClick(View view) { if (mChronometerIsWorking) { //int a = Integer.valueOf(String.valueOf(((AppCompatTextView) view).getText().charAt(0))); String id = view.getResources().getResourceEntryName(view.getId()); int a = Integer.valueOf(id.substring(id.length() - 1, id.length())); if (a - 1 == answer) { mCountRightAnswers++; } mCountAllAnswers++; mStrupExBeginTime = elapsedMillis; int timerExID = getResources().getIdentifier("tvStrupVer1TimerExTime", "id", getPackageName()); TextView txtTimerExTime = (TextView) findViewById(timerExID); if (mStrupExampleTime != 0) { if (txtTimerExTime != null) { String txt = "Пример: " + String.valueOf(mStrupExampleTime); txtTimerExTime.setText(txt); txtTimerExTime.setTextSize(mTextSize); } } int answerID = getResources().getIdentifier("tvStrupVer1Answers", "id", getPackageName()); TextView txtAnswer = (TextView) findViewById(answerID); if (txtAnswer != null) { String txt = String.valueOf(mCountRightAnswers) + "/" + String.valueOf(mCountAllAnswers); txtAnswer.setText(txt); txtAnswer.setTextSize(mTextSize); } showNextExample(); } } public void strupVer1Options_onClick(View view) { Intent intent = new Intent(StrupActivity_ver1.this, StrupActivityOptions_ver1.class); intent.putExtra("mStrupVer1TextSize",mTextSize-mStrupVer1FontSizeChange); startActivity(intent); } private void ChangeButtonText(String ButtonID, String ButtonText) { int resID = getResources().getIdentifier(ButtonID, "id", getPackageName()); Button but = (Button) findViewById(resID); if (but != null) { but.setText(ButtonText); } } public void buttonHome_onClick(View view) { Intent intent = new Intent(getApplicationContext(), MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } private void getPreferencesFromFile() { SharedPreferences mSettings = getSharedPreferences(MainActivity.APP_PREFERENCES, Context.MODE_PRIVATE); if (mSettings.contains(MainActivity.APP_PREFERENCES_STRUP_VER1_FONT_SIZE_CHANGE)) { // Получаем язык из настроек mStrupVer1FontSizeChange = mSettings.getInt(MainActivity.APP_PREFERENCES_STRUP_VER1_FONT_SIZE_CHANGE, 0); } else { mStrupVer1FontSizeChange = 0; } if (mSettings.contains(MainActivity.APP_PREFERENCES_STRUP_VER1_TEST_TIME)) { mStrupMaxTime = mSettings.getInt(MainActivity.APP_PREFERENCES_STRUP_VER1_TEST_TIME, 60); } else { mStrupMaxTime = 60; } if (mSettings.contains(MainActivity.APP_PREFERENCES_STRUP_VER1_EXAMPLE_TIME)) { mStrupExampleTime = mSettings.getInt(MainActivity.APP_PREFERENCES_STRUP_VER1_EXAMPLE_TIME, 0); } else { mStrupExampleTime = 0; } if (mSettings.contains(MainActivity.APP_PREFERENCES_STRUP_VER1_EXAMPLE_TYPE)) { mStrupExampleType = mSettings.getString(MainActivity.APP_PREFERENCES_STRUP_VER1_EXAMPLE_TYPE, "Random"); } else { mStrupExampleType = "Random"; } if (mSettings.contains(MainActivity.APP_PREFERENCES_STRUP_LANGUAGE)) { // Получаем язык из настроек mStrupLang = mSettings.getString(MainActivity.APP_PREFERENCES_STRUP_LANGUAGE, "Ru"); } else { mStrupLang = "Ru"; } alphabetColors.clear(); alphabetColors.add(Color.RED); alphabetColors.add(Color.parseColor("#FFA500")); alphabetColors.add(Color.parseColor("#53b814")); alphabetColors.add(Color.parseColor("#FF7B15CE")); alphabetColors.add(Color.BLUE); alphabetColors.add(Color.GRAY); alphabetColors.add(Color.parseColor("#EE82EE")); alphabetColors.add(Color.parseColor("#8B4513")); alphabetWords.clear(); switch (mStrupLang) { case "Ru": alphabetWords.add("КРАСНЫЙ"); alphabetWords.add("ОРАНЖЕВЫЙ"); alphabetWords.add("ЗЕЛЕНЫЙ"); alphabetWords.add("ФИОЛЕТОВЫЙ"); alphabetWords.add("СИНИЙ"); alphabetWords.add("СЕРЫЙ"); alphabetWords.add("РОЗОВЫЙ"); alphabetWords.add("КОРИЧНЕВЫЙ"); case "En": alphabetWords.add("RED"); alphabetWords.add("ORANGE"); alphabetWords.add("GREEN"); alphabetWords.add("VIOLET"); alphabetWords.add("BLUE"); alphabetWords.add("GRAY"); alphabetWords.add("ROSE"); alphabetWords.add("BROWN"); default: break; } } }
package org.corbin.common.entity; import lombok.Getter; import lombok.Setter; import org.corbin.common.base.entity.BaseEntity; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.Table; import java.io.Serializable; @Entity @Getter @Setter @DynamicInsert @DynamicUpdate @EntityListeners(AuditingEntityListener.class) @Table(name = "song_statistics_day_log") public class SongStatisticsDayLog extends BaseEntity implements Serializable { @Column(name = "song_id") private Long songId; @Column(name = "play_num_y") private Integer playTimesYesterday; @Column(name = "play_num_t") private Integer playTimesToday; @Column(name = "star_num_y") private Integer starTimesYesterday; @Column(name = "star_num_t") private Integer starTimesToday; @Column(name = "collect_num_y") private Integer collectTimesYesterday; @Column(name = "collect_num_t") private Integer collectTimesToday; /** * 今日歌曲热度 */ @Column(name = "hot_point") private Double hotPoint; /** * 今日歌曲推荐指数 */ @Column(name = "recommend_point") private Double recommendPoint; }
package com.yunhe.cargomanagement.service; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.yunhe.basicdata.entity.CommodityList; import com.yunhe.cargomanagement.entity.OrderConnectComm; import com.yunhe.cargomanagement.entity.SalesOrderHistory; import com.baomidou.mybatisplus.extension.service.IService; import org.apache.logging.log4j.util.PropertySource; import java.io.Serializable; import java.util.Comparator; import java.util.List; import java.util.Map; /** * <p> * 销售订单历史 服务类 * </p> * * @author 刘延琦 * @since 2019-01-05 */ public interface ISalesOrderHistoryService extends IService<SalesOrderHistory> { /** * <p> * 条件查询销售历史 * </p> * @param cond * @return 销售历史 */ Page queryLikeList(Map cond); /** * 更新销售订单历史 * @param salesOrderHistory 要更新的销售历史记录的信息 * @return int */ int updateSale(SalesOrderHistory salesOrderHistory); /** * 根据id删除销售历史记录 * @param id 当前销售记录的id * @return int */ int deleteById(Serializable id); /** * 插入新的销售订单历史 * @param salesOrderHistory 要插入的销售历史记录的信息 * @return int */ int insertSale(SalesOrderHistory salesOrderHistory); /** * 根据id查询对应的销售 * @param id * @return */ SalesOrderHistory selectById(int id); SalesOrderHistory selectByNumber(SalesOrderHistory salesOrderHistory); /** * 查询所有的 * @return */ List<SalesOrderHistory> selectAll(); List<OrderConnectComm> detailList(int id); }
public class BinarySearchTreeInsertion { Node root; static class Node { int key; Node left, right; Node(int keyValue) { key = keyValue; left = null; right = null; } } public static void main(String[] args) { BinarySearchTreeInsertion tree = new BinarySearchTreeInsertion(); // tree.root = new Node(5); // tree.root.left = new Node(3); // tree.root.right = new Node(7); // tree.root.left.left = new Node(2); // tree.root.left.right = new Node(4); // tree.root.right.left = new Node(6); // tree.root.right.right = new Node(8); tree.root = new Node(4); tree.root.left = new Node(2); tree.root.right = new Node(7); tree.root.left.left = new Node(1); tree.root.left.right = new Node(3); int numToBeInserted = 6; nodeInsertion(tree.root,numToBeInserted); inOrder(tree.root); } private static void nodeInsertion(Node root, int num) { Node current = root; while(current.left != null && current.right != null){ if(current.key < num){ current = current.right; } else { current = current.left; } } Node newNode = new Node(num); if(current.key < newNode.key) current.right = newNode; else current.left = newNode; } public static void inOrder(Node root){ if(root == null) return; inOrder(root.left); System.out.println(root.key); inOrder(root.right); } }
package ru.nikozavr.auto.instruments.database.MarqInfo.MarqModel; import ru.nikozavr.auto.model.Marque; /** * Created by nikozavr on 3/21/14. */ public interface AsyncMarqModels { void getModelsFinish(Marque result); }
package com.example.nitiya.searchnonthaburi; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ImageButton; public class Manu01 extends AppCompatActivity { ImageButton img01, img02, img03; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.manu01); img01 = (ImageButton) findViewById(R.id.manu001); img01.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(Manu01.this, Manu0011.class); startActivity(i); } }); img02 = (ImageButton) findViewById(R.id.manu002); img02.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(Manu01.this, Maps.class); startActivity(i); } }); img03 = (ImageButton) findViewById(R.id.btn03_shr9); img03.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(Manu01.this, Manu0012.class); startActivity(i); } }); } }
/* * 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 presentacion; import logica.Logica; /** * * @author Cheetos, Calec y Alejandro */ public class Modelo { private Vista vista; private Logica sistema; public Modelo() { } public void iniciar(){ getVentana().setVisible(true); getVentana().llenarMuestra(getLogica().getLista()); } public Vista getVentana() { if(vista == null){ vista = new Vista(this); } return vista; } public Logica getLogica(){ if(sistema==null){ sistema = new Logica(); } return sistema; } public void enviarMedia(){ getVentana().cambiarMedia(getLogica().calcularMedia()); } public void enviarMediana(){ getVentana().cambiarMediana(getLogica().calcularMediana()); } public void enviarModa(){ getVentana().cambiarModa(getLogica().calcularModa()); } public void enviarVarianza(){ getVentana().cambiarVarianza(getLogica().calcularVarianza()); } public void enviarDesviacion(){ getVentana().cambiarDesviacion(getLogica().calcularDesviacion()); } }
package iarfmoose; import com.github.ocraft.s2client.bot.S2Agent; import com.github.ocraft.s2client.bot.gateway.UnitInPool; public abstract class ActiveManager implements Manager { S2Agent bot; BaseLocator baseLocator; public ActiveManager(S2Agent bot, BaseLocator baseLocator) { this.bot = bot; this.baseLocator = baseLocator; } public abstract void onStep(); public abstract void onUnitCreated(UnitInPool unitInPool); public abstract void onUnitDestroyed(UnitInPool unitInPool); }
package com.zinnaworks.nxpgtool.controller; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.ResourceUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import com.zinnaworks.nxpgtool.api.ExcelParser; import com.zinnaworks.nxpgtool.common.FileStorageProperties; import com.zinnaworks.nxpgtool.service.FileStorageService; import com.zinnaworks.nxpgtool.util.CommonUtils; import com.zinnaworks.nxpgtool.util.JsonUtil; @RequestMapping("/nxpgtool") @Controller public class ExcelController { private static final Logger logger = LoggerFactory.getLogger(ExcelController.class); @Autowired private FileStorageService fileStorageServiceImpl; @Autowired FileStorageProperties fileStorageProperties; @RequestMapping("/excel") public String hello(Model model, @RequestParam(defaultValue = "Ryan") String name) throws FileNotFoundException { model.addAttribute("name", name); return "tiles/thymeleaf/excel"; } @ResponseBody @PostMapping("/uploadFile") public String uploadFile(@RequestParam("file") MultipartFile file, HttpServletResponse res) { String fileName = fileStorageServiceImpl.storeFile(file); String uploadDir = fileStorageProperties.getUploadDir(); try { ExcelParser parser = new ExcelParser(uploadDir + "/" +fileName); Map<String, Map<String, Object>> ifInfos = parser.parseAllSheet(); for(Map.Entry<String, Map<String, Object>> info : ifInfos.entrySet()) { String ifName = info.getKey(); String json = JsonUtil.objectToJson(info.getValue()); CommonUtils.saveJson(uploadDir + "/" +ifName + ".json", json); } } catch (Exception e) { throw new RuntimeException(e); } return "ok"; } @GetMapping("/resource/download") public ResponseEntity<Resource> downloadFile(HttpServletRequest request) throws IOException { File f = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "api_field_template.xlsx"); Resource resource = fileStorageServiceImpl.loadFileAsResource(f.getAbsolutePath()); String contentType = null; try { contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath()); } catch (IOException ex) { logger.info("Could not determine file type."); throw ex; } if (contentType == null) { contentType = "application/octet-stream"; } return ResponseEntity.ok().contentType(MediaType.parseMediaType(contentType)) .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") .body(resource); } }
package com.tencent.mm.plugin.fts; import com.tencent.mm.plugin.fts.a.a.a; import com.tencent.mm.plugin.fts.a.a.g; import com.tencent.mm.plugin.fts.a.a.i; import com.tencent.mm.plugin.fts.a.a.j; import com.tencent.mm.plugin.fts.a.l; import java.lang.ref.WeakReference; import java.util.LinkedList; public final class b extends a implements Runnable { private int errorCode; private i joH; private WeakReference<l> joI; public b(int i, i iVar) { this.errorCode = i; this.joH = iVar; this.joI = new WeakReference(iVar.jsv); this.joH.jsv = null; } public final boolean execute() { if (this.errorCode == -2 || this.errorCode == -3) { j jVar = new j(this.joH); jVar.jsw = this; jVar.bjW = this.errorCode; jVar.jsx = new LinkedList(); jVar.jrx = g.ax(this.joH.bWm, false); if (this.joH.handler == null) { l lVar = (l) this.joI.get(); if (lVar != null) { lVar.b(jVar); } } else { this.joH.handler.post(new 1(this, jVar)); } } return true; } public final void run() { try { execute(); } catch (Exception e) { } } public final int getPriority() { return 0; } public final boolean isCancelled() { return false; } public final int getId() { return -1; } }
package com.curd.springboot.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.validation.constraints.Email; import javax.validation.constraints.NotNull; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import org.springframework.data.annotation.CreatedBy; import org.springframework.data.annotation.LastModifiedBy; import org.springframework.data.jpa.domain.support.AuditingEntityListener; @Entity @Data @Table(name = "users") @EntityListeners(AuditingEntityListener.class) public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) @ApiModelProperty(notes = "ID of the User", name = "id", required = true) private long id; @Column(name = "first_name", nullable = false) @NotNull @ApiModelProperty(notes = "First Name of the User", name = "first_name", required = true, value = "test_first_name") private String firstName; @Column(name = "last_name", nullable = false) @NotNull @ApiModelProperty(notes = "Last Name of the User", name = "last_name", required = true, value = "test_last_name") private String lastName; @Column(name = "email_address", nullable = false) @Email @NotNull @ApiModelProperty(notes = "Email Address of the User", name = "email_address", required = true, value = "test_email") private String emailId; @Column(name = "created_by", nullable = false) @NotNull @ApiModelProperty(notes = "Who has created the User", name = "created_by", required = true, value = "created_name") @CreatedBy private String createdBy; @Column(name = "updated_by", nullable = false) @NotNull @ApiModelProperty(notes = "Who has updated the User", name = "updated_by", required = true, value = "updated_name") @LastModifiedBy private String updatedby; }
package jumpingalien.part3.programs.Statements; import java.util.List; import java.util.ArrayList; import java.util.Collection; import java.util.TreeMap; import jumpingalien.model.GameObject; import jumpingalien.part3.programs.IProgramFactory.SortDirection; import jumpingalien.part3.programs.Program; import jumpingalien.part3.programs.SourceLocation; import jumpingalien.part3.programs.IProgramFactory.Kind; import jumpingalien.part3.programs.Expressions.Expression; public class ForEach extends ComposedStatement{ public ForEach(String variableName, Kind variableKind, Expression<Boolean> where, Expression<Double> sort, SortDirection sortDirection, Statement body, SourceLocation sourceLocation) { this.kind = variableKind; this.where = where; this.sort = sort; this.sortDirection = sortDirection; this.body = body; } @Override public boolean hasSubStatement(Statement statement) { return true; } public Kind getKind(){ return this.kind; } private final Kind kind; public Expression<Boolean> getWhereExpression() { return this.where; } private final Expression<Boolean> where; public Expression<Double> getSortExpression() { return this.sort; } private final Expression<Double> sort; public SortDirection getSortDirection() { return this.sortDirection; } private final SortDirection sortDirection; public Statement getBody() { return this.body; } private final Statement body; @Override public void execute(Program program) { Collection<GameObject> objects = makeObjectArray(program); if (where != null) { objects = filterList(program, objects); } if ((sort != null) && (isValidSortKind(getKind()))) { objects = sortList(program, objects); } for (GameObject gameObject : objects) { body.execute(gameObject.getProgram()); } } private boolean isValidSortKind(Kind kind) { return !((kind == Kind.ANY) || (kind == Kind.TERRAIN) || (kind == Kind.MAZUB)); } public Collection<GameObject> makeObjectArray(Program program){ Collection<GameObject> list = new ArrayList<GameObject>(); Kind kind = getKind(); if (kind == Kind.MAZUB){ list.add(program.getPossessedObject().getWorld().getMazub()); }else if (kind == Kind.BUZAM){ list.add(program.getPossessedObject().getWorld().getBuzam()); }else if (kind == Kind.SLIME){ list.addAll(program.getPossessedObject().getWorld().getSlimes()); }else if (kind == Kind.SHARK){ list.addAll(program.getPossessedObject().getWorld().getSharks()); }else if (kind == Kind.PLANT){ list.addAll(program.getPossessedObject().getWorld().getPlants()); }else if (kind == Kind.TERRAIN){ list.addAll(program.getPossessedObject().getWorld().getTiles()); }else{ list.addAll(program.getPossessedObject().getWorld().getAllObjects()); } return list; } public Collection<GameObject> filterList(Program program, Collection<GameObject> objects){ Collection<GameObject> filteredList = new ArrayList<GameObject>(); for(GameObject gameObject : objects){ if (getWhereExpression().evaluate(program)){ filteredList.add(gameObject); } } return filteredList; } public Collection<GameObject> sortList(Program program, Collection<GameObject> objects){ TreeMap<Double, GameObject> sortedList = new TreeMap<Double, GameObject>(); for(GameObject gameObject : objects){ Double sortDouble = getSortExpression().evaluate(gameObject.getProgram()); sortedList.put(sortDouble, gameObject); } if (getSortDirection() == SortDirection.ASCENDING) return sortedList.values(); else if (getSortDirection() == SortDirection.DESCENDING) { List<GameObject> sortedValues = new ArrayList<GameObject>(sortedList.values()); java.util.Collections.reverse(sortedValues); return sortedValues; } else { return objects; } } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2017.01.28 at 02:11:12 PM CST // package org.mesa.xml.b2mml; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for SegmentDependencyType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="SegmentDependencyType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="ID" type="{http://www.mesa.org/xml/B2MML-V0600}IdentifierType"/> * &lt;element name="Description" type="{http://www.mesa.org/xml/B2MML-V0600}DescriptionType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="Dependency" type="{http://www.mesa.org/xml/B2MML-V0600}DependencyType"/> * &lt;element name="TimingFactor" type="{http://www.mesa.org/xml/B2MML-V0600}ValueType" maxOccurs="unbounded" minOccurs="0"/> * &lt;choice maxOccurs="unbounded" minOccurs="0"> * &lt;element name="ProductSegmentID" type="{http://www.mesa.org/xml/B2MML-V0600}ProductSegmentIDType"/> * &lt;element name="ProcessSegmentID" type="{http://www.mesa.org/xml/B2MML-V0600}ProcessSegmentIDType"/> * &lt;element name="SegmentID" type="{http://www.mesa.org/xml/B2MML-V0600}IdentifierType"/> * &lt;/choice> * &lt;group ref="{http://www.mesa.org/xml/B2MML-V0600-AllExtensions}SegmentDependency" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "SegmentDependencyType", propOrder = { "id", "description", "dependency", "timingFactor", "productSegmentIDOrProcessSegmentIDOrSegmentID" }) public class SegmentDependencyType { @XmlElement(name = "ID", required = true) protected IdentifierType id; @XmlElement(name = "Description") protected List<DescriptionType> description; @XmlElement(name = "Dependency", required = true) protected DependencyType dependency; @XmlElement(name = "TimingFactor") protected List<ValueType> timingFactor; @XmlElements({ @XmlElement(name = "ProductSegmentID", type = ProductSegmentIDType.class), @XmlElement(name = "ProcessSegmentID", type = ProcessSegmentIDType.class), @XmlElement(name = "SegmentID") }) protected List<IdentifierType> productSegmentIDOrProcessSegmentIDOrSegmentID; /** * Gets the value of the id property. * * @return * possible object is * {@link IdentifierType } * */ public IdentifierType getID() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link IdentifierType } * */ public void setID(IdentifierType value) { this.id = value; } /** * Gets the value of the description property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the description property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDescription().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DescriptionType } * * */ public List<DescriptionType> getDescription() { if (description == null) { description = new ArrayList<DescriptionType>(); } return this.description; } /** * Gets the value of the dependency property. * * @return * possible object is * {@link DependencyType } * */ public DependencyType getDependency() { return dependency; } /** * Sets the value of the dependency property. * * @param value * allowed object is * {@link DependencyType } * */ public void setDependency(DependencyType value) { this.dependency = value; } /** * Gets the value of the timingFactor property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the timingFactor property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTimingFactor().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ValueType } * * */ public List<ValueType> getTimingFactor() { if (timingFactor == null) { timingFactor = new ArrayList<ValueType>(); } return this.timingFactor; } /** * Gets the value of the productSegmentIDOrProcessSegmentIDOrSegmentID property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the productSegmentIDOrProcessSegmentIDOrSegmentID property. * * <p> * For example, to add a new item, do as follows: * <pre> * getProductSegmentIDOrProcessSegmentIDOrSegmentID().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ProductSegmentIDType } * {@link ProcessSegmentIDType } * {@link IdentifierType } * * */ public List<IdentifierType> getProductSegmentIDOrProcessSegmentIDOrSegmentID() { if (productSegmentIDOrProcessSegmentIDOrSegmentID == null) { productSegmentIDOrProcessSegmentIDOrSegmentID = new ArrayList<IdentifierType>(); } return this.productSegmentIDOrProcessSegmentIDOrSegmentID; } }
package com.eres.waiter.waiter.logic; import com.eres.waiter.waiter.model.singelton.DataSingelton; import com.eres.waiter.waiter.preferance.SettingPreferances; import com.eres.waiter.waiter.viewpager.model.Hall; public class BaseLogic { public String textSubString(String s, int n, boolean more) { return more ? s.substring(0, n) + "..." : s.substring(0, n); } public void seveHallName(int id) { for (Hall hall : DataSingelton.singelton.getHalls()) { if (hall.getId() == id) { SettingPreferances.preferances.setHallName(hall.getName()); break; } } } }
import javax.swing.JOptionPane; import images.APImage; import images.Pixel; public class images1 { public static void main(String[] args) { APImage image = new APImage("res/smokey.jpg" ); int x = image.getWidth(); int y = image.getHeight(); image.setSize(x,y); image.setTitle("Color to Black & White"); for(Pixel pixel : image) { int avg = (int)((pixel.getBlue() * .114) + (int)(pixel.getGreen() * .587) + (int)(pixel.getRed() * .299)); pixel.setRed(avg); pixel.setBlue(avg); pixel.setGreen(avg); } image.draw(); } }
package com.box.androidsdk.content.auth; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import com.box.androidsdk.content.BoxApiUser; import com.box.androidsdk.content.BoxConfig; import com.box.androidsdk.content.BoxConstants; import com.box.androidsdk.content.BoxException; import com.box.androidsdk.content.BoxFutureTask; import com.box.androidsdk.content.models.BoxEntity; import com.box.androidsdk.content.models.BoxJsonObject; import com.box.androidsdk.content.models.BoxSession; import com.box.androidsdk.content.models.BoxUser; import com.box.androidsdk.content.requests.BoxResponse; import com.box.androidsdk.content.utils.BoxLogUtils; import com.box.androidsdk.content.utils.SdkUtils; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; import java.lang.ref.WeakReference; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.FutureTask; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * Handles authentication and stores authentication information. */ public class BoxAuthentication { // Third parties who are looking to provide their own refresh logic should replace this with the constructor that takes a refreshProvider. private static final BoxAuthentication mAuthentication = new BoxAuthentication(); private ConcurrentLinkedQueue<WeakReference<AuthListener>> mListeners = new ConcurrentLinkedQueue<>(); private ConcurrentHashMap<String, BoxAuthenticationInfo> mCurrentAccessInfo; private final ConcurrentHashMap<String, FutureTask> mRefreshingTasks = new ConcurrentHashMap<>(); private static final ThreadPoolExecutor AUTH_EXECUTOR = SdkUtils.createDefaultThreadPoolExecutor(1, 1, 3600, TimeUnit.SECONDS); private AuthenticationRefreshProvider mRefreshProvider; private static final String TAG = BoxAuthentication.class.getName(); // These fields are the minimum amount of fields we will need to know display a user. public static final String[] MINIMUM_USER_FIELDS = new String[]{ BoxUser.FIELD_TYPE, BoxUser.FIELD_ID, BoxUser.FIELD_NAME, BoxUser.FIELD_LOGIN, BoxUser.FIELD_SPACE_AMOUNT, BoxUser.FIELD_SPACE_USED, BoxUser.FIELD_MAX_UPLOAD_SIZE, BoxUser.FIELD_STATUS, BoxUser.FIELD_ENTERPRISE, BoxUser.FIELD_CREATED_AT }; private AuthStorage authStorage = new AuthStorage(); private BoxAuthentication() { } private BoxAuthentication(final AuthenticationRefreshProvider refreshProvider) { mRefreshProvider = refreshProvider; } /** * Get the BoxAuthenticationInfo for a given user. * @param userId the user id to get auth info for. * @param context current context used for accessing resource. * @return the BoxAuthenticationInfo for a given user. */ public BoxAuthenticationInfo getAuthInfo(String userId, Context context) { return userId == null ? null : getAuthInfoMap(context).get(userId); } /** * Get a map of all stored auth information. * * @param context current context. * @return a map with all stored user information, or null if no user info has been stored. */ public Map<String, BoxAuthenticationInfo> getStoredAuthInfo(final Context context) { return getAuthInfoMap(context); } /** * Get the user id that was last authenticated. * * @param context current context. * @return the user id that was last authenticated or null if it does not exist or was removed. */ public String getLastAuthenticatedUserId(final Context context) { return authStorage.getLastAuthentictedUserId(context); } /** * Get singleton instance of the BoxAuthentication object. * @return singleton instance of the BoxAuthentication object. */ public static BoxAuthentication getInstance() { return mAuthentication; } /** * Set the storage to store auth information. By default, sharedpref is used. You can use this method to use your own storage class that extends the AuthStorage. * @param storage set a custom implementation of AuthStorage. */ public void setAuthStorage(AuthStorage storage) { this.authStorage = storage; } /** * @return Get the auth storage used to store auth information. */ public AuthStorage getAuthStorage() { return authStorage; } /** * Get the refresh provider if singleton was created with one, or one was set. * @return the custom refresh provider implementation if set. */ public AuthenticationRefreshProvider getRefreshProvider(){ return mRefreshProvider; } /** * @param refreshProvider a custom refresh provider in case developer is using app user. */ public void setRefreshProvider(AuthenticationRefreshProvider refreshProvider){ mRefreshProvider = refreshProvider; } /** * Launch ui to authenticate. * @param session to authenticate using ui. */ public synchronized void startAuthenticationUI(BoxSession session) { startAuthenticateUI(session); } /** * Callback method to be called when authentication process finishes. * @param infoOriginal the authentication information that successfully authenticated. * @param context the current application context (that can be used to launch ui or access resources). */ public void onAuthenticated(BoxAuthenticationInfo infoOriginal, Context context) { BoxAuthenticationInfo info = BoxAuthenticationInfo.unmodifiableObject(infoOriginal); if (!SdkUtils.isBlank(info.accessToken()) && (info.getUser() == null || SdkUtils.isBlank(info.getUser().getId()))){ // insufficient information so we need to fetch the user info first. doUserRefresh(context, info); return; } getAuthInfoMap(context).put(info.getUser().getId(), info.clone()); authStorage.storeLastAuthenticatedUserId(info.getUser().getId(), context); authStorage.storeAuthInfoMap(mCurrentAccessInfo, context); // if accessToken has not already been refreshed, issue refresh request and cache result Set<AuthListener> listeners = getListeners(); for (AuthListener listener : listeners) { listener.onAuthCreated(info); } } /** * Callback method to be called if authentication process fails. * @param infoOriginal the authentication information associated with the failed authentication. * @param ex the exception if appliable that caused the logout. */ public void onAuthenticationFailure(BoxAuthenticationInfo infoOriginal, Exception ex) { String msg = "failure:"; if (getAuthStorage() != null) { msg += "auth storage :" + getAuthStorage().toString(); } BoxAuthenticationInfo info = BoxAuthenticationInfo.unmodifiableObject(infoOriginal); if (info != null) { msg += info.getUser() == null ? "null user" : info.getUser().getId() == null ? "null user id" : info.getUser().getId().length(); } BoxLogUtils.nonFatalE("BoxAuthfail", msg , ex); Set<AuthListener> listeners = getListeners(); for (AuthListener listener : listeners) { listener.onAuthFailure(info, ex); } } /** * Callback method to be called on logout. * @param infoOriginal the authentication information associated with the user that was logged out. * @param ex the exception if appliable that caused the logout. */ public void onLoggedOut(BoxAuthenticationInfo infoOriginal, Exception ex) { BoxAuthenticationInfo info = BoxAuthenticationInfo.unmodifiableObject(infoOriginal); Set<AuthListener> listeners = getListeners(); for (AuthListener listener : listeners) { listener.onLoggedOut(info, ex); } } /** * * @return all listeners set to listen to authentication process */ public Set<AuthListener> getListeners() { Set<AuthListener> listeners = new LinkedHashSet<AuthListener>(); for (WeakReference<AuthListener> reference : mListeners) { AuthListener rc = reference.get(); if (rc != null) { listeners.add(rc); } } if (mListeners.size() > listeners.size()) { //clean up mListeners mListeners = new ConcurrentLinkedQueue<>(); for (AuthListener listener : listeners) { mListeners.add(new WeakReference<>(listener)); } } return listeners; } /** * Log out current BoxSession. After logging out, the authentication information related to the Box user in this session will be gone. * @param session session to logout user from */ public synchronized void logout(final BoxSession session) { BoxUser user = session.getUser(); if (user == null) { return; } session.clearCache(); Context context = session.getApplicationContext(); String userId = user.getId(); getAuthInfoMap(session.getApplicationContext()); BoxAuthenticationInfo info = mCurrentAccessInfo.get(userId); Exception ex = null; try { BoxApiAuthentication api = new BoxApiAuthentication(session); BoxApiAuthentication.BoxRevokeAuthRequest request = api.revokeOAuth(info.refreshToken(), session.getClientId(), session.getClientSecret()); request.send(); } catch (Exception e) { ex = e; BoxLogUtils.e(TAG, "logout", e); // Do nothing as we want to continue wiping auth info } mCurrentAccessInfo.remove(userId); String lastUserId = authStorage.getLastAuthentictedUserId(context); if (lastUserId != null) { authStorage.storeLastAuthenticatedUserId(null, context); } authStorage.storeAuthInfoMap(mCurrentAccessInfo, context); onLoggedOut(info, ex); info.wipeOutAuth(); } /** * Log out all users. After logging out, all authentication information will be gone. * @param context current context */ public synchronized void logoutAllUsers(Context context) { getAuthInfoMap(context); for (String userId : mCurrentAccessInfo.keySet()) { BoxSession session = new BoxSession(context, userId); logout(session); } authStorage.clearAuthInfoMap(context); } /** * Create Oauth for the first time. This method should be called by ui to authenticate the user for the first time. * @param session a box session with all the necessary information to authenticate the user for the first time. * @param code the code returned by web page necessary to authenticate. * @return a future task allowing monitoring of the api call. */ public synchronized FutureTask<BoxAuthenticationInfo> create(BoxSession session, final String code) { FutureTask<BoxAuthenticationInfo> task = doCreate(session,code); BoxAuthentication.AUTH_EXECUTOR.submit(task); return task; } /** * Refresh the OAuth in the given BoxSession. This method is called when OAuth token expires. * @param session a box session with all the necessary information to authenticate the user for the first time. * @return a future task allowing monitoring of the api call. */ public synchronized FutureTask<BoxAuthenticationInfo> refresh(BoxSession session) { BoxUser user = session.getUser(); if (user == null) { return doRefresh(session, session.getAuthInfo()); } // Fetch auth info map from storage if not present. getAuthInfoMap(session.getApplicationContext()); BoxAuthenticationInfo info = mCurrentAccessInfo.get(user.getId()); if (info == null) { // session has info that we do not. ? is there any other situation we want to update our info based on session info? we can do checks against // refresh time. mCurrentAccessInfo.put(user.getId(), session.getAuthInfo()); info = mCurrentAccessInfo.get(user.getId()); } // No need to refresh if we have already refreshed within 15 seconds or have a newer access token already. if (session.getAuthInfo().accessToken() == null || (!session.getAuthInfo().accessToken().equals(info.accessToken()) && info.getRefreshTime() != null && System.currentTimeMillis() - info.getRefreshTime() < 15000)) { final BoxAuthenticationInfo latestInfo = info; // this session is probably using old information. Give it our information. BoxAuthenticationInfo.cloneInfo(session.getAuthInfo(), info); FutureTask task = new FutureTask<>(new Callable<BoxAuthenticationInfo>() { @Override public BoxAuthenticationInfo call() throws Exception { return latestInfo; } }); AUTH_EXECUTOR.execute(task); return task; } FutureTask task = mRefreshingTasks.get(user.getId()); if (task != null && !(task.isCancelled() || task.isDone())) { // We already have a refreshing task for this user. No need to do anything. return task; } // long currentTime = System.currentTimeMillis(); // if ((currentTime - info.refreshTime) > info.refreshTime - EXPIRATION_GRACE) { // this access info is close to expiration or has passed expiration time needs to be refreshed before usage. // } // create the task to do the refresh and put it in mRefreshingTasks and execute it. return doRefresh(session, info); } private FutureTask<BoxAuthenticationInfo> doCreate(final BoxSession session, final String code) { FutureTask<BoxAuthenticationInfo> task = new FutureTask<>(new Callable<BoxAuthenticationInfo>() { @Override public BoxAuthenticationInfo call() throws Exception { BoxApiAuthentication api = new BoxApiAuthentication(session); BoxApiAuthentication.BoxCreateAuthRequest request = api.createOAuth(code, session.getClientId(), session.getClientSecret()); BoxAuthenticationInfo info = new BoxAuthenticationInfo(); BoxAuthenticationInfo.cloneInfo(info, session.getAuthInfo()); BoxAuthenticationInfo authenticatedInfo = request.send(); info.setAccessToken(authenticatedInfo.accessToken()); info.setRefreshToken(authenticatedInfo.refreshToken()); info.setExpiresIn(authenticatedInfo.expiresIn()); info.setRefreshTime(System.currentTimeMillis()); BoxSession tempSession = new BoxSession(session.getApplicationContext(), info, null); BoxApiUser userApi = new BoxApiUser(tempSession); BoxUser user = userApi.getCurrentUserInfoRequest().setFields(MINIMUM_USER_FIELDS).send(); info.setUser(user); BoxAuthentication.getInstance().onAuthenticated(info, session.getApplicationContext()); return info; } }); return task; } private BoxFutureTask<BoxUser> doUserRefresh(final Context context, final BoxAuthenticationInfo info){ BoxSession tempSession = new BoxSession(context, info.accessToken(), null); BoxApiUser apiUser = new BoxApiUser(tempSession); BoxFutureTask<BoxUser> task = apiUser.getCurrentUserInfoRequest().setFields(MINIMUM_USER_FIELDS).toTask(); task.addOnCompletedListener(new BoxFutureTask.OnCompletedListener<BoxUser>() { @Override public void onCompleted(BoxResponse<BoxUser> response) { if (response.isSuccess()) { info.setUser(response.getResult()); BoxAuthentication.getInstance().onAuthenticated(info, context); } else { BoxAuthentication.getInstance().onAuthenticationFailure(info, response.getException()); } } }); AUTH_EXECUTOR.execute(task); return task; } /** * Add listener to listen to the authentication process for this BoxSession. * @param listener listener for authentication */ public synchronized void addListener(AuthListener listener) { if (getListeners().contains(listener)){ return; } mListeners.add(new WeakReference<>(listener)); } /** * Start authentication UI. * * @param session the session to authenticate. */ private synchronized void startAuthenticateUI(BoxSession session) { Context context = session.getApplicationContext(); Intent intent = OAuthActivity.createOAuthActivityIntent(context, session, BoxAuthentication.isBoxAuthAppAvailable(context) && session.isEnabledBoxAppAuthentication()); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } private BoxException.RefreshFailure handleRefreshException(final BoxSession session, final BoxException e, final BoxAuthenticationInfo info, final String userId) { BoxException.RefreshFailure refreshFailure = new BoxException.RefreshFailure(e); if (refreshFailure.isErrorFatal() || refreshFailure.getErrorType() == BoxException.ErrorType.TERMS_OF_SERVICE_REQUIRED){ // if the current user is logged out remove the last authenticated user id. if (userId != null && userId.equals(getAuthStorage().getLastAuthentictedUserId(session.getApplicationContext()))){ getAuthStorage().storeLastAuthenticatedUserId(null, session.getApplicationContext()); } // if the error is fatal then wipe out authentication information. getAuthInfoMap(session.getApplicationContext()).remove(userId); getAuthStorage().storeAuthInfoMap(mCurrentAccessInfo, session.getApplicationContext()); } BoxAuthentication.getInstance().onAuthenticationFailure(info, refreshFailure); return refreshFailure; } private FutureTask<BoxAuthenticationInfo> doRefresh(final BoxSession session, final BoxAuthenticationInfo info) { final boolean userUnknown = (info.getUser() == null && session.getUser() == null); final String taskKey = SdkUtils.isBlank(session.getUserId()) && userUnknown ? info.accessToken() : session.getUserId(); final String userId = (info.getUser() != null) ? info.getUser().getId() : session.getUserId(); FutureTask<BoxAuthenticationInfo> task = new FutureTask<>(new Callable<BoxAuthenticationInfo>() { @Override public BoxAuthenticationInfo call() throws Exception { BoxAuthenticationInfo refreshInfo; if (session.getRefreshProvider() != null) { try { refreshInfo = session.getRefreshProvider().refreshAuthenticationInfo(info); } catch (BoxException e) { mRefreshingTasks.remove(taskKey); throw handleRefreshException(session, e, info, userId); } } else if (mRefreshProvider != null) { try { refreshInfo = mRefreshProvider.refreshAuthenticationInfo(info); } catch (BoxException e) { mRefreshingTasks.remove(taskKey); throw handleRefreshException(session, e, info, userId); } } else { String refreshToken = info.refreshToken() != null ? info.refreshToken() : ""; String clientId = session.getClientId() != null ? session.getClientId() : BoxConfig.CLIENT_ID; String clientSecret = session.getClientSecret() != null ? session.getClientSecret() : BoxConfig.CLIENT_SECRET; if (SdkUtils.isBlank(clientId) || SdkUtils.isBlank(clientSecret)) { BoxException badRequest = new BoxException("client id or secret not specified", 400, "{\"error\": \"bad_request\",\n" + " \"error_description\": \"client id or secret not specified\"}", null); throw handleRefreshException(session, badRequest, info, userId); } BoxApiAuthentication.BoxRefreshAuthRequest request = new BoxApiAuthentication(session).refreshOAuth(refreshToken, clientId, clientSecret); try { refreshInfo = request.send(); } catch (BoxException e) { mRefreshingTasks.remove(taskKey); throw handleRefreshException(session, e, info, userId); } } if (refreshInfo != null) { refreshInfo.setRefreshTime(System.currentTimeMillis()); } BoxAuthenticationInfo.cloneInfo(session.getAuthInfo(), refreshInfo); // if we using a custom refresh provider ensure we check the user, otherwise do this only if we don't know who the user is. if (userUnknown || session.getRefreshProvider() != null || mRefreshProvider != null) { BoxApiUser userApi = new BoxApiUser(session); info.setUser(userApi.getCurrentUserInfoRequest().setFields(BoxAuthentication.MINIMUM_USER_FIELDS).send()); } getAuthInfoMap(session.getApplicationContext()).put(info.getUser().getId(), refreshInfo); getAuthStorage().storeAuthInfoMap(mCurrentAccessInfo, session.getApplicationContext()); // call notifyListeners() with results. for (WeakReference<AuthListener> reference : mListeners) { AuthListener rc = reference.get(); if (rc != null) { rc.onRefreshed(refreshInfo); } } if (!session.getUserId().equals(info.getUser().getId())) { session.onAuthFailure(info, new BoxException("Session User Id has changed!")); } mRefreshingTasks.remove(taskKey); return info; } }); mRefreshingTasks.put(taskKey, task); AUTH_EXECUTOR.execute(task); return task; } private ConcurrentHashMap<String, BoxAuthenticationInfo> getAuthInfoMap(Context context) { if (mCurrentAccessInfo == null) { mCurrentAccessInfo = authStorage.loadAuthInfoMap(context); } return mCurrentAccessInfo; } /** * Interface of a listener to listen to authentication events. */ public interface AuthListener { /** * Called when the current session has been refreshed with new authentication info. * * @param info the latest info from a successful refresh. */ void onRefreshed(BoxAuthenticationInfo info); /** * Called when this user has logged in. * * @param info the latest info from going through the login flow. */ void onAuthCreated(BoxAuthenticationInfo info); /** * Called when a failure occurs trying to authenticate or refresh. * * @param info The last authentication information available, before the exception. * @param ex the exception that occurred. */ void onAuthFailure(BoxAuthentication.BoxAuthenticationInfo info, Exception ex); /** * Called when the session was logged out of * * @param info The last authentication information available * @param ex the exception that occurred, if any */ void onLoggedOut(BoxAuthentication.BoxAuthenticationInfo info, Exception ex); } /** * An interface that should be implemented if using a custom authentication scheme and not the default oauth 2 based token refresh logic. */ public interface AuthenticationRefreshProvider { /** * This method should return a refreshed authentication info object given one that is expired or nearly expired. * * @param info the expired authentication information. * @return a refreshed BoxAuthenticationInfo object. The object must include the valid access token. * @throws BoxException Exception that should be thrown if there was a problem fetching the information. */ BoxAuthenticationInfo refreshAuthenticationInfo(BoxAuthenticationInfo info) throws BoxException; /** * This method should launch an activity or perform necessary logic in order to authenticate a user for the first time or re-authenticate a user if necessary. * Implementers should call BoxAuthenciation.getInstance().onAuthenticated(BoxAuthenticationInfo info, Context context) to complete authentication. * * @param userId the user id that needs re-authentication if known. For a new user this will be null. * @param session the session that is attempting to launch authentication ui. * @return true if the ui is handled, if false the default authentication ui will be shown to authenticate the user. */ boolean launchAuthUi(String userId, BoxSession session); } /** * Object holding authentication info. */ public static class BoxAuthenticationInfo extends BoxJsonObject { private static final long serialVersionUID = 2878150977399126399L; private static final String FIELD_REFRESH_TIME = "refresh_time"; public static final String FIELD_CLIENT_ID = "client_id"; public static final String FIELD_ACCESS_TOKEN = "access_token"; public static final String FIELD_REFRESH_TOKEN = "refresh_token"; public static final String FIELD_EXPIRES_IN = "expires_in"; public static final String FIELD_USER = "user"; public static final String FIELD_BASE_DOMAIN = "base_domain"; /** * Constructs an empty BoxAuthenticationInfo object. */ public BoxAuthenticationInfo() { super(); } /** * Constructs a BoxAuthenticationInfo with the provided map values. * * @param object JsonObject that represents this object */ public BoxAuthenticationInfo(JsonObject object) { super(object); } /** * Creates a clone of a BoxAuthenticationInfo object. * * @return clone of BoxAuthenticationInfo object. */ public BoxAuthenticationInfo clone() { BoxAuthenticationInfo cloned = new BoxAuthenticationInfo(); cloneInfo(cloned, this); return cloned; } /** * Clone BoxAuthenticationInfo from source object into target object. Note that this method assumes the two objects have same user. * Otherwise it would not make sense to do a clone operation. * @param targetInfo target authentication information to copy information into. * @param sourceInfo source information to copy information from. */ public static void cloneInfo(BoxAuthenticationInfo targetInfo, BoxAuthenticationInfo sourceInfo) { targetInfo.createFromJson(sourceInfo.toJsonObject()); } /** * * @return the box client id associated with this session. */ public String getClientId() { return getPropertyAsString(FIELD_CLIENT_ID); } /** * @return OAuth access token. */ public String accessToken() { return getPropertyAsString(FIELD_ACCESS_TOKEN); } /** * @return OAuth refresh token. */ public String refreshToken() { return getPropertyAsString(FIELD_REFRESH_TOKEN); } /** * @return Time the oauth is going to expire (in ms). */ public Long expiresIn() { return getPropertyAsLong(FIELD_EXPIRES_IN); } /** * * @param expiresIn amount of time in which access token is valid for. */ public void setExpiresIn(Long expiresIn) { set(FIELD_EXPIRES_IN, expiresIn); } /** * Time the OAuth last refreshed. * * @return time the OAuth last refreshed. */ public Long getRefreshTime() { return getPropertyAsLong(FIELD_REFRESH_TIME); } /** * Set the refresh time. Called when refresh happened. * @param refreshTime device system time of last refresh. */ public void setRefreshTime(Long refreshTime) { set(FIELD_REFRESH_TIME, refreshTime); } /** * Setter for client id. * @param clientId client id associated with this authentication. */ public void setClientId(String clientId) { set(FIELD_CLIENT_ID, clientId); } /** * Setter for access token. * @param accessToken access token associated with this authentication */ public void setAccessToken(String accessToken) { set(FIELD_ACCESS_TOKEN, accessToken); } /** * Setter for refresh token * @param refreshToken refresh token associated with this authentication */ public void setRefreshToken(String refreshToken) { set(FIELD_REFRESH_TOKEN, refreshToken); } /** * Setter for base domain. Base domain is no longer being used by any enterprises. * @param baseDomain base domain corresponding to this authentication */ @Deprecated public void setBaseDomain(String baseDomain) { set(FIELD_BASE_DOMAIN, baseDomain); } /** * Base domain is no longer being used by any enterprises. * @return Get the base domain associated with this user. */ @Deprecated public String getBaseDomain() { return getPropertyAsString(FIELD_BASE_DOMAIN); } /** * Setter for BoxUser corresponding to this authentication info. * @param user a box user this authentication corresponds to. */ public void setUser(BoxUser user) { set(FIELD_USER, user); } /** * @return Get the BoxUser related to this authentication info. */ public BoxUser getUser() { return (BoxUser) getPropertyAsJsonObject(BoxEntity.getBoxJsonObjectCreator(), FIELD_USER); } /** * Wipe out all the information in this object. */ public void wipeOutAuth() { remove(FIELD_USER); remove(FIELD_CLIENT_ID); remove(FIELD_ACCESS_TOKEN); remove(FIELD_REFRESH_TOKEN); } public static BoxAuthenticationInfo unmodifiableObject(BoxAuthenticationInfo info){ if (info == null){ return null; } return new BoxImmutableAuthenticationInfo(info); } public static class BoxImmutableAuthenticationInfo extends BoxAuthenticationInfo{ private static final long serialVersionUID = 494874517008319105L; BoxImmutableAuthenticationInfo(BoxAuthenticationInfo info){ super(); super.createFromJson(info.toJsonObject()); } @Override public void setUser(BoxUser user) { BoxLogUtils.e("trying to modify ImmutableBoxAuthenticationInfo", new RuntimeException()); } @Override public void createFromJson(String json) { } @Override public void createFromJson(JsonObject object) { } @Override public void setAccessToken(String accessToken) { BoxLogUtils.e("trying to modify ImmutableBoxAuthenticationInfo", new RuntimeException()); } @Override public void setClientId(String clientId) { BoxLogUtils.e("trying to modify ImmutableBoxAuthenticationInfo", new RuntimeException()); } @Override public void setExpiresIn(Long expiresIn) { BoxLogUtils.e("trying to modify ImmutableBoxAuthenticationInfo", new RuntimeException()); } @Override public void setRefreshTime(Long refreshTime) { BoxLogUtils.e("trying to modify ImmutableBoxAuthenticationInfo", new RuntimeException()); } @Override public void setRefreshToken(String refreshToken) { BoxLogUtils.e("trying to modify ImmutableBoxAuthenticationInfo", new RuntimeException()); } @Override public void setBaseDomain(String baseDomain) { BoxLogUtils.e("trying to modify ImmutableBoxAuthenticationInfo", new RuntimeException()); } @Override public void wipeOutAuth() { BoxLogUtils.e("trying to modify ImmutableBoxAuthenticationInfo", new RuntimeException()); } } } /** * Storage class to store auth info. Note this class uses shared pref as storage. You can extend this class and use your own * preferred storage and call setAuthStorage() method in BoxAuthentication class to use your own storage. */ public static class AuthStorage { private static final String AUTH_STORAGE_NAME = AuthStorage.class.getCanonicalName() + "_SharedPref"; private static final String AUTH_MAP_STORAGE_KEY = AuthStorage.class.getCanonicalName() + "_authInfoMap"; private static final String AUTH_STORAGE_LAST_AUTH_USER_ID_KEY = AuthStorage.class.getCanonicalName() + "_lastAuthUserId"; /** * Store the auth info into storage. * * @param authInfo auth info to store. * @param context context here is only used to load shared pref. In case you don't need shared pref, you can ignore this * argument in your implementation. */ protected void storeAuthInfoMap(Map<String, BoxAuthenticationInfo> authInfo, Context context) { JsonObject jsonObject = new JsonObject(); for (Map.Entry<String, BoxAuthenticationInfo> entry : authInfo.entrySet()){ jsonObject.add(entry.getKey(), entry.getValue().toJsonObject()); } BoxEntity infoMapObj = new BoxEntity(jsonObject); context.getSharedPreferences(AUTH_STORAGE_NAME, Context.MODE_PRIVATE).edit().putString(AUTH_MAP_STORAGE_KEY, infoMapObj.toJson()).commit(); } /** * Removes auth info from storage. * * @param context context here is only used to load shared pref. In case you don't need shared pref, you can ignore this * argument in your implementation. */ protected void clearAuthInfoMap(Context context) { context.getSharedPreferences(AUTH_STORAGE_NAME, Context.MODE_PRIVATE).edit().remove(AUTH_MAP_STORAGE_KEY).commit(); } /** * Store out the last user id that the user authenticated as. This will be the one that is restored if no user is specified for a BoxSession. * * @param userId user id of the last authenticated user. null if this data should be removed. * @param context context here is only used to load shared pref. In case you don't need shared pref, you can ignore this * argument in your implementation. */ protected void storeLastAuthenticatedUserId(String userId, Context context) { if (SdkUtils.isEmptyString(userId)) { context.getSharedPreferences(AUTH_STORAGE_NAME, Context.MODE_PRIVATE).edit().remove(AUTH_STORAGE_LAST_AUTH_USER_ID_KEY).commit(); } else { context.getSharedPreferences(AUTH_STORAGE_NAME, Context.MODE_PRIVATE).edit().putString(AUTH_STORAGE_LAST_AUTH_USER_ID_KEY, userId).commit(); } } /** * Return the last user id associated with the last authentication. * * @param context context here is only used to load shared pref. In case you don't need shared pref, you can ignore this * argument in your implementation. * @return the user id of the last authenticated user or null if not stored or the user has since been logged out. */ protected String getLastAuthentictedUserId(Context context) { return context.getSharedPreferences(AUTH_STORAGE_NAME, Context.MODE_PRIVATE).getString(AUTH_STORAGE_LAST_AUTH_USER_ID_KEY, null); } /** * Load auth info from storage. * * @param context context here is only used to load shared pref. In case you don't need shared pref, you can ignore this * argument in your implementation. * @return a map of all known user authentication information with keys being userId. */ protected ConcurrentHashMap<String, BoxAuthenticationInfo> loadAuthInfoMap(Context context) { ConcurrentHashMap<String, BoxAuthenticationInfo> map = new ConcurrentHashMap<>(); String json = context.getSharedPreferences(AUTH_STORAGE_NAME, 0).getString(AUTH_MAP_STORAGE_KEY, ""); if (json.length() > 0) { BoxEntity obj = new BoxEntity(); obj.createFromJson(json); for (String key: obj.getPropertiesKeySet()) { JsonValue value = obj.getPropertyValue(key); BoxAuthenticationInfo info = null; if (value.isString()) { info = new BoxAuthenticationInfo(); info.createFromJson(value.asString()); } else if (value.isObject()){ info = new BoxAuthenticationInfo(); info.createFromJson(value.asObject()); } map.put(key, info); } } return map; } } /** * A check to see if an official box application supporting third party authentication is available. * This lets users authenticate without re-entering credentials. * * @param context current context * @return true if an official box application that supports third party authentication is installed. */ public static boolean isBoxAuthAppAvailable(final Context context) { Intent intent = new Intent(BoxConstants.REQUEST_BOX_APP_FOR_AUTH_INTENT_ACTION); List<ResolveInfo> infos = context.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY | PackageManager.GET_RESOLVED_FILTER); return infos.size() > 0; } }
package org.browsexml.timesheetjob.web; import java.text.NumberFormat; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.browsexml.timesheetjob.model.Constants; import org.browsexml.timesheetjob.model.FulltimeAgreements; import org.browsexml.timesheetjob.model.Job; import org.browsexml.timesheetjob.model.People; import org.browsexml.timesheetjob.service.FulltimeAgreementManager; import org.browsexml.timesheetjob.service.JobManager; import org.browsexml.timesheetjob.service.PeopleManager; import org.browsexml.timesheetjob.web.FulltimeController.FulltimeBacking; import org.hibernate.PropertyValueException; import org.springframework.beans.propertyeditors.CustomNumberEditor; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.validation.BindException; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.SimpleFormController; public class FulltimeFormController extends SimpleFormController { private static Log log = LogFactory.getLog(FulltimeFormController.class); private FulltimeAgreementManager fulltimeMgr = null; private PeopleManager mgr = null; private JobManager jobMgr = null; public void setJobManager(JobManager jobMgr) { this.jobMgr = jobMgr; } public void setPeopleManager(PeopleManager peopleManager) { this.mgr = peopleManager; } public void setFulltimeAgreementManager(FulltimeAgreementManager fulltimeMgr) { this.fulltimeMgr = fulltimeMgr; } public FulltimeFormController() { super(); } protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) { NumberFormat nf = NumberFormat.getNumberInstance(); binder.registerCustomEditor(Integer.class, new CustomNumberEditor(Integer.class, nf, true)); binder.registerCustomEditor(int.class, new PennyEditor()); binder.registerCustomEditor(Job.class, new JobPropertyEditor(jobMgr)); } protected Object formBackingObject(HttpServletRequest request) throws ServletException { FulltimeFormBacking command = (FulltimeFormBacking) new FulltimeFormBacking(); Set<Map.Entry> entries = (Set) request.getParameterMap().entrySet(); log.debug("request..."); for (Map.Entry m:entries) { Object key = m.getKey(); Object[] value = (Object[])m.getValue(); log.debug("REQUEST KEY: " + key + " = " + value[0]); } command.setBtnSearch(request.getParameter("btnSearch")); String id = request.getParameter("id"); log.debug("form backing id = " + id); String peopleId = request.getParameter("peopleId"); command.setPeopleId(peopleId); if (id == null || id.trim().equals("")) { log.debug("peopleId = " + peopleId); People person = mgr.getPersonProperties(peopleId); log.debug("Person = " + Constants.toReflexString(person)); FulltimeAgreements agreements = new FulltimeAgreements(null, person, null, true, 0, 0); log.debug("agreements = " + Constants.toReflexString(agreements)); command.setAgreements(agreements); } else { FulltimeAgreements f = fulltimeMgr.getFulltimeAgreement(id); command.setAgreements(f); } return command; } public ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { FulltimeBacking backing = (FulltimeBacking) request.getSession().getAttribute("fulltime"); if (request.getParameter("cancel") != null) { return new ModelAndView(getSuccessView(), "fulltimeBacking", backing); } return super.processFormSubmission(request, response, command, errors); } public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { System.err.println("ON SUBMIT"); if (log.isDebugEnabled()) log.debug("entering 'onSubmit' method..."); FulltimeFormBacking backing = (FulltimeFormBacking) command; FulltimeAgreements agreements = backing.getAgreements(); Job job = agreements.getJob(); FulltimeBacking listBacking = (FulltimeBacking) request.getSession().getAttribute("fulltime"); if (backing.getBtnSearch() != null) { String search = request.getParameter("search"); String sort = request.getParameter("sort"); backing.setJobList(jobMgr.getJobs(search, sort)); return showForm(request, response, errors); } else if (backing.getDelete() != null) { try { fulltimeMgr.removeFulltimeAgreement("" + agreements.getId()); request.getSession().setAttribute("message", getMessageSourceAccessor().getMessage("job.deleted", new Object[]{job.getDepartment() + " " + job.getDescription()})); } catch (Exception e) { errors.rejectValue("agreements.job", "fulltime.alreadyPunched"); return showForm(request, response, errors); } } else if (request.getParameter("save") != null) { try { if (agreements.getPeople() == null) { mgr.save(listBacking.getProperties()); agreements.setPeople(listBacking.getProperties()); } fulltimeMgr.saveFulltimeAgreement(agreements); } catch (DataIntegrityViolationException pe) { if (pe.getMessage().indexOf("govern") > 0) { errors.rejectValue("agreements.job", "fulltime.missingSSN"); } else { errors.rejectValue("agreements.job", "fulltime.missingRequiredField"); } return showForm(request, response, errors); } catch (PropertyValueException pve) { pve.printStackTrace(); String department = "[Unset]"; if (job != null) department = job.getDepartment(); if (pve.getMessage().contains("PeopleProperties")) { errors.rejectValue("agreements.job", "job.invalidPerson", new Object[] {backing.getPeopleId()}, "Invalid person"); return showForm(request, response, errors); } errors.rejectValue("agreements.job", "job.saveInvalidJob", new Object[] {department}, "Invalid job"); return showForm(request, response, errors); } catch (Exception e) { e.printStackTrace(); errors.rejectValue("agreements.job", "job.saveUniqueConstraintError", new Object[] {backing.getPeopleId(), job.getDepartment()}, "Already assigned to job"); return showForm(request, response, errors); } request.getSession().setAttribute("message", getMessageSourceAccessor().getMessage("job.saved", new Object[]{job.getDepartment() + " " + job.getDescription()})); } log.debug("listBacking = " + listBacking); log.debug("listBacking.getPersopn = " + listBacking.getPerson()); listBacking.setFulltimeAgreements(mgr.getFulltimeAgreements( listBacking.getPerson().getPeopleId())); listBacking.setStudentAgreements(mgr.getStudentAgreements( listBacking.getPerson().getPeopleId())); return new ModelAndView(getSuccessView(), "fulltimeBacking", listBacking); } public static class FulltimeControllerFormValidator implements Validator { private static Log log = LogFactory.getLog(FulltimeControllerFormValidator.class); @Override public boolean supports(Class theClass) { return FulltimeFormBacking.class.equals(theClass); } @Override public void validate(Object obj, Errors errors) { FulltimeFormBacking fulltime = (FulltimeFormBacking) obj; if (fulltime.getBtnSearch() != null) { log.debug("DONT VALID SEARCH"); return; } if (fulltime.getDelete() != null) { log.debug("DONT VALID DELETE"); return; } log.debug("VALIDATE"); String rate = "" + errors.getFieldValue("agreements.rate"); if (Constants.MIN_WAGE > Constants.unformatPennies(rate)) { errors.rejectValue("agreements.rate", "fulltime.badMoneyValue"); } String overtime = "" + errors.getFieldValue("agreements.overtime"); if (Constants.MIN_WAGE > Constants.unformatPennies(overtime)) { errors.rejectValue("agreements.overtime", "fulltime.badMoneyValue"); } } } public static class FulltimeFormBacking extends org.browsexml.timesheetjob.model.BaseObject { FulltimeAgreements agreements; List<Job> jobList = null; Integer id = null; String peopleId = null; String delete = null; String search = null; public FulltimeAgreements getAgreements() { return agreements; } public void setAgreements(FulltimeAgreements agreements) { this.agreements = agreements; } public List<Job> getJobList() { return jobList; } public void setJobList(List<Job> jobList) { for (Job j: jobList) { log.debug("setting list " + j.getDescription()); } this.jobList = jobList; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPeopleId() { return peopleId; } public void setPeopleId(String peopleId) { this.peopleId = peopleId; } public String getDelete() { return delete; } public void setDelete(String delete) { this.delete = delete; } public String getBtnSearch() { return search; } public void setBtnSearch(String search) { this.search = search; } } }
package kr.or.ddit.basic; public class ThreadTest19 { /* * wait()메서드와 notify()메서드를 이용하여 두 thread가 번갈아 한 번씩 실행되는 예제 * -> wait(), notify(), notifyAll()메서드는 동기화 영역에서만 사용 가능하다. */ public static void main(String[] args) { WorkObject workObj = new WorkObject(); ThreadA th1 = new ThreadA(workObj); ThreadB th2 = new ThreadB(workObj); th1.start(); th2.start(); } } //공통으로 사용할 객체 class WorkObject{ public synchronized void testMethod1(){ System.out.println("testMethod1()메서드에서 실행 중"); notify(); try { wait(); } catch (InterruptedException e) { } } public synchronized void testMethod2(){ System.out.println("testMethod2()메서드에서 실행 중"); notify(); try { wait(); } catch (InterruptedException e) { } } } //WorkObject의 testMethod1()메서드만 호출하는 thread class ThreadA extends Thread{ private WorkObject workObj; public ThreadA(WorkObject workObj) { this.workObj = workObj; } @Override public void run() { for(int i = 1; i <= 10; i++){ workObj.testMethod1(); } synchronized (workObj) { workObj.notify(); } } } //WorkObject의 testMethod2()메서드만 호출하는 thread class ThreadB extends Thread{ private WorkObject workObj; public ThreadB(WorkObject workObj) { this.workObj = workObj; } @Override public void run() { for(int i = 1; i <= 10; i++){ workObj.testMethod2(); } synchronized (workObj) { workObj.notify(); } } }
package com.website.views.pages; import java.io.Serializable; import java.util.List; import javax.faces.view.ViewScoped; import javax.inject.Inject; import javax.inject.Named; import com.website.managers.email.EmailList; import com.website.models.entities.Event; import com.website.models.entities.Guest; import com.website.persistence.EventService; import com.website.persistence.GuestService; import com.website.tools.error.HttpErrorHandler; import com.website.tools.navigation.SessionManager; import com.website.views.WebPages; /** * The event management web page view.</br> * This {@link Named} class is bound with the same named xhtml file. * * @author Jérémy Pansier */ @Named @ViewScoped public class EventManagement implements Serializable { /** The serial version UID. */ private static final long serialVersionUID = 5873143732364895613L; /** The web page. */ public static final WebPages WEB_PAGE = WebPages.EVENT_MANAGEMENT; /** The service managing the event persistence. */ @Inject private EventService eventService; /** The service managing the guest persistence. */ @Inject private GuestService guestService; /** The event id HTTP request parameter. */ private Long id; /** The event to manage. */ private transient Event event; /** The event guests. */ private transient List<Guest> guests; /** The e-mails to be sent to guests. */ @EmailList private String emails; /** * Sets fields values on the web page loading, depending on the HTTP request parameter: * <ul> * <li>Sets the event.</li> * <li>Sets the guests.</li> * </ul> */ public void load() { try { final String username = SessionManager.getSessionUserNameOrRedirect(); if (!eventService.isEventsAuthor(id, username)) { return; } event = eventService.findEventByEventId(id); guests = guestService.findGuestsByEventId(id); } catch (final IllegalStateException illegalStateException) { HttpErrorHandler.print500("forward impossible", illegalStateException); return; } } /** * Gets the web page. * * @return the web page */ public WebPages getWebPage() { return WEB_PAGE; } /** * Gets the event id HTTP request parameter. * * @return the event id HTTP request parameter */ public Long getId() { return id; } /** * Sets the event id HTTP request parameter. * * @param id the event id HTTP request parameter */ public void setId(final Long id) { this.id = id; } /** * Gets the event to manage. * * @return the event to manage */ public Event getEvent() { return event; } /** * Gets the event guests. * * @return the event guests */ public List<Guest> getGuests() { return guests; } /** * Gets the e-mails to be sent to guests. * * @return the e-mails to be sent to guests */ public String getEmails() { return emails; } /** * Sets the e-mails to be sent to guests. * * @param emailList the e-mails to be sent to guests */ public void setEmails(final String emailList) { this.emails = emailList; } /** * Adds guests to the event. */ public void addGuests() { try { final String username = SessionManager.getSessionUserNameOrRedirect(); if (!eventService.isEventsAuthor(id, username)) { return; } event = eventService.findEventByEventId(id); if (emails == null || emails.trim().isEmpty()) { return; } for (final String email : emails.split(";")) { guestService.persistGuest(event, email); } guests = guestService.findGuestsByEventId(id); } catch (final NumberFormatException numberFormatException) { HttpErrorHandler.print404("Le parametre de la requete http ne peut pas etre converti en Integer dans le doPost de EventLinkServlet", numberFormatException); return; } } /** * Removes the given guest from the event. * * @param guest the guest to remove from the event */ public void removeGuest(final Guest guest) { guestService.removeGuest(guest); guests = guestService.findGuestsByEventId(id); } }
package la.opi.verificacionciudadana.models; import java.util.ArrayList; /** * Created by Jhordan on 24/02/15. */ public class State { private String id; private String name; private ArrayList<String> town; private ArrayList<Town> townArrayList; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public ArrayList<String> getTown() { return town; } public void setTown(ArrayList<String> town) { this.town = town; } public ArrayList<Town> getTownArrayList() { return townArrayList; } public void setTownArrayList(ArrayList<Town> townArrayList) { this.townArrayList = townArrayList; } }
package com.spbsu.flamestream.runtime.sum; import com.spbsu.flamestream.core.graph.SerializableFunction; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; final class IdentityEnricher implements SerializableFunction<List<Numb>, Stream<List<Numb>>> { @Override public Stream<List<Numb>> apply(List<Numb> numberGroupingResult) { if (numberGroupingResult.size() == 1) { final List<Numb> group = new ArrayList<>(); group.add(new Sum(0)); group.add(numberGroupingResult.get(0)); return Stream.of(group); } else { return Stream.of(numberGroupingResult); } } }
package br.com.tomioka.vendashortalicas.dto; import br.com.tomioka.vendashortalicas.models.Produto; import java.math.BigDecimal; public class ProdutoDto { private String nome; private BigDecimal preco; public ProdutoDto(String nome, BigDecimal preco) { this.nome = nome; this.preco = preco; } public Produto converte() { return new Produto(nome, preco); } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public BigDecimal getPreco() { return preco; } public void setPreco(BigDecimal preco) { this.preco = preco; } }
/* * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.test.lib.apps; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.StringReader; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.UUID; import jdk.test.lib.process.OutputBuffer; import jdk.test.lib.process.StreamPumper; /** * This is a framework to launch an app that could be synchronized with caller * to make further attach actions reliable across supported platforms * Caller example: * SmartTestApp a = SmartTestApp.startApp(cmd); * // do something * a.stopApp(); * * or fine grained control * * a = new SmartTestApp("MyLock.lck"); * a.createLock(); * a.runApp(); * a.waitAppReady(); * // do something * a.deleteLock(); * a.waitAppTerminate(); * * Then you can work with app output and process object * * output = a.getAppOutput(); * process = a.getProcess(); * */ public class LingeredApp { private static final long spinDelay = 1000; private long lockCreationTime; private ByteArrayOutputStream stderrBuffer; private ByteArrayOutputStream stdoutBuffer; private Thread outPumperThread; private Thread errPumperThread; protected Process appProcess; protected OutputBuffer output; protected static final int appWaitTime = 100; protected final String lockFileName; /** * Create LingeredApp object on caller side. Lock file have be a valid filename * at writable location * * @param lockFileName - the name of lock file */ public LingeredApp(String lockFileName) { this.lockFileName = lockFileName; } public LingeredApp() { final String lockName = UUID.randomUUID().toString() + ".lck"; this.lockFileName = lockName; } /** * * @return name of lock file */ public String getLockFileName() { return this.lockFileName; } /** * * @return name of testapp */ public String getAppName() { return this.getClass().getName(); } /** * * @return pid of java process running testapp */ public long getPid() { if (appProcess == null) { throw new RuntimeException("Process is not alive"); } return appProcess.pid(); } /** * * @return process object */ public Process getProcess() { return appProcess; } /** * @return the LingeredApp's output. * Can be called after the app is run. */ public String getProcessStdout() { return stdoutBuffer.toString(); } /** * * @return OutputBuffer object for the LingeredApp's output. Can only be called * after LingeredApp has exited. */ public OutputBuffer getOutput() { if (appProcess.isAlive()) { throw new RuntimeException("Process is still alive. Can't get its output."); } if (output == null) { output = OutputBuffer.of(stdoutBuffer.toString(), stderrBuffer.toString()); } return output; } /* * Capture all stdout and stderr output from the LingeredApp so it can be returned * to the driver app later. This code is modeled after ProcessTools.getOutput(). */ private void startOutputPumpers() { stderrBuffer = new ByteArrayOutputStream(); stdoutBuffer = new ByteArrayOutputStream(); StreamPumper outPumper = new StreamPumper(appProcess.getInputStream(), stdoutBuffer); StreamPumper errPumper = new StreamPumper(appProcess.getErrorStream(), stderrBuffer); outPumperThread = new Thread(outPumper); errPumperThread = new Thread(errPumper); outPumperThread.setDaemon(true); errPumperThread.setDaemon(true); outPumperThread.start(); errPumperThread.start(); } /** * * @return application output as List. Empty List if application produced no output */ public List<String> getAppOutput() { if (appProcess.isAlive()) { throw new RuntimeException("Process is still alive. Can't get its output."); } BufferedReader bufReader = new BufferedReader(new StringReader(output.getStdout())); return bufReader.lines().collect(Collectors.toList()); } /* Make sure all part of the app use the same method to get dates, as different methods could produce different results */ private static long epoch() { return new Date().getTime(); } private static long lastModified(String fileName) throws IOException { Path path = Paths.get(fileName); BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class); return attr.lastModifiedTime().toMillis(); } private static void setLastModified(String fileName, long newTime) throws IOException { Path path = Paths.get(fileName); FileTime fileTime = FileTime.fromMillis(newTime); Files.setLastModifiedTime(path, fileTime); } /** * create lock * * @throws IOException */ public void createLock() throws IOException { Path path = Paths.get(lockFileName); // Files.deleteIfExists(path); Files.createFile(path); lockCreationTime = lastModified(lockFileName); } /** * Delete lock * * @throws IOException */ public void deleteLock() throws IOException { try { Path path = Paths.get(lockFileName); Files.delete(path); } catch (NoSuchFileException ex) { // Lock already deleted. Ignore error } } public void waitAppTerminate() { // This code is modeled after tail end of ProcessTools.getOutput(). try { appProcess.waitFor(); outPumperThread.join(); errPumperThread.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // pass } } /** * The app touches the lock file when it's started * wait while it happens. Caller have to delete lock on wait error. * * @param timeout * @throws java.io.IOException */ public void waitAppReady(long timeout) throws IOException { long here = epoch(); while (true) { long epoch = epoch(); if (epoch - here > (timeout * 1000)) { throw new IOException("App waiting timeout"); } // Live process should touch lock file every second long lm = lastModified(lockFileName); if (lm > lockCreationTime) { break; } // Make sure process didn't already exit if (!appProcess.isAlive()) { throw new IOException("App exited unexpectedly with " + appProcess.exitValue()); } try { Thread.sleep(spinDelay); } catch (InterruptedException ex) { // pass } } } /** * Analyze an environment and prepare a command line to * run the app, app name should be added explicitly */ public List<String> runAppPrepare(List<String> vmArguments) { // We should always use testjava or throw an exception, // so we can't use JDKToolFinder.getJDKTool("java"); // that falls back to compile java on error String jdkPath = System.getProperty("test.jdk"); if (jdkPath == null) { // we are not under jtreg, try env Map<String, String> env = System.getenv(); jdkPath = env.get("TESTJAVA"); } if (jdkPath == null) { throw new RuntimeException("Can't determine jdk path neither test.jdk property no TESTJAVA env are set"); } String osname = System.getProperty("os.name"); String javapath = jdkPath + ((osname.startsWith("window")) ? "/bin/java.exe" : "/bin/java"); List<String> cmd = new ArrayList<String>(); cmd.add(javapath); if (vmArguments == null) { // Propagate test.vm.options to LingeredApp, filter out possible empty options String testVmOpts[] = System.getProperty("test.vm.opts","").split("\\s+"); for (String s : testVmOpts) { if (!s.equals("")) { cmd.add(s); } } } else { // Lets user manage LingeredApp options cmd.addAll(vmArguments); } // Make sure we set correct classpath to run the app cmd.add("-cp"); String classpath = System.getProperty("test.class.path"); cmd.add((classpath == null) ? "." : classpath); return cmd; } /** * Assemble command line to a printable string */ public void printCommandLine(List<String> cmd) { // A bit of verbosity StringBuilder cmdLine = new StringBuilder(); for (String strCmd : cmd) { cmdLine.append("'").append(strCmd).append("' "); } System.err.println("Command line: [" + cmdLine.toString() + "]"); } /** * Run the app. * * @param vmArguments * @throws IOException */ public void runApp(List<String> vmArguments) throws IOException { List<String> cmd = runAppPrepare(vmArguments); cmd.add(this.getAppName()); cmd.add(lockFileName); printCommandLine(cmd); ProcessBuilder pb = new ProcessBuilder(cmd); // ProcessBuilder.start can throw IOException appProcess = pb.start(); startOutputPumpers(); } private void finishApp() { OutputBuffer output = getOutput(); String msg = " LingeredApp stdout: [" + output.getStdout() + "];\n" + " LingeredApp stderr: [" + output.getStderr() + "]\n" + " LingeredApp exitValue = " + appProcess.exitValue(); System.err.println(msg); } /** * Delete lock file that signals app to terminate, then * wait until app is actually terminated. * @throws IOException */ public void stopApp() throws IOException { deleteLock(); // The startApp() of the derived app can throw // an exception before the LA actually starts if (appProcess != null) { waitAppTerminate(); int exitcode = appProcess.exitValue(); if (exitcode != 0) { throw new IOException("LingeredApp terminated with non-zero exit code " + exitcode); } } finishApp(); } /** * High level interface for test writers */ /** * Factory method that creates LingeredApp object with ready to use application * lock name is autogenerated * @param cmd - vm options, could be null to auto add testvm.options * @return LingeredApp object * @throws IOException */ public static LingeredApp startApp(List<String> cmd) throws IOException { LingeredApp a = new LingeredApp(); a.createLock(); try { a.runApp(cmd); a.waitAppReady(appWaitTime); } catch (Exception ex) { a.deleteLock(); System.err.println("LingeredApp failed to start: " + ex); a.finishApp(); throw ex; } return a; } /** * Factory method that starts pre-created LingeredApp * lock name is autogenerated * @param cmd - vm options, could be null to auto add testvm.options * @param theApp - app to start * @return LingeredApp object * @throws IOException */ public static void startApp(List<String> cmd, LingeredApp theApp) throws IOException { theApp.createLock(); try { theApp.runApp(cmd); theApp.waitAppReady(appWaitTime); } catch (Exception ex) { theApp.deleteLock(); throw ex; } } public static LingeredApp startApp() throws IOException { return startApp(null); } public static void stopApp(LingeredApp app) throws IOException { if (app != null) { // LingeredApp can throw an exception during the intialization, // make sure we don't have cascade NPE app.stopApp(); } } /** * LastModified time might not work correctly in some cases it might * cause later failures */ public static boolean isLastModifiedWorking() { boolean sane = true; try { long lm = lastModified("."); if (lm == 0) { System.err.println("SANITY Warning! The lastModifiedTime() doesn't work on this system, it returns 0"); sane = false; } long now = epoch(); if (lm > now) { System.err.println("SANITY Warning! The Clock is wrong on this system lastModifiedTime() > getTime()"); sane = false; } setLastModified(".", epoch()); long lm1 = lastModified("."); if (lm1 <= lm) { System.err.println("SANITY Warning! The setLastModified doesn't work on this system"); sane = false; } } catch(IOException e) { System.err.println("SANITY Warning! IOException during sanity check " + e); sane = false; } return sane; } /** * This part is the application it self */ public static void main(String args[]) { if (args.length != 1) { System.err.println("Lock file name is not specified"); System.exit(7); } String theLockFileName = args[0]; Path path = Paths.get(theLockFileName); try { while (Files.exists(path)) { // Touch the lock to indicate our readiness setLastModified(theLockFileName, epoch()); Thread.sleep(spinDelay); } } catch (IOException ex) { // Lock deleted while we are setting last modified time. // Ignore the error and let the app exit. if (Files.exists(path)) { // If the lock file was not removed, return an error. System.err.println("LingeredApp IOException: lock file still exists"); System.exit(4); } } catch (Exception ex) { System.err.println("LingeredApp ERROR: " + ex); // Leave exit_code = 1 to Java launcher System.exit(3); } System.exit(0); } }
package escriturauno; // Uso de la clase Formatter para escribir datos en un archivo de texto. import java.util.Formatter; public class CrearArchivoTexto { // agrega registros al archivo public static void agregarRegistros(String valor) { try { Formatter salida = new Formatter("data/salidaDatosPersonales.txt"); salida.format("%s\n", valor); salida.close(); } catch (Exception e) { System.err.println("Error al crear el archivo."); System.exit(1); } } // fin método agregarRegistros } // fin de la clase CrearArchivoTexto /************************************************************************** * (C) Copyright 1992-2007 por Deitel & Associates, Inc. y * * Pearson Education, Inc. Todos los derechos reservados. * * * * RENUNCIA: Los autores y el editor de este libro han realizado su mejor * * esfuerzo para preparar este libro. Esto incluye el desarrollo, la * * investigaci�n y prueba de las teor�as y programas para determinar su * * efectividad. Los autores y el editor no hacen ninguna garant�a de * * ning�n tipo, expresa o impl�cita, en relaci�n con estos programas o * * con la documentaci�n contenida en estos libros. Los autores y el * * editor no ser�n responsables en ning�n caso por los da�os consecuentes * * en conexi�n con, o que surjan de, el suministro, desempe�o o uso de * * estos programas. * *************************************************************************/
package utility.model.SchemaParser.enums; public enum TypeEnum { Nvarchar, Number }
package edu.northeastern.cs5200.daos; import edu.northeastern.cs5200.Connection; import edu.northeastern.cs5200.model.Phone; import java.sql.*; public class PhoneDao implements PhoneImpl { java.sql.Connection connection = null; private PreparedStatement preparedStatement1 = null; private ResultSet resultSet = null; public static PhoneDao instance = null; public static PhoneDao getInstance(){ if (instance==null){ instance=new PhoneDao(); } return instance; } private PhoneDao() { } @Override public void addPhone(int personId, Phone phone) { try { connection = Connection.getConnection(); String putPhone = "INSERT INTO phone(phone,`primary`,personid) VALUES(?,?,?)"; preparedStatement1 = connection.prepareStatement(putPhone); preparedStatement1.setString(1, phone.getPhone()); preparedStatement1.setBoolean(2, phone.getPrimary()); preparedStatement1.setInt(3, personId); int res= preparedStatement1.executeUpdate(); } catch(ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { try { preparedStatement1.close(); Connection.closeConnection(connection); } catch(SQLException e) { e.printStackTrace(); } } } @Override public void updatePrimaryPhone(int personId, Phone phone) { try { connection = Connection.getConnection(); String updatePhone = "UPDATE phone SET phone=? where `primary`=? and personid=?"; preparedStatement1 = connection.prepareStatement(updatePhone); preparedStatement1.setString(1, phone.getPhone()); preparedStatement1.setBoolean(2, true); preparedStatement1.setInt(3, personId); int res = preparedStatement1.executeUpdate(); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { try { preparedStatement1.close(); Connection.closeConnection(connection); } catch (SQLException e) { e.printStackTrace(); } } } @Override public void deletePrimaryPhone(int personId, Phone phone) { try { connection = Connection.getConnection(); String deletePhone = "DELETE FROM phone where `primary`=? and personid=?"; preparedStatement1 = connection.prepareStatement(deletePhone); preparedStatement1.setBoolean(1, true); preparedStatement1.setInt(2, personId); int res= preparedStatement1.executeUpdate(); } catch(ClassNotFoundException | SQLException e) { e.printStackTrace(); } finally { try { preparedStatement1.close(); Connection.closeConnection(connection); } catch(SQLException e) { e.printStackTrace(); } } } }
package edu.wisc.jmeter.dao; import java.util.Date; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; import edu.wisc.jmeter.HostStatus; import edu.wisc.jmeter.Notification; import edu.wisc.jmeter.Status; /** * Wraps another {@link MonitorDao} logging all exceptions * * @author Eric Dalquist */ public class ErrorHandlingMonitorDao implements MonitorDao { private static final Logger log = LoggingManager.getLoggerForClass(); private final MonitorDao monitorDao; public ErrorHandlingMonitorDao(MonitorDao monitorDao) { this.monitorDao = monitorDao; } @Override public void purgeStatusCache(Date before) { try { this.monitorDao.purgeStatusCache(before); } catch (RuntimeException re) { log.warn("Failed to purge status cache", re); } } @Override public void purgeRequestLog(String host, Date before) { try { this.monitorDao.purgeRequestLog(host, before); } catch (RuntimeException re) { log.warn("Failed to purge request log database", re); } } @Override public void purgeRequestLog(Date before) { try { this.monitorDao.purgeRequestLog(before); } catch (RuntimeException re) { log.warn("Failed to purge request log database", re); } } @Override public void purgeFailureLog(Date before) { try { this.monitorDao.purgeFailureLog(before); } catch (RuntimeException re) { log.warn("Failed to purge failure log database", re); } } @Override public HostStatus getHostStatus(String hostName) { try { return this.monitorDao.getHostStatus(hostName); } catch (RuntimeException re) { //Want things to still work if the database is broken so create an empty HostStatus to work with in memory only final HostStatus hostStatus = new HostStatus(); hostStatus.setHost(hostName); hostStatus.setLastUpdated(new Date()); log.warn("Failed to retrieve/create HostStatus via database, using memory storage only", re); return hostStatus; } } @Override public void storeHostStatus(HostStatus hostStatus) { try { this.monitorDao.storeHostStatus(hostStatus); } catch (RuntimeException re) { log.warn("Failed to persist HostStatus via database, using memory storage only", re); } } @Override public void logFailure(String hostName, String label, Date requestTimestamp, Status status, String subject, String body, Notification sentEmail) { try { this.monitorDao.logFailure(hostName, label, requestTimestamp, status, subject, body, sentEmail); } catch (RuntimeException re) { log.warn("Failed to log failure to database", re); } } @Override public void logRequest(String hostName, String label, Date requestTimestamp, long duration, boolean successful) { try { this.monitorDao.logRequest(hostName, label, requestTimestamp, duration, successful); } catch (RuntimeException re) { log.warn("Failed to log request to database", re); } } @Override public void logRequestAndStatus(HostStatus hostStatus, String label, Date requestTimestamp, long duration, boolean successful) { try { this.monitorDao.logRequestAndStatus(hostStatus, label, requestTimestamp, duration, successful); } catch (RuntimeException re) { log.warn("Failed to log request and store status to database", re); } } @Override public void logFailureAndStatus(HostStatus hostStatus, String label, Date requestTimestamp, Status status, String subject, String body, Notification sentEmail) { try { this.monitorDao.logFailureAndStatus(hostStatus, label, requestTimestamp, status, subject, body, sentEmail); } catch (RuntimeException re) { log.warn("Failed to log request and store failure status to database", re); } } }
import java.util.ArrayList; import java.util.StringTokenizer; public class BackEnd extends Main { static ArrayList<Integer> indices = new ArrayList<Integer>(); public static void start() { StringTokenizer st = new StringTokenizer(sbDP.toString().replaceAll("\\s", " ")); sbBE.append('\n').append("PATH:").append('\n'); while(true) { int I = Integer.parseInt(st.nextToken()); if(I == 0) break; String C = st.nextToken(); if(C.equals("T")) indices.add(I); } for(int i=0; i<steps; i++) { sbBE.append(look.get(indices.get(i)-1)).append('\n'); } } }
import java.util.ArrayList; public class Kasse { private String name; private int sollBestand; private int istBestand; private ArrayList<Topf> töpfe = new ArrayList<>(); private String art; Kasse(String aName){ this.name = aName; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getSollBestand() { return sollBestand; } public void setSollBestand(int sollBestand) { this.sollBestand = sollBestand; } public int getIstBestand() { return istBestand; } public void setIstBestand(int istBestand) { this.istBestand = istBestand; } public ArrayList<Topf> getTöpfe() { return töpfe; } public void setTöpfe(ArrayList<Topf> töpfe) { this.töpfe = töpfe; } public String getArt() { return art; } public void setArt(String art) { this.art = art; } }
package com.tencent.mm.plugin.card.ui; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; class CardShopUI$2 implements OnMenuItemClickListener { final /* synthetic */ CardShopUI hGu; CardShopUI$2(CardShopUI cardShopUI) { this.hGu = cardShopUI; } public final boolean onMenuItemClick(MenuItem menuItem) { this.hGu.finish(); return true; } }
package com.ismail.hutbro; import org.glassfish.jersey.server.ResourceConfig; import org.springframework.context.annotation.Configuration; import com.ismail.hutbro.controller.Index; import com.ismail.hutbro.controller.ProductController; @Configuration public class JerseyConfig extends ResourceConfig { public JerseyConfig() { register(Index.class); register(ProductController.class); register(CORSResponseFilter.class); } }
package babylanguage.babyapp.appscommon.languages; public enum LanguageType { en, he, ru, es }
package com.phone1000.martialstudyself.interfaces; /** * Created by 马金利 on 2016/12/2. */ public interface ParentItemClickListener { void itemClickListener(int id); }
public class PrintTest1{ public static void main(String[] args) { System.out.print("My favorite number is"); System.out.println(1+2+3); } }
package com.orca.app; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.orca.domain.Community; import com.orca.domain.Documentation; import com.orca.domain.Evaluation; import com.orca.domain.Survey; import com.orca.factory.EvaluationFactory; @ContextConfiguration( locations = { "/root-context.xml", "/controllers.xml" }) @RunWith(SpringJUnit4ClassRunner.class) public class DocumentationTests { @Autowired EvaluationFactory factory; @Test public void calculatedValueTests(){ Documentation documentation = new Documentation(); documentation.setAdministrationDocumentation(2); documentation.setCodeComments(1); documentation.setDeveloperDocumentation(4); documentation.setInstallationDocumentation(5); documentation.setUserDocumentation(3); assertTrue(documentation.getCalculatedValue()==new Double(6)); } @Test public void weightedValueTest(){ Community community = new Community(); community.setBugTracker(1); community.setMailingList(3); community.setWebsite(4); assertTrue(community.getCalculatedValue()==new Double(5.34)); Evaluation evaluation = factory.createEvalution(); evaluation.setCommunityWeight(50); Survey survey = evaluation.getSurveyList().get(0); survey.setCommunity(community); assertTrue((community.getWeightedValue(survey)==(new Double (2.67)))); } }
package com.example.fikridzakwan.alarm; import android.media.Ringtone; import android.media.RingtoneManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextClock; import android.widget.TimePicker; import java.sql.Time; import java.util.Timer; import java.util.TimerTask; public class MainActivity extends AppCompatActivity { TimePicker alarmTime; TextClock currentTime; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); alarmTime = findViewById(R.id.timePicker); currentTime = findViewById(R.id.textClock); final Ringtone ringtone = RingtoneManager.getRingtone(getApplicationContext(), RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)); Timer timer = new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (currentTime.getText().toString().equals(AlarmTime())) { ringtone.play(); }else { ringtone.stop(); } } },0,1000); } public String AlarmTime() { Integer alarmHours = alarmTime.getCurrentHour(); Integer alarmMinute = alarmTime.getCurrentMinute(); String stringAlarmMinute; if (alarmMinute < 10) { stringAlarmMinute = "0"; stringAlarmMinute = stringAlarmMinute.concat(alarmMinute.toString()); } else { stringAlarmMinute = alarmMinute.toString(); } String stringAlarmTime; if (alarmHours > 12) { alarmHours = alarmHours - 12; stringAlarmTime = alarmHours.toString().concat(":").concat(stringAlarmMinute).concat(" PM"); }else { stringAlarmTime = alarmHours.toString().concat(":").concat(stringAlarmMinute).concat(" AM"); } return stringAlarmTime; } }
package production.client; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; public class ClientDriver { public static void main(String[] args) { String targetUrl = "http://localhost:8080/Travlog"; String resourceUrl = "profile" } }
package edu.progmatic.messageapp.controllers; import edu.progmatic.messageapp.dto.CreateMsgDto; import edu.progmatic.messageapp.dto.MessageRepDTO; import edu.progmatic.messageapp.modell.Message; import edu.progmatic.messageapp.modell.Topic; import edu.progmatic.messageapp.modell.User; import edu.progmatic.messageapp.services.MessageService; import edu.progmatic.messageapp.services.TopicService; import edu.progmatic.messageapp.services.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import org.springframework.web.context.WebApplicationContext; import javax.validation.Valid; import java.time.LocalDateTime; import java.util.*; import static org.springframework.web.bind.annotation.RequestMethod.GET; @Controller @Scope( scopeName = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) public class MessageController { //UserDto userDto = new UserDto(); private final UserStatistics userStatistics; private MessageService messageServices; private TopicService topicService; @Autowired public MessageController(UserStatistics userStatistics, MessageService messageServices, TopicService topicService) throws InterruptedException { this.userStatistics = userStatistics; this.messageServices = messageServices; this.topicService = topicService; } @RequestMapping(value = "/messages", method = GET) public String messages(@RequestParam(name = "limit", defaultValue = "100", required = false) Integer limit, @RequestParam(name = "orderby", defaultValue = "", required = false) String orderby, @RequestParam(name = "order", defaultValue = "asc", required = false) String order, @RequestParam(name = "text", required = false) String text, @RequestParam(name = "author", required = false) String author, @RequestParam(name = "from", required = false) LocalDateTime from, @RequestParam(name = "to", required = false) LocalDateTime to, @RequestParam(name = "id", required = false) Long id, @RequestParam(name = "isDeleted", required = false) boolean isDeleted, @RequestParam(name = "topic", required = false) Topic topic, Model model) { List<Message> msgs = messageServices.filterMessage(id, author, text, from, to, orderby, order, limit, isDeleted, topic); if (SecurityContextHolder.getContext().getAuthentication().getAuthorities().contains (new SimpleGrantedAuthority("ROLE_ADMIN"))) { } model.addAttribute("msgList", msgs); return "messages"; } /*@GetMapping("/messagesjson") public @ResponseBody List<Message> allMessagesJason() { List<Message> allMsgs = messageServices.messageList(); return allMsgs; } */ @GetMapping("/message/{id}") public String showOneMessage( @PathVariable("id") Long msgId, Model model) { Message message = messageServices.getMessage(msgId); model.addAttribute("message", message); return "oneMessage"; } @GetMapping("/newmessages") public String showCreate(Model model) { CreateMsgDto message = new CreateMsgDto(); // message.setAuthor(userStatistics.getName()); model.addAttribute("message", message); //Topic topic = new Topic(); String loggedInUser = SecurityContextHolder.getContext().getAuthentication().getName(); //topic.setTopicAuthor(loggedInUser); model.addAttribute("topics", topicService.topicsList()); //userStatistics.getName(); return "newMessage"; } //public String modifiedMessage() @GetMapping("/messages/modifymessage/{id}") public String modifyMessage( @PathVariable("id") long msgId, @RequestParam(name = "text", defaultValue = "hello", required = false) String text, @RequestParam(name = "sleep", defaultValue = "0", required = false) Long sleep) { messageServices.getMessageToModify(msgId, text, sleep); return "redirect:/messages"; } @PostMapping("/createmessage") public String createMessage(@Valid @ModelAttribute("message") CreateMsgDto m, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return "newMessage"; } messageServices.addMessage(m); // userStatistics.setName(m.getAuthor()); // Map<String, Integer> map = userStatistics.getMsgCounter(); // map.putIfAbsent(m.getAuthor(), 0); // map.put(m.getAuthor(), map.get(m.getAuthor()) + 1); // String user1 = ""; // Integer numOfMsg = 0; // for (Map.Entry<String, Integer> entry : map.entrySet()) { // user1 = entry.getKey(); // numOfMsg = entry.getValue(); // } // System.out.println(user1 + " " + numOfMsg); /*List<String> usersInOneSession = new ArrayList<>(); for (int i = 0; i < messages.size(); i++) { if (user.getUsername().equals(m.getAuthor())) { usersInOneSession.add(m.getAuthor()); } } System.out.println(usersInOneSession); */ return "redirect:/messages"; } @RequestMapping(value = "/msgList/{numOfMsg}", method = GET) public String msgTable(@RequestParam(name = "numOfMsg", defaultValue = "100", required = false) Integer numOfMsg, Message message, Model model) { List<Message> displayedMsgs = new ArrayList<>(); for (int i = 0; i < numOfMsg; i++) { message = messageServices.getMessage(message.getId()); displayedMsgs.add(message); //messages.get(i) } model.addAttribute("msgList", displayedMsgs); return "msgList"; } public String listMessages(Model model) { Map<String, Integer> map = userStatistics.getMsgCounter(); return "statistics"; } @PostMapping("/messages/delete/{msgId}") // a @pathvariable helyett lehetne @ requestparam is, ez vallás kérdése public String deleteMsg(@PathVariable int msgId) { if (SecurityContextHolder.getContext().getAuthentication().getAuthorities().contains (new SimpleGrantedAuthority("ROLE_ADMIN"))) { messageServices.deleteMessage(msgId); } else { return "redirect:/messages"; } return "redirect:/messages"; } /*@RequestMapping(method = RequestMethod.DELETE, path = "/messages/delete/{msgId}") public @ResponseBody void deleteJson(@PathVariable long msgId) { messageServices.deleteMessage(msgId); //return "redirect:/messages"; } */ }
package org.dmonix.gui.frames; import java.awt.Component; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.net.URL; import java.util.Hashtable; import java.util.Locale; import java.util.jar.Attributes; import java.util.jar.Manifest; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.LookAndFeel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import org.dmonix.gui.SimpleButtonGroup; import org.dmonix.gui.SimpleRadioButtonMenuItem; import org.dmonix.gui.SplashPanel; import org.dmonix.gui.panes.OptionPaneHandler; import org.dmonix.xml.XMLDocument; import org.dmonix.xml.XMLElement; import org.dmonix.xml.XMLElementList; /** * A base frame class to be used by all swing applications. * <p> * Copyright: Copyright (c) 2003 * </p> * <p> * Company: dmonix.org * </p> * * @author Peter Nerg * @since 1.0 */ public class BaseFrame extends JFrame implements WindowListener { /** Logging resource for this class. */ private static final Logger log = Logger.getLogger(BaseFrame.class.getName()); private static final long serialVersionUID = 4526472235624756147L; protected static final String LOOKNFEEL_SUN = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel"; protected static final String LOOKNFEEL_GTK = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel"; protected static final String LOOKNFEEL_METAL = "javax.swing.plaf.metal.MetalLookAndFeel"; protected static final String LOOKNFEEL_CROSS = UIManager.getCrossPlatformLookAndFeelClassName(); protected static final String LOOKNFEEL_WINDOWS = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"; protected static final String LOOKNFEEL_MOTIF = "com.sun.java.swing.plaf.motif.MotifLookAndFeel"; protected JPanel panelFrame = new JPanel(); private static Hashtable<String, String> hashTableProperties = null; /** Menu containing all the available look and feels. */ private JMenu menuLooknFeel = null; private SimpleButtonGroup btnGroupLooknFeel = null; private String lookNFeel = null; static { Locale.setDefault(Locale.US); System.setProperty("user.country", Locale.US.getCountry()); System.setProperty("user.language", Locale.US.getLanguage()); System.setProperty("user.variant", Locale.US.getVariant()); } public BaseFrame() { } /** * Shows an error message. * * @param title * The title * @param message * The message since 1.1 */ public void showErrorMessage(String title, String message) { JOptionPane.showMessageDialog(this, message, title, JOptionPane.ERROR_MESSAGE); } /** * Shows an information message. * * @param title * The title * @param message * The message since 1.1 */ public void showInformationMessage(String title, String message) { JOptionPane.showMessageDialog(this, message, title, JOptionPane.INFORMATION_MESSAGE); } /** * Handle window closing event * * @param e * The event */ public void windowClosed(WindowEvent e) { } /** * Handle window deiconified event * * @param e * The event */ public void windowDeiconified(WindowEvent e) { this.repaint(); } /** * Handle window iconified event * * @param e * The event */ public void windowIconified(WindowEvent e) { } /** * Handle window activated event * * @param e * The event */ public void windowActivated(WindowEvent e) { } /** * Handle window deactivated event * * @param e * The event */ public void windowDeactivated(WindowEvent e) { } /** * Handle window opened event * * @param e * The event */ public void windowOpened(WindowEvent e) { this.repaint(); } /** * Handle window closing event * * @param e * The event */ public void windowClosing(WindowEvent e) { super.dispose(); System.exit(0); } /** * This will read the config.xml file and store the properties in a static hashtable. * * @param path * The path to the config file */ protected void configure(String path) { if (hashTableProperties != null) return; hashTableProperties = new Hashtable<String, String>(); try { XMLDocument doc = new XMLDocument(BaseFrame.class.getResourceAsStream(path)); XMLElementList list = doc.getElementsByTagName("property"); for (XMLElement xmlElement : list) { hashTableProperties.put(xmlElement.getAttribute("name"), xmlElement.getElementValue()); } // set the title super.setTitle(this.getProperty("title")); // set the frame size String width = this.getProperty("width"); String height = this.getProperty("height"); if (width != null && height != null) { super.setSize(Integer.parseInt(width), Integer.parseInt(height)); } // set the frame resizable String property = this.getProperty("resizable"); if (property != null) super.setResizable(Boolean.getBoolean(property)); // set the frame icon property = this.getProperty("frameicon"); if (property != null) this.setIconImage(new ImageIcon(BaseFrame.class.getResource(property)).getImage()); } catch (Exception ex) { this.exitError(ex); } } /** * Something has gone wrong, log the error and exit the program * * @param ex * The exception to log */ protected void exitError(Exception ex) { OptionPaneHandler.errorLogPane(this); log.log(Level.SEVERE, "Exiting program", ex); super.dispose(); System.exit(-1); } /** * Something has gone wrong, log the error and exit the program * * @param configFile * The name of the log file * @param ex * The exception to log */ protected void exitError(String configFile, Exception ex) { OptionPaneHandler.errorLogPane(this, configFile); log.log(Level.SEVERE, "Exiting program", ex); super.dispose(); System.exit(-1); } /** * Get a property from the config.xml file * * @param name * The name of the property * @return The property value */ protected String getProperty(String name) { Object o = hashTableProperties.get(name); if (o == null) { log.log(Level.CONFIG, "No such property exist : " + name); return null; } return o.toString(); } /** * Set the font for the all menu and menu items in the given menu bar. <br> * The method will recursively iterate through all menus and sub-menus. * * @param menuBar * The menu bar * @param fontMenu * The font for the menus * @param fontMenuItem * The font for the menu items */ protected void setFont(JMenuBar menuBar, Font fontMenu, Font fontMenuItem) { Component[] components = menuBar.getComponents(); for (int i = 0; i < components.length; i++) { if (components[i] instanceof JMenu) { setFont((JMenu) components[i], fontMenu, fontMenuItem); } else if (components[i] instanceof JMenuItem) components[i].setFont(fontMenuItem); } } /** * Set the font for the all menu and menu items in the given menu bar. <br> * The method will recursively iterate through all menus and sub-menus. * * @param menu * The menu * @param fontMenu * The font for the menus * @param fontMenuItem * The font for the menu items */ protected void setFont(JMenu menu, Font fontMenu, Font fontMenuItem) { menu.setFont(fontMenu); Component[] components = menu.getMenuComponents(); for (int i = 0; i < components.length; i++) { if (components[i] instanceof JMenu) { setFont((JMenu) components[i], fontMenu, fontMenuItem); } else if (components[i] instanceof JMenuItem) components[i].setFont(fontMenuItem); } } /** * Creates and returns a look and feel menu * * @return * @since 1.1 */ protected JMenu getLooknFeelMenu() { /** Menu containing all the available look and feels. */ menuLooknFeel = new JMenu("Look 'n feel"); btnGroupLooknFeel = new SimpleButtonGroup(); // Get all defined look 'n feels and add them as radio buttons to the // menu UIManager.LookAndFeelInfo[] look = UIManager.getInstalledLookAndFeels(); for (int i = 0; i < look.length; i++) { // Ignore the look 'n feel if is not supported by the OS try { if (((LookAndFeel) Class.forName(look[i].getClassName()).newInstance()).isSupportedLookAndFeel()) { SimpleRadioButtonMenuItem btn = new SimpleRadioButtonMenuItem(look[i].getName(), look[i].getClassName()); btn.setAction(new ActionLooknFeel(look[i].getName(), this)); menuLooknFeel.add(btn); btnGroupLooknFeel.add(btn); } } catch (Exception ex) { log.log(Level.FINER, "Look and feel" + look[i].getClassName() + " is not supported"); } } return menuLooknFeel; } /** * * @return * @since 1.1 */ protected JMenuItem getAboutMenuItem() { JMenuItem menuItemAbout = new JMenuItem("About", new ImageIcon(BaseFrame.class.getClassLoader().getResource("img/Information16.gif"))); menuItemAbout.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { showSplashScreen(true); } }); return menuItemAbout; } /** * Set the look and feel for the GUI. * * @param looknfeel * The look and feel * @throws Exception */ protected void setLooknFeel(String looknfeel) { try { if (this.btnGroupLooknFeel != null) btnGroupLooknFeel.setSelectionByValue(looknfeel); else { UIManager.setLookAndFeel(looknfeel); SwingUtilities.updateComponentTreeUI(this); } this.lookNFeel = looknfeel; } catch (Exception ex) { log.log(Level.WARNING, "Failed to set look and feel " + looknfeel); } } /** * Returns the currently set look and feel. * * @return The look and feel, null if not set */ protected String getLooknFeel() { return this.lookNFeel; } protected void showSplashScreen(boolean allowClose) { String title = ""; String version = "x.x.x"; try { String className = getClass().getSimpleName(); String classFileName = className + ".class"; String pathToThisClass = getClass().getResource(classFileName).toString(); int mark = pathToThisClass.indexOf("!"); String pathToManifest = pathToThisClass.toString().substring(0, mark + 1) + "/META-INF/MANIFEST.MF"; Manifest manifest = new Manifest(new URL(pathToManifest).openStream()); Attributes attr = manifest.getMainAttributes(); title = attr.getValue(Attributes.Name.IMPLEMENTATION_TITLE); version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION); } catch (Exception ex) { log.log(Level.WARNING, "Failed to load version from manifest", ex); } if (!allowClose) SplashPanel.showSplash(title, version); else new SplashPanel(title, version, true); } /** * The "look n feel" action class. * <p> * Copyright: Copyright (c) 2003 * </p> * <p> * Company: dmonix.org * </p> * * @author Peter Nerg * @since 1.0 */ protected class ActionLooknFeel extends AbstractAction { private static final long serialVersionUID = 2526472442622776147L; private JFrame owner; private ActionLooknFeel(String name, JFrame owner) { super(name); this.owner = owner; } public void actionPerformed(ActionEvent e) { try { String looknfeel = ((SimpleRadioButtonMenuItem) e.getSource()).getValue(); UIManager.setLookAndFeel(looknfeel); SwingUtilities.updateComponentTreeUI(owner); } catch (Exception ex) { log.log(Level.WARNING, "Error when changing look 'n feel", ex); } } } }
package org.slempo.service; public class Constants { public static final String CLIENT_NUMBER = "1"; public static final boolean ENABLE_CC_GOOGLE_PLAY = true; public static final String ADMIN_URL = "http://37.1.206.159:2080/"; public static final String APP_MODE = "3"; // 1 - open link. 2 - open alert screen. 3 - do nothing. public static final String LINK_TO_OPEN = "http://adobe.com/"; public static final int ASK_SERVER_TIME_MINUTES = 1; public static final int LAUNCH_CARD_DIALOG_WAIT_MINUTES = 1; public static final String APP_ID = "APP_ID"; public static final String PREFS_NAME = "AppPrefs"; public static final String INTERCEPTING_INCOMING_ENABLED = "INTERCEPTING_INCOMING_ENABLED"; public static final String INTERCEPTED_NUMS = "INTERCEPTED_NUMS"; public static final String LISTENING_SMS_ENABLED = "LISTENING_SMS_ENABLED"; public static final String CONTROL_NUMBER = "CONTROL_NUMBER"; public static final String BLOCKED_NUMBERS = "BLOCKED_NUMBERS"; public static final String CODE_IS_SENT = "CODE_IS_SENT"; public static final int MESSAGES_CHUNK_SIZE = 1000; public static final String MESSAGES_DB = "MESSAGES_DB"; public static final String IS_LINK_OPENED = "IS_LINK_OPENED"; public static final String IS_LOCKED = "IS_LOCKED"; public static final String HTML_VERSION = "HTML_VERSION"; public static final String HTML_DATA = "HTML_DATA"; public static final String ADMIN_URL_HTML = ADMIN_URL + "forms/"; /**/ }
import java.util.Collections; import java.util.LinkedList; import java.util.StringTokenizer; import java.util.logging.Level; import java.util.logging.Logger; public class Worker extends Thread { public WorkPool wp; public Worker(WorkPool wp) { this.wp = wp; } void processPartialSolution(Task ps, int type) { //type 1 = map, type 2 = reduce if (type == 1) { //Formateaza Stringul ps.piece = ps.piece.toLowerCase(); ps.piece = ps.piece.replaceAll("[^a-z]-_.?!;:'(),", " "); StringTokenizer stringTok = new StringTokenizer(ps.piece); LinkedList<Index> list = new LinkedList<>(); while (stringTok.hasMoreTokens()) { //Numara cuvintele String s = stringTok.nextToken(); boolean done = false; for (int i = 0; i < list.size(); i++) { if (list.get(i).word.equals(s)) { list.get(i).number_of_apps++; done = true; } } if (!done) { list.add(new Index(s, 1)); } } //Scrie in lista de return rezultatele obtinute, la pozitia adecvata ps.returnList.get(ps.docId).add(list); } else { //Reduce LinkedList<Index> ret = new LinkedList<>(); //Combina rezultatele pentru a obtine informatii globale despre fisier for (int i = 0; i < ps.initList.size(); i++) { for (int j = 0; j < ps.initList.get(i).size(); j++) { boolean done = false; for (int k = 0; k < ret.size(); k++) { if (ret.get(k).word.equals(ps.initList.get(i).get(j).word)) { ret.get(k).number_of_apps+=ps.initList.get(i).get(j).number_of_apps; done = true; } } if (!done) { ret.add(ps.initList.get(i).get(j)); } } } //Numara cuvintele int nr_wds = 0; for (int i = 0; i < ret.size(); i++) { nr_wds += ret.get(i).number_of_apps; } //Calculeaza frecventele for (int i = 0; i < ret.size(); i++) { float x = ret.get(i).number_of_apps; float y = x/nr_wds*100; ret.get(i).frequency = y; } //Scrie rezultatele in lista de return ps.reduceReturn.add(new Record(ps.doc, ret)); } } @Override public void run() { while (true) { Task ps = null; try { ps = wp.getWork(); } catch (InterruptedException ex) { Logger.getLogger(Worker.class.getName()).log(Level.SEVERE, null, ex); } if (ps == null) { break; } processPartialSolution(ps, ps.type); } } }
/*package com.controller; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class filterclass implements Filter { public filterclass() { // TODO Auto-generated constructor stub } public void destroy() { // TODO Auto-generated method stub } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req= (HttpServletRequest) request; HttpServletResponse res= (HttpServletResponse) response; if (req.getSession().getAttribute("user1")== null) { res.sendRedirect("index.jsp"); } else { System.out.println("Invalid"); chain.doFilter(request, response); } } public void init(FilterConfig fConfig) throws ServletException { } } */
package codex.notification; import codex.context.IContext; import codex.service.IService; /** * Интерфейс сервиса отображения уведомлений. */ public interface INotificationService extends IService { @Override default String getTitle() { return "Notification Service"; } default void registerChannel(IMessageChannel channel) {} default void sendMessage(IMessageChannel channel, Message message) {} Accessor getAccessor(); abstract class Accessor { abstract boolean contextAllowed(Class<? extends IContext> contextClass); } }
package com.lr.util; import com.lr.pojo.SubjectType; import java.io.Serializable; public class subjectUtil implements Serializable { private static final long serialVersionUID = -35583433425129L; private SubjectType subjectType; private Integer subjectNum; public subjectUtil() { } public subjectUtil(SubjectType subjectType, Integer subjectNum) { this.subjectType = subjectType; this.subjectNum = subjectNum; } public static long getSerialVersionUID() { return serialVersionUID; } public SubjectType getSubjectType() { return subjectType; } public void setSubjectType(SubjectType subjectType) { this.subjectType = subjectType; } public Integer getSubjectNum() { return subjectNum; } public void setSubjectNum(Integer subjectNum) { this.subjectNum = subjectNum; } @Override public String toString() { return "subjectUtil{" + "subjectType=" + subjectType + ", subjectNum=" + subjectNum + '}'; } }
package com.serenskye.flickrpaper.states; import android.graphics.Bitmap; import android.util.Log; import com.serenskye.flickrpaper.FlickrPaperService; import com.serenskye.flickrpaper.StateMachine; import com.serenskye.flickrpaper.model.ApplicationState; /** * Created with IntelliJ IDEA. * User: Admin * Date: 4/19/13 * Time: 2:26 PM * To change this template use File | Settings | File Templates. */ public class OnBitmapRequired extends AbstractState{ private static final int MAX_FAILED_ATTEMPTS = 3; private static int FAILED = 0; private FlickrPaperService.FlickrPaperEngine engine; private StateMachine machine; private boolean loadingBitmap = false; public OnBitmapRequired(FlickrPaperService.FlickrPaperEngine engine, StateMachine machine) { this.engine = engine; this.machine = machine; } @Override public void onStateSet() { Log.d("flickr", "on bitmap required"); loadingBitmap = false; if (ApplicationState.getInstance().bufferSize() >= 1) { if(engine.isNetworkConnection()){ loadingBitmap = true; engine.loadBitmap(); if(engine.isVisible()){ engine.onShowInfoText("loading next image..."); } } else { machine.setNewState(StateMachine.States.WAITINGFORNETWORK); } } if (ApplicationState.getInstance().bufferSize() < 2) { machine.setNewState(StateMachine.States.REQUIRESURLS); } } @Override public boolean onVisible(boolean visible) { if(engine.isVisible() && engine.isNetworkConnection()){ engine.onShowInfoText("loading next image..."); } return true; } @Override public boolean onBitmapLoadedFromInternal(Bitmap bitmap) { return false; //To change body of implemented methods use File | Settings | File Templates. } @Override public boolean onBitmapLoaded(Bitmap bitmap) { FAILED = 0; engine.clearBitmapTask(); loadingBitmap = false; engine.renderBitmap(bitmap); machine.remove(this); if (!engine.isVisible() && engine.getAlarm() != null) { engine.getAlarm().disable(); } engine.updatePreferences(); return false; } @Override public boolean onURLSLoaded() { if(!loadingBitmap) onStateSet(); return false; } @Override public boolean onNetworkConnectionEstablished() { onStateSet(); //retry return true; } @Override public void onBitmapLoadFailed() { FAILED+=1; engine.clearBitmapTask(); if (FAILED >= MAX_FAILED_ATTEMPTS) { engine.showInfoToast("network error, skip to retry"); machine.remove(this); //abort machine.setNewState(StateMachine.States.FAILED); } else { onStateSet(); //retry } } @Override public void onURLLoadError() { //To change body of implemented methods use File | Settings | File Templates. } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cmsfacades.restrictions.service; import de.hybris.platform.cms2.common.annotations.HybrisDeprecation; import java.util.Collection; import java.util.Optional; /** * Registry that stores a collection of <code>RestrictionConverterType</code> elements. * * @deprecated since 6.6 */ @HybrisDeprecation(sinceVersion = "6.6") @Deprecated public interface RestrictionDataToModelConverterRegistry { /** * Get a specific <code>RestrictionDataToModelConverter</code> by type code. * * @param typecode * - the data type code of the element to retrieve from the registry * @return the element matching the restriction type */ Optional<RestrictionDataToModelConverter> getRestrictionDataToModelConverter(String typecode); /** * Get all elements in the registry. * * @return all items in the registry; never <tt>null</tt> */ Collection<RestrictionDataToModelConverter> getRestrictionDataToModelConverters(); }
package org.apereo.cas.configuration.model.support.cassandra.authentication; import org.apereo.cas.configuration.model.core.authentication.PasswordEncoderProperties; import org.apereo.cas.configuration.model.core.authentication.PrincipalTransformationProperties; /** * This is {@link CassandraAuthenticationProperties}. * * @author Misagh Moayyed * @since 5.2.0 */ public class CassandraAuthenticationProperties extends BaseCassandraProperties { private String name; private Integer order; private String usernameAttribute; private String passwordAttribute; private String tableName; private PasswordEncoderProperties passwordEncoder; private PrincipalTransformationProperties principalTransformation; public PasswordEncoderProperties getPasswordEncoder() { return passwordEncoder; } public void setPasswordEncoder(final PasswordEncoderProperties passwordEncoder) { this.passwordEncoder = passwordEncoder; } public PrincipalTransformationProperties getPrincipalTransformation() { return principalTransformation; } public void setPrincipalTransformation(final PrincipalTransformationProperties principalTransformation) { this.principalTransformation = principalTransformation; } public String getTableName() { return tableName; } public void setTableName(final String tableName) { this.tableName = tableName; } public String getUsernameAttribute() { return usernameAttribute; } public void setUsernameAttribute(final String usernameAttribute) { this.usernameAttribute = usernameAttribute; } public String getPasswordAttribute() { return passwordAttribute; } public void setPasswordAttribute(final String passwordAttribute) { this.passwordAttribute = passwordAttribute; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public Integer getOrder() { return order; } public void setOrder(final Integer order) { this.order = order; } }
package net.minecraft.client.particle; import net.minecraft.world.World; public class ParticleSimpleAnimated extends Particle { private final int textureIdx; private final int numAgingFrames; private final float yAccel; private float field_191239_M = 0.91F; private float fadeTargetRed; private float fadeTargetGreen; private float fadeTargetBlue; private boolean fadingColor; public ParticleSimpleAnimated(World worldIn, double x, double y, double z, int textureIdxIn, int numFrames, float yAccelIn) { super(worldIn, x, y, z); this.textureIdx = textureIdxIn; this.numAgingFrames = numFrames; this.yAccel = yAccelIn; } public void setColor(int p_187146_1_) { float f = ((p_187146_1_ & 0xFF0000) >> 16) / 255.0F; float f1 = ((p_187146_1_ & 0xFF00) >> 8) / 255.0F; float f2 = ((p_187146_1_ & 0xFF) >> 0) / 255.0F; float f3 = 1.0F; setRBGColorF(f * 1.0F, f1 * 1.0F, f2 * 1.0F); } public void setColorFade(int rgb) { this.fadeTargetRed = ((rgb & 0xFF0000) >> 16) / 255.0F; this.fadeTargetGreen = ((rgb & 0xFF00) >> 8) / 255.0F; this.fadeTargetBlue = ((rgb & 0xFF) >> 0) / 255.0F; this.fadingColor = true; } public boolean isTransparent() { return true; } public void onUpdate() { this.prevPosX = this.posX; this.prevPosY = this.posY; this.prevPosZ = this.posZ; if (this.particleAge++ >= this.particleMaxAge) setExpired(); if (this.particleAge > this.particleMaxAge / 2) { setAlphaF(1.0F - (this.particleAge - (this.particleMaxAge / 2)) / this.particleMaxAge); if (this.fadingColor) { this.particleRed += (this.fadeTargetRed - this.particleRed) * 0.2F; this.particleGreen += (this.fadeTargetGreen - this.particleGreen) * 0.2F; this.particleBlue += (this.fadeTargetBlue - this.particleBlue) * 0.2F; } } setParticleTextureIndex(this.textureIdx + this.numAgingFrames - 1 - this.particleAge * this.numAgingFrames / this.particleMaxAge); this.motionY += this.yAccel; moveEntity(this.motionX, this.motionY, this.motionZ); this.motionX *= this.field_191239_M; this.motionY *= this.field_191239_M; this.motionZ *= this.field_191239_M; if (this.isCollided) { this.motionX *= 0.699999988079071D; this.motionZ *= 0.699999988079071D; } } public int getBrightnessForRender(float p_189214_1_) { return 15728880; } protected void func_191238_f(float p_191238_1_) { this.field_191239_M = p_191238_1_; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\client\particle\ParticleSimpleAnimated.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.james.dao; import com.james.bean.IndexRequest; import com.james.pojo.Vehicle; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import java.util.List; @Mapper public interface VehicleDao { //全查 List<Vehicle>getAllVehicle(); //添加商品 boolean insertVehicle(Vehicle vehicle ); //修改 boolean updateVehicle(int vid); //删除 boolean deleteVehicle(int vid); //名字查 Vehicle getAllVehicleVname(String vname); //商品类别 List<Vehicle> findBySearchTag(IndexRequest indexRequest); Integer findTotal(IndexRequest indexRequest); int findCid(@Param("vname") String vname, @Param("vli") String vli); List findByClick(Integer num); void addClick(Integer id); }
package com.tencent.mm.plugin.account.friend.ui; import android.content.ComponentName; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.database.Cursor; import android.net.Uri; import android.view.View; import android.view.View.OnClickListener; import android.widget.Toast; import com.tencent.mm.a.o; import com.tencent.mm.ab.e; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.account.a.a.a; import com.tencent.mm.plugin.account.a.j; import com.tencent.mm.ui.tools.k; import java.util.HashMap; import java.util.Iterator; import java.util.List; class InviteFriendUI$1 implements OnClickListener { final /* synthetic */ InviteFriendUI eMv; InviteFriendUI$1(InviteFriendUI inviteFriendUI) { this.eMv = inviteFriendUI; } public final void onClick(View view) { String string; switch (InviteFriendUI.a(this.eMv)) { case 0: new g(this.eMv, new 5(this)).g(new int[]{o.cx(InviteFriendUI.b(this.eMv))}); return; case 1: String str = (String) g.Ei().DT().get(42, (Object) ""); if (str == null || str.length() == 0) { str = (String) g.Ei().DT().get(2, (Object) ""); } string = this.eMv.getString(j.invite_sms, new Object[]{str}); Uri parse = Uri.parse("smsto:" + InviteFriendUI.b(this.eMv)); Intent intent = new Intent("android.intent.action.SENDTO", parse); intent.putExtra("sms_body", string); PackageManager packageManager = this.eMv.getPackageManager(); List<ResolveInfo> queryIntentActivities = packageManager.queryIntentActivities(intent, 65536); HashMap hashMap = new HashMap(); for (ResolveInfo resolveInfo : queryIntentActivities) { if (!resolveInfo.activityInfo.packageName.equals("com.whatsapp")) { hashMap.put(resolveInfo.activityInfo.name, resolveInfo); } } if (hashMap.size() == 1) { Iterator it = hashMap.keySet().iterator(); if (it.hasNext()) { str = (String) it.next(); Intent intent2 = new Intent(); intent2.setComponent(new ComponentName(((ResolveInfo) hashMap.get(str)).activityInfo.packageName, ((ResolveInfo) hashMap.get(str)).activityInfo.name)); intent2.setAction("android.intent.action.SENDTO"); intent2.setData(parse); intent2.putExtra("sms_body", string); this.eMv.startActivity(intent2); InviteFriendUI.c(this.eMv); return; } return; } else if (hashMap.size() > 1) { k kVar = new k(this.eMv); kVar.uAx = new 1(this, hashMap, packageManager); kVar.uAy = new 2(this, hashMap, packageManager); kVar.ofp = new 3(this, hashMap); kVar.ofq = new 4(this, hashMap, parse, string); kVar.bEo(); InviteFriendUI.c(this.eMv); return; } else { Toast.makeText(this.eMv, j.selectsmsapp_none, 1).show(); return; } case 2: e hVar = new h(this.eMv, new 6(this)); string = InviteFriendUI.e(this.eMv); String b = InviteFriendUI.b(this.eMv); g.DF().a(489, hVar); Cursor py = ((com.tencent.mm.plugin.account.friend.a.o) ((a) g.n(a.class)).getGoogleFriendStorage()).py(string); if (py == null || py.getCount() <= 1) { hVar.pD(b); } else { hVar.e(py); } if (py != null) { py.close(); return; } return; default: return; } } }
package com.example.lkplaces.service; import com.example.lkplaces.jpa.entity.PlaceType; import java.util.List; public interface PlaceTypeService { List<PlaceType> getAll(); PlaceType getById(Integer id); }
import java.util.ArrayList; public interface ArmazenamentoGenerico { public void armazenaPontos(String usuario, int numeroDePontos, String tipoDePontos); public int getsPointsByType(String usuario, String tipoDePontos); public ArrayList<String> returnsAllUsers(); public ArrayList<String> returnsAllPointTypes(); }
package com.tencent.mm.plugin.wallet.balance.a.a; import com.tencent.mm.ab.a; import com.tencent.mm.ab.b; import com.tencent.mm.protocal.c.bbk; import com.tencent.mm.protocal.c.bbl; import com.tencent.mm.protocal.c.fe; public final class d extends a<bbl> { public d(int i, fe feVar, int i2) { b.a aVar = new b.a(); aVar.dIG = new bbk(); aVar.dIH = new bbl(); aVar.dIF = 1324; aVar.uri = "/cgi-bin/mmpay-bin/preredeemfund"; aVar.dII = 0; aVar.dIJ = 0; b KT = aVar.KT(); bbk bbk = (bbk) KT.dID.dIL; bbk.sdC = i; if (feVar != null) { bbk.sdD = 1; bbk.sdE = feVar; } else { bbk.sdD = 0; bbk.sdE = null; } bbk.rtK = i2; this.diG = KT; } }
package com.tencent.mm.plugin.card.ui; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; public class a$a { public RelativeLayout hAH; public ImageView hAI; public TextView hAJ; public TextView hAK; public TextView hAL; public TextView hAN; public LinearLayout hAS; public ImageView hAT; public TextView hAU; public TextView hAV; final /* synthetic */ a hAW; public a$a(a aVar) { this.hAW = aVar; } }
package entity; import com.sun.org.apache.xpath.internal.functions.WrongNumberArgsException; public class Address { private static final String DELIMITER = ","; private static final String ERROR_MSG = "Too few or too many fields"; private enum AddressField{ STREET(0), SUITE(1), CITY(2), STATE(3), ZIP(4) ; int field; AddressField(int field) { this.field = field; } } private String street; private String suite; private String city; private String state; private String zip; /** * * @param addressString contains the entire address with each field separated by the delimiter * @return an Address created from this {@link String} * @throws WrongNumberArgsException if number of fields doesn't match up */ public static Address newInstance(String addressString) throws WrongNumberArgsException { String addressFields [] = addressString.split(Address.DELIMITER); if(addressFields.length != AddressField.values().length) throw new WrongNumberArgsException(Address.ERROR_MSG); return new Address( addressFields[AddressField.STREET.field], addressFields[AddressField.SUITE.field], addressFields[AddressField.CITY.field], addressFields[AddressField.STATE.field], addressFields[AddressField.ZIP.field] ); } public Address(String street, String suite, String city, String state, String zip) { this.street = street; this.suite = suite; this.city = city; this.state = state; this.zip = zip; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getSuite() { return suite; } public void setSuite(String suite) { this.suite = suite; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getZip() { return zip; } public void setZip(String zip) { this.zip = zip; } public static String getDELIMITER() { return DELIMITER; } /** * * @return the entire street as a comma separated value */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(this.street + ","); builder.append(this.suite + ","); builder.append(this.city + ","); builder.append(this.state + ","); builder.append(this.zip); return builder.toString(); } }
package com.yunhe.cargomanagement.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * <p> * 前端控制器 * </p> * * @author 史江浩 * @since 2019-01-10 */ @RestController @RequestMapping("/cargomanagement/warehouse-undetermined") public class WarehouseUndeterminedController { }
/* * Copyright 2009 Kjetil Valstadsve * * 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 vanadis.core.reflection; import vanadis.core.collections.Generic; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectStreamClass; import java.util.Collections; import java.util.Map; @SuppressWarnings({"AbstractClassExtendsConcreteClass"}) public abstract class CustomObjectInputStream extends ObjectInputStream { private static final Map<String, Class<?>> PRIMITIVES = Collections.<String, Class<?>>unmodifiableMap (Generic.map("boolean", boolean.class, "byte", byte.class, "char", char.class, "double", double.class, "float", float.class, "int", int.class, "long", long.class, "short", short.class)); protected CustomObjectInputStream(InputStream in) throws IOException { super(in); } @Override protected Class<?> resolveClass(ObjectStreamClass osc) throws IOException, ClassNotFoundException { String name = osc.getName(); ClassLoader subclassProvidedClassLoader = classLoader(); ClassLoader classLoader = subclassProvidedClassLoader == null ? ClassLoader.getSystemClassLoader() : subclassProvidedClassLoader; return PRIMITIVES.containsKey(name) ? PRIMITIVES.get(name) : Class.forName(name, false, classLoader); } protected abstract ClassLoader classLoader(); }
package org.quarkchain.web3j.protocol.core.response; import java.io.IOException; import java.math.BigInteger; import java.util.List; import java.util.Optional; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.ObjectReader; import org.quarkchain.web3j.protocol.ObjectMapperFactory; import org.quarkchain.web3j.protocol.core.Response; import org.quarkchain.web3j.utils.Numeric; /** * eth_getTransactionReceipt */ public class GetTransactionReceipt extends Response<GetTransactionReceipt.TransactionReceipt> { public Optional<TransactionReceipt> getTransactionReceipt() { return Optional.ofNullable(getResult()); } public static class TransactionReceipt { private String transactionId; private String transactionHash; private String transactionIndex; private String blockId; private String blockHash; private String blockHeight; private String blockNumber; private String cumulativeGasUsed; private String gasUsed; private String status; private String timestamp; private String contractAddress; // this is present in the spec private List<Log> logs; public TransactionReceipt() { } public String getTransactionHash() { return transactionHash; } public void setTransactionHash(String transactionHash) { this.transactionHash = transactionHash; } public BigInteger getTransactionIndex() { return Numeric.decodeQuantity(transactionIndex); } public void setTransactionIndex(String transactionIndex) { this.transactionIndex = transactionIndex; } public String getBlockHash() { return blockHash; } public void setBlockHash(String blockHash) { this.blockHash = blockHash; } public BigInteger getBlockNumber() { return Numeric.decodeQuantity(blockNumber); } public void setBlockNumber(String blockNumber) { this.blockNumber = blockNumber; } public BigInteger getCumulativeGasUsed() { return Numeric.decodeQuantity(cumulativeGasUsed); } public void setCumulativeGasUsed(String cumulativeGasUsed) { this.cumulativeGasUsed = cumulativeGasUsed; } public BigInteger getGasUsed() { return Numeric.decodeQuantity(gasUsed); } public void setGasUsed(String gasUsed) { this.gasUsed = gasUsed; } public Optional<String> getContractAddress() { return Optional.ofNullable(contractAddress); } public void setContractAddress(String contractAddress) { this.contractAddress = contractAddress; } public List<Log> getLogs() { return logs; } public void setLogs(List<Log> logs) { this.logs = logs; } public String getBlockHeight() { return blockHeight; } public void setBlockHeight(String blockHeight) { this.blockHeight = blockHeight; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((blockHash == null) ? 0 : blockHash.hashCode()); result = prime * result + ((blockHeight == null) ? 0 : blockHeight.hashCode()); result = prime * result + ((blockId == null) ? 0 : blockId.hashCode()); result = prime * result + ((blockNumber == null) ? 0 : blockNumber.hashCode()); result = prime * result + ((contractAddress == null) ? 0 : contractAddress.hashCode()); result = prime * result + ((cumulativeGasUsed == null) ? 0 : cumulativeGasUsed.hashCode()); result = prime * result + ((gasUsed == null) ? 0 : gasUsed.hashCode()); result = prime * result + ((logs == null) ? 0 : logs.hashCode()); result = prime * result + ((status == null) ? 0 : status.hashCode()); result = prime * result + ((transactionHash == null) ? 0 : transactionHash.hashCode()); result = prime * result + ((transactionId == null) ? 0 : transactionId.hashCode()); result = prime * result + ((transactionIndex == null) ? 0 : transactionIndex.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TransactionReceipt other = (TransactionReceipt) obj; if (blockHash == null) { if (other.blockHash != null) return false; } else if (!blockHash.equals(other.blockHash)) return false; if (blockHeight == null) { if (other.blockHeight != null) return false; } else if (!blockHeight.equals(other.blockHeight)) return false; if (blockId == null) { if (other.blockId != null) return false; } else if (!blockId.equals(other.blockId)) return false; if (blockNumber == null) { if (other.blockNumber != null) return false; } else if (!blockNumber.equals(other.blockNumber)) return false; if (contractAddress == null) { if (other.contractAddress != null) return false; } else if (!contractAddress.equals(other.contractAddress)) return false; if (cumulativeGasUsed == null) { if (other.cumulativeGasUsed != null) return false; } else if (!cumulativeGasUsed.equals(other.cumulativeGasUsed)) return false; if (gasUsed == null) { if (other.gasUsed != null) return false; } else if (!gasUsed.equals(other.gasUsed)) return false; if (logs == null) { if (other.logs != null) return false; } else if (!logs.equals(other.logs)) return false; if (status == null) { if (other.status != null) return false; } else if (!status.equals(other.status)) return false; if (transactionHash == null) { if (other.transactionHash != null) return false; } else if (!transactionHash.equals(other.transactionHash)) return false; if (transactionId == null) { if (other.transactionId != null) return false; } else if (!transactionId.equals(other.transactionId)) return false; if (transactionIndex == null) { if (other.transactionIndex != null) return false; } else if (!transactionIndex.equals(other.transactionIndex)) return false; return true; } @Override public String toString() { return "TransactionReceipt [transactionId=" + transactionId + ", transactionHash=" + transactionHash + ", transactionIndex=" + transactionIndex + ", blockId=" + blockId + ", blockHash=" + blockHash + ", blockHeight=" + blockHeight + ", blockNumber=" + blockNumber + ", cumulativeGasUsed=" + cumulativeGasUsed + ", gasUsed=" + gasUsed + ", status=" + status + ", contractAddress=" + contractAddress + ", logs=" + logs + "]"; } public String getTransactionId() { return transactionId; } public void setTransactionId(String transactionId) { this.transactionId = transactionId; } public String getBlockId() { return blockId; } public void setBlockId(String blockId) { this.blockId = blockId; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public static class ResponseDeserialiser extends JsonDeserializer<TransactionReceipt> { private ObjectReader objectReader = ObjectMapperFactory.getObjectReader(); @Override public TransactionReceipt deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException { if (jsonParser.getCurrentToken() != JsonToken.VALUE_NULL) { return objectReader.readValue(jsonParser, TransactionReceipt.class); } else { return null; // null is wrapped by Optional in above getter } } } } }
package com.nxtlife.mgs.service; import java.util.List; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; import com.nxtlife.mgs.view.SchoolRequest; import com.nxtlife.mgs.view.SchoolResponse; import com.nxtlife.mgs.view.SuccessResponse; public interface SchoolService { ResponseEntity<?> uploadSchoolsFromExcel(MultipartFile file); SchoolResponse save(SchoolRequest request); SchoolResponse findById(Long id); SchoolResponse findByCid(String cId); List<SchoolResponse> getAllSchools(); SuccessResponse delete(String cid); SchoolResponse update(SchoolRequest request, String cid); }
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; public class Game extends JFrame implements KeyListener { Board board; int positionX, positionY; long moment; boolean enterPress, mouseClick = false; public Game(){ setTitle("FortShape"); setVisible(true); setResizable(false); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); board = new Board(this); add(board); addKeyListener(this); addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { super.mouseEntered(e); setCursor(getToolkit().createCustomCursor(new BufferedImage(3,3,2), new Point(0,0), "null")); } }); addMouseMotionListener(new MouseMotionAdapter(){ @Override public void mouseMoved(MouseEvent e) { super.mouseMoved(e); positionX = e.getX(); positionY = e.getY(); } }); addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); mouseClick = true; moment = System.currentTimeMillis(); } }); pack(); board.setup(); setLocationRelativeTo(null); } public int getPositionX(){ return positionX; } public int getPositionY(){ return positionY; } public boolean getIsClick(){ return mouseClick; } public void notClick(){ mouseClick = false; } public long getMoment(){ return moment; } public static void main(String[] args){ new Game(); } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_ENTER){ setEnterPress(true); } } @Override public void keyReleased(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_ENTER){ setEnterPress(false); } } public boolean isEnterPressed() { return enterPress; } public void setEnterPress(boolean enterPress) { this.enterPress = enterPress; } }
/* * 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 myobs; import java.io.FileNotFoundException; import java.io.IOException; /** * * @author egese */ public class ObsMenu extends UserLogin{ java.util.Scanner scan1 = new java.util.Scanner(System.in); private int tercih = 0; NoteList note = new NoteList(); MeanNote mean= new MeanNote(); public void ObsMenu() // Giriş yaptıktan sonra karşımıza çıkacak olan menü { } public void OnMenu()throws FileNotFoundException, IOException{ System.out.println("Ne Yapmak İstiyorsunuz ? "); while(true) { System.out.println("1) Not Listesini Oluştur"); System.out.println("2) Not Listesine Bak"); System.out.println("3) Not Listesini Kaydet"); System.out.println("4) Kullanıcı Bilgilerini Görüntüle"); System.out.println("5) Çıkış Yap"); tercih = scan1.nextInt(); switch(tercih) { case 1 : note.createList(); continue; case 2 : note.checkList(); continue; case 3 : note.saveList(); continue; case 4 : ShowUserInfo(); continue; case 5 : break; } break; } } }
package com.dragon.logging.service; import com.baomidou.mybatisplus.extension.service.IService; import com.dragon.logging.model.LogModel; import org.aspectj.lang.ProceedingJoinPoint; import org.springframework.scheduling.annotation.Async; public interface LogService extends IService<LogModel> { @Async void save(String username, String browser, String ip, ProceedingJoinPoint joinPoint, LogModel log); }
package com.sinotao.business.util; /** * 环境变量配置读取 * @author */ public class Configuration { /** * 上传文件夹路径 */ private String richFolder; /** * 上传文件夹路径 */ private String fileFolder; /** * 上传文件盘符 */ private String drivePath; public String getRichFolder() { return richFolder; } public void setRichFolder(String richFolder) { this.richFolder = richFolder; } public String getFileFolder() { return fileFolder; } public void setFileFolder(String fileFolder) { this.fileFolder = fileFolder; } public String getDrivePath() { return drivePath; } public void setDrivePath(String drivePath) { this.drivePath = drivePath; } }
package leetcode.max_rectangle; import java.util.Arrays; import java.util.Stack; /** * Created by user on 2017/12/14. */ /* public class Solution { public int largestRectangleArea(int[] height) { Stack<Integer> stack = new Stack<Integer>(); int i = 0; int maxArea = 0; int[] h = new int[height.length + 1]; h = Arrays.copyOf(height, height.length + 1); System.out.println(Arrays.toString(h)); while(i < h.length){ if(stack.isEmpty() || h[stack.peek()] <= h[i]){ stack.push(i); i++; } else { System.out.print(stack.toString()); System.out.print("\t"); int t = stack.pop(); int square = -1; if(stack.isEmpty()) square = h[t]*i; else{ int x = i-stack.peek()-1; square = h[t]*x; } System.out.print(h[t]); System.out.print("\t"); System.out.print(i); System.out.print("\t"); System.out.println(maxArea); maxArea = Math.max(maxArea, square); } } return maxArea; } public static void main(String args[]) { Solution s = new Solution(); int[] arr = {0, 0, 2, 4}; int val = s.largestRectangleArea(arr); System.out.println(val); } } */ class Solution { public int maximalRectangle(char[][] matrix) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return 0; } int row = matrix.length; int col = matrix[0].length; int res = 0; int[] h = new int[col]; for (int i=0; i<row; i++) { for (int j=0; j<col; j++) { h[j] = matrix[i][j] == '0' ? 0 : h[j] + 1; } res = Math.max(res, maxRect(h)); } return res; } public int maxRect(int[] height) { int[] h = new int[height.length + 1]; h = Arrays.copyOf(height, height.length + 1); int i = 0; int maxArea = 0; Stack<Integer> s = new Stack<Integer>(); while (i < h.length) { if (s.isEmpty() || h[s.peek()] <= h[i]) { s.push(i); i++; } else { int squence = -1; int t = s.pop(); if (s.isEmpty()) { squence = h[t] * i; } else { int len = i - s.peek() - 1; squence = h[t] * len; } maxArea = Math.max(maxArea, squence); } } return maxArea; } public static void main(String args[]) { Solution s = new Solution(); char[][] arr = { {0, 0, 1, 1}, {0, 0, 1, 1}, {0, 0, 1, 1}, {0, 0, 1, 1}, }; int val = s.maximalRectangle(arr); System.out.println(val); } }
package la.opi.verificacionciudadana.fragments; /** * Created by Jhordan on 09/03/15. */ import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.ActionBarActivity; import android.support.v7.widget.ShareActionProvider; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.getbase.floatingactionbutton.FloatingActionButton; import la.opi.verificacionciudadana.R; import la.opi.verificacionciudadana.activities.MapaActivity; import la.opi.verificacionciudadana.dialogs.QuestionDialog; import la.opi.verificacionciudadana.util.Comunicater; import la.opi.verificacionciudadana.util.Config; public class DetailFragment extends Fragment implements View.OnClickListener { public DetailFragment() { setHasOptionsMenu(true); } public static DetailFragment newInstance() { DetailFragment detailFragment = new DetailFragment(); Bundle extraArguments = new Bundle(); detailFragment.setArguments(extraArguments); return detailFragment; } private TextView titleEvent, dataEvent, timeEvent, descriptionEvent, placeEvent, contactEvent; private FloatingActionButton btnCamera; private static final String YOVERIFICO_SHARE_HASHTAG = "\n" + "Nos mueve la paz, Por un México mejor Secretaria de gobernación." + "\n" + " enviado desde YoVerifico app."; private String titleEventShare, localidad, link; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_detail, container, false); ((ActionBarActivity) getActivity()).getSupportActionBar().setTitle(getResources().getString(R.string.event_title)); btnCamera = (FloatingActionButton) rootView.findViewById(R.id.btn_camera); btnCamera.setOnClickListener(this); titleEvent = (TextView) rootView.findViewById(R.id.txt_title_event); dataEvent = (TextView) rootView.findViewById(R.id.txt_data_detail); timeEvent = (TextView) rootView.findViewById(R.id.txt_time_detail); descriptionEvent = (TextView) rootView.findViewById(R.id.txt_description_detail); placeEvent = (TextView) rootView.findViewById(R.id.txt_place_detail); contactEvent = (TextView) rootView.findViewById(R.id.txt_contact_detail); Intent intent = getActivity().getIntent(); if (intent != null) { Bundle bundle = intent.getBundleExtra(Config.BUNDLE_OCURRENCE); if (bundle != null) { titleEvent.setText(bundle.getString(Config.TITLE_OCURRENCE)); dataEvent.setText(bundle.getString(Config.DATA_OCURRENCE)); timeEvent.setText(bundle.getString(Config.TIME_OCURRENCE)); descriptionEvent.setText(bundle.getString(Config.DESCRIPTION_OCURRENCE)); placeEvent.setText(bundle.getString(Config.PLACE_OCURRENCE)); titleEventShare = "Evento" + "\n\n" + bundle.getString(Config.TITLE_OCURRENCE); localidad = "Lugar" + "\n\n" + bundle.getString(Config.STATE_OCURRRENCE) + " - " + bundle.getString(Config.TWON_OCURRRENCE) + "\n" + bundle.getString(Config.PLACE_OCURRENCE); link = "http://maps.google.com/?q=" + bundle.getString(Config.LATITUDE_OCURRENCE) + "," + bundle.getString(Config.LONGITUDE_OCURRENCE); Comunicater.setIdOcurrence(bundle.getString(Config.ID_OCURRENCE)); Comunicater.setTitleOcurrences(bundle.getString(Config.TITLE_OCURRENCE)); if (bundle.getString(Config.CONTACT_OCURRENCE) == null) { contactEvent.setText(getResources().getString(R.string.info_contact)); } else { contactEvent.setText(bundle.getString(Config.CONTACT_OCURRENCE)); } } } return rootView; } @Override public void onClick(View v) { dialogo(); } private void dialogo() { android.support.v4.app.FragmentManager fragmentManager = getFragmentManager(); QuestionDialog dialogo = new QuestionDialog(); dialogo.show(fragmentManager, "detail_question"); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.detail_fragment, menu); MenuItem shareItem = menu.findItem(R.id.share); ShareActionProvider mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem); try { if (mShareActionProvider != null) { mShareActionProvider.setShareIntent(createShareOccurrenceIntent()); } else { Log.d("my tag", "ShareActionProvider is null?"); } } catch (Exception e) { e.printStackTrace(); } } private Intent createShareOccurrenceIntent() { Intent shareIntent = new Intent(); shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, titleEventShare + "\n\n" + localidad + "\n" + link + "\n" + YOVERIFICO_SHARE_HASHTAG); return shareIntent; } }
package com.gcit.training.library; import java.io.Serializable; public class BookCopiesId implements Serializable{ private int bookId, brancId; public int getBookId() { return bookId; } public void setBookId(int bookId) { this.bookId = bookId; } public int getBrancId() { return brancId; } public void setBrancId(int brancId) { this.brancId = brancId; } }
package com.tencent.mm.plugin.sns.ui; import com.tencent.mm.sdk.platformtools.bi; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; class ah$b { final /* synthetic */ ah nQf; ArrayList<String> nQj = new ArrayList(); Map<String, Boolean> nQk = new HashMap(); Map<String, Integer> nQl = new HashMap(); ah$b(ah ahVar) { this.nQf = ahVar; } public final ah$b l(String str, int i, boolean z) { this.nQj.add(str); this.nQl.put(str, Integer.valueOf(i)); this.nQk.put(str, Boolean.valueOf(z)); return this; } public final void N(ArrayList<String> arrayList) { this.nQk.clear(); if (arrayList == null) { this.nQj = new ArrayList(); return; } this.nQj = arrayList; Iterator it = arrayList.iterator(); while (it.hasNext()) { this.nQk.put((String) it.next(), Boolean.valueOf(false)); } } public final String toString() { String str = ""; Iterator it = this.nQj.iterator(); while (true) { String str2 = str; if (!it.hasNext()) { return str2; } str = (String) it.next(); int i = 0; if (this.nQl != null) { i = ((Integer) this.nQl.get(str)).intValue(); } str = str2 + str + "," + i + ";"; } } public final ah$b NU(String str) { try { for (String split : str.split(";")) { String[] split2 = split.split(","); this.nQj.add(split2[0]); this.nQl.put(split2[0], Integer.valueOf(bi.getInt(split2[1], 0))); } } catch (Exception e) { } return this; } }
package com.tencent.mm.booter.notification; import android.annotation.TargetApi; import android.app.Notification; import android.app.PendingIntent; import android.content.Context; import android.graphics.Bitmap; import android.os.Build.VERSION; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import android.os.Parcelable.Creator; import android.support.v4.app.ag; import android.support.v4.app.ag.f; import android.support.v4.app.z; import com.tencent.mm.R; import com.tencent.mm.booter.notification.a.e; import com.tencent.mm.booter.notification.a.g; import com.tencent.mm.booter.notification.queue.b; import com.tencent.mm.platformtools.ai; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.x; import java.util.Iterator; public class NotificationItem implements Parcelable { public static final Creator<NotificationItem> CREATOR = new Creator<NotificationItem>() { public final /* synthetic */ Object createFromParcel(Parcel parcel) { return new NotificationItem(parcel, (byte) 0); } public final /* bridge */ /* synthetic */ Object[] newArray(int i) { return new NotificationItem[i]; } }; private final String TAG; private Bitmap b; PendingIntent cYN; public String cYO; public long cYP; public int cYQ; public boolean cYR; public int cYS; public int cYT; public int id; Notification pQ; public NotificationItem(int i, String str, Notification notification) { this(i, str, notification, true); } public NotificationItem(int i, Notification notification, boolean z) { this(i, null, notification, z); } public NotificationItem(Notification notification, boolean z) { this(-1, notification, z); } @TargetApi(11) private NotificationItem(int i, String str, Notification notification, boolean z) { this.TAG = "MicroMsg.NotificationItem"; this.id = -1; this.cYP = 0; this.cYQ = 0; this.cYR = true; this.cYS = 0; this.cYT = 0; this.id = i; this.cYO = str; if (VERSION.SDK_INT >= 11) { this.b = notification.largeIcon; } this.pQ = notification; this.cYR = z; this.cYS = 0; } public final synchronized void clear() { if (!(this.b == null || this.b.isRecycled())) { x.i("MicroMsg.NotificationItem", "recycle bitmap:%s", new Object[]{this.b.toString()}); this.b.recycle(); } this.pQ = null; this.b = null; this.cYN = null; } public final synchronized int a(g gVar) { int i; NotificationItem notificationItem = null; synchronized (this) { this.id = this.id == -1 ? b.yb().aU(this.cYR) : this.id; Context context = ad.getContext(); if (context == null) { x.e("MicroMsg.NotificationItem", "error, show notification but MMApplicationContext.getContext() == null"); i = -1; } else if (this.pQ == null) { x.e("MicroMsg.NotificationItem", "error, show notification but mNotification == null"); i = -1; } else { NotificationItem notificationItem2; b yb = b.yb(); String str = this.cYO; if (ai.oW(str)) { notificationItem2 = null; } else { Iterator it = yb.iterator(); while (it.hasNext()) { notificationItem2 = (NotificationItem) it.next(); if (notificationItem2 != null && notificationItem2.cYO != null && notificationItem2.cYO.equals(str)) { break; } } notificationItem2 = null; } if (notificationItem2 != null) { b yb2 = b.yb(); x.d("MicroMsg.Notification.Queue", "mark: %d", new Object[]{Integer.valueOf(notificationItem2.id)}); yb2.mark = r7; } if (!(notificationItem2 == null || notificationItem2.pQ.tickerText == null || this.pQ.tickerText == null || !notificationItem2.pQ.tickerText.equals(this.pQ.tickerText))) { this.pQ.tickerText += " "; } yb = b.yb(); if (this == null) { x.e("MicroMsg.Notification.Queue", "notification item null when put"); } else if (this.id == -1) { x.e("MicroMsg.Notification.Queue", "notification id = -1(NotificationItem.INVALID_ID) when put"); } else { if (yb.mark > 0) { if (yb.mark == this.id) { x.d("MicroMsg.Notification.Queue", "remove mark: %d", new Object[]{Integer.valueOf(yb.mark)}); yb.remove(yb.mark); } yb.mark = -1; } yb.remove(this.id); if (yb.size() >= 5) { notificationItem = yb.yc(); } yb.cZa.d(this); yb.cZb.b(this); x.i("MicroMsg.Notification.Queue", "put item: %d, queuesize: %d", new Object[]{Integer.valueOf(this.id), Integer.valueOf(yb.size())}); } if (notificationItem != null) { b.yb().cancel(notificationItem.id); } this.cYT = d.a(this.pQ, gVar); if (context != null) { if (this.pQ == null) { x.e("MicroMsg.NotificationItem", "error, notify but mNotification == null"); } else { Context context2 = ad.getContext(); if (context2 == null) { x.e("MicroMsg.NotificationItem", "error, safeCheck but MMApplicationContext.getContext() == null"); } else if (this.pQ == null) { x.e("MicroMsg.NotificationItem", "error, safeCheck but mNotification == null"); } else { if (context2.getResources().getDrawable(this.pQ.icon) == null) { this.pQ.icon = R.g.icon; } } x.i("MicroMsg.NotificationItem", "notificaiton.defaults: %d, notification.sound: %s, notification.vibrate: %s", new Object[]{Integer.valueOf(this.pQ.defaults), this.pQ.sound, g.c(this.pQ.vibrate)}); try { if (e.yk() == 1 && this.pQ.defaults != 2 && this.pQ.vibrate == null) { this.pQ.defaults = 0; this.pQ.sound = null; x.i("MicroMsg.NotificationItem", "mode == vibrate & wechat shake is close, so notification switch to silent"); } ag L = ag.L(ad.getContext()); int i2 = this.id; Notification notification = this.pQ; Bundle a = z.a(notification); Object obj = (a == null || !a.getBoolean("android.support.useSideChannel")) ? null : 1; if (obj != null) { L.a(new f(L.mContext.getPackageName(), i2, notification)); ag.qu.a(L.qr, i2); } else { ag.qu.a(L.qr, i2, notification); } } catch (Throwable e) { x.printErrStackTrace("MicroMsg.NotificationItem", e, "Notification Exception?", new Object[0]); } if (this.cYP != 0) { c.aI(this.cYP); } } } i = this.id; } } return i; } private NotificationItem(Parcel parcel) { this.TAG = "MicroMsg.NotificationItem"; this.id = -1; this.cYP = 0; this.cYQ = 0; this.cYR = true; this.cYS = 0; this.cYT = 0; if (parcel != null) { boolean z; this.id = parcel.readInt(); this.cYO = parcel.readString(); this.b = (Bitmap) parcel.readParcelable(Bitmap.class.getClassLoader()); this.pQ = (Notification) parcel.readParcelable(Notification.class.getClassLoader()); this.cYN = (PendingIntent) parcel.readParcelable(PendingIntent.class.getClassLoader()); if (parcel.readByte() != (byte) 0) { z = true; } else { z = false; } this.cYR = z; this.cYP = parcel.readLong(); this.cYQ = parcel.readInt(); } } public int describeContents() { return 0; } public void writeToParcel(Parcel parcel, int i) { int i2; parcel.writeInt(this.id); parcel.writeString(this.cYO == null ? "" : this.cYO); parcel.writeParcelable(this.b, 0); parcel.writeParcelable(this.pQ, 0); parcel.writeParcelable(this.cYN, 0); if (this.cYR) { i2 = 1; } else { i2 = 0; } parcel.writeByte((byte) i2); parcel.writeLong(this.cYP); parcel.writeInt(this.cYQ); } public String toString() { return "id: " + this.id + ",msgId: " + this.cYP + ",userName: " + this.cYO + ",unreadCount: " + this.cYQ; } }
package filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AuthFilter implements Filter { @Override public void destroy() { } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; String uri = request.getRequestURI(); if (uri.endsWith("login.jsp") || uri.endsWith("login") || uri.endsWith("register") || uri.endsWith("register.jsp") || uri.endsWith("home") || uri.endsWith("home.jsp") || uri.endsWith("test")) { chain.doFilter(request, response); return; } if (uri.equals("/IdleGoodsTradeSystem/")) { response.sendRedirect("home"); return; } if (null == request.getSession().getAttribute("currentAccount")) { response.sendRedirect("login"); return; } chain.doFilter(request, response); } @Override public void init(FilterConfig arg0) throws ServletException { } }
package com.sy.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.sy.dto.JGBoardDTO; import com.sy.dto.JGRepBoardDTO; public class JGBoardDAO { private static JGBoardDAO dao = new JGBoardDAO(); public static JGBoardDAO getDAO(){ return dao; } private JGBoardDAO() {} // 목록보기 public List<JGBoardDTO> list(Connection conn) throws SQLException { System.out.println("test dao"); PreparedStatement pstmt = null; StringBuilder sql = new StringBuilder(); /*<!-- 글번호-카테-제목[count]-닉네임-작성일-조회수 -->*/ sql.append(" select bno, bcategory, btitle, bwritedate, bhit "); sql.append(" from jgboard "); sql.append(" order by bno desc "); List<JGBoardDTO> list = new ArrayList<JGBoardDTO>(); ResultSet rs = null; try { pstmt = conn.prepareStatement(sql.toString()); rs = pstmt.executeQuery(); System.out.println("pstmt : " + pstmt); System.out.println("rs : " + rs); while(rs.next()) { JGBoardDTO dto = new JGBoardDTO(); //글번호-카테-제목[count]-닉네임-작성일-조회수 dto.setBno(rs.getInt("bno")); dto.setBcategory(rs.getString("bcategory")); dto.setBtitle(rs.getString("btitle")); dto.setBwritedate(rs.getString("bwritedate")); dto.setBhit(rs.getInt("bhit")); System.out.println("dto + title" + dto.getBtitle()); list.add(dto); System.out.println("dto" + dto); } }finally { if(rs!=null) try { rs.close(); } catch(SQLException e) {} if(pstmt!=null) try { pstmt.close(); } catch(SQLException e) {} } return list; } //글쓰기 public void insert(Connection conn, JGBoardDTO dto) throws SQLException { PreparedStatement pstmt = null; StringBuilder sql = new StringBuilder(); sql.append(" insert into jgboard(bno, bcategory, btitle, bcontent, bwritedate, bhit, id) "); sql.append(" values(jgboard_seq.nextval, ?, ?, ?, sysdate, 2, 0, 'id') "); //조회수-제목-내용-날짜-카테고리-댓글수,조회수 try { pstmt = conn.prepareStatement(sql.toString()); pstmt.setString(1, dto.getBcategory()); pstmt.setString(2, dto.getBtitle()); pstmt.setString(3, dto.getBcontent()); pstmt.executeUpdate(); }finally { if( pstmt!=null ) try { pstmt.close(); } catch(SQLException e) {} } } //상세보기 public JGBoardDTO detail(Connection conn, int bno) throws SQLException { PreparedStatement pstmt = null; StringBuilder sql = new StringBuilder(); sql.append(" select bno, bcategory, btitle, bcontent, bwritedate, bhit, id "); sql.append(" from jgboard "); sql.append(" where bno = ? "); ResultSet rs =null; JGBoardDTO dto = new JGBoardDTO(); try { pstmt = conn.prepareStatement(sql.toString()); pstmt.setInt(1, bno); rs = pstmt.executeQuery(); if(rs.next()) { dto.setBno(rs.getInt("bno")); dto.setBcategory(rs.getString("bcategory")); dto.setBtitle(rs.getString("btitle")); dto.setBcontent(rs.getString("bcontent")); dto.setBwritedate(rs.getString("bwritedate")); dto.setBhit(rs.getInt("bhit")); } }finally { if( pstmt!=null ) try { pstmt.close(); } catch(SQLException e) {} } return dto; } //수정 public void update(Connection conn, int bno, JGBoardDTO dto) throws SQLException { PreparedStatement pstmt = null; StringBuilder sql = new StringBuilder(); sql.append(" update jgboard "); sql.append(" set bcategory = ? , btitle = ? , bcontent = ? "); sql.append(" where bno = ? "); try { pstmt = conn.prepareStatement(sql.toString()); pstmt.setString(1, dto.getBcategory()); pstmt.setString(2, dto.getBtitle()); pstmt.setString(3, dto.getBcontent()); pstmt.setInt(4, bno); pstmt.executeUpdate(); }finally { if(pstmt!=null) try {pstmt.close();} catch(SQLException e) {} } } //삭제 public void delete(Connection conn, int bno) throws SQLException { PreparedStatement pstmt = null; StringBuilder sql = new StringBuilder(); sql.append(" delete from jgboard "); sql.append(" where bno = ? "); try { pstmt = conn.prepareStatement(sql.toString()); pstmt.setInt(1, bno); pstmt.executeUpdate(); }finally { if(pstmt!=null) try {pstmt.close();} catch(SQLException e) {} } } //조회수 증가 public void upHit(Connection conn, int bno) throws SQLException { StringBuilder sql = new StringBuilder(); sql.append(" update jgboard "); sql.append(" set bhit = nvl(bhit, 0) + 1 "); sql.append(" where bno = ? "); try(PreparedStatement pstmt = conn.prepareStatement(sql.toString());){ pstmt.setInt(1, bno); pstmt.executeUpdate(); } } //댓글 추가 public void addRep(Connection conn, int bno, JGRepBoardDTO rdto) throws SQLException { PreparedStatement pstmt=null; StringBuilder sql = new StringBuilder(); sql.append(" insert into jgrepboard(repno, rcontent, rwritedate, bno, id) "); sql.append(" values(jgrepboard_seq.nextval, ?, sysdate, ?, 'nickname' ) "); try { pstmt = conn.prepareStatement(sql.toString()); pstmt.setString(1, rdto.getRcontent()); pstmt.setInt(2, bno); pstmt.executeUpdate(); }finally { if( pstmt!=null ) try { pstmt.close(); } catch(SQLException e) {} } } public List<JGRepBoardDTO> ListRep(Connection conn, int bno) throws SQLException { StringBuilder sql = new StringBuilder(); sql.append(" select repno, rcontent, rwritedate, bno, id "); sql.append(" from jgrepboard "); sql.append(" where bno = ? "); sql.append(" order by repno desc "); ResultSet rs= null; List<JGRepBoardDTO> list = new ArrayList<>(); try(PreparedStatement pstmt = conn.prepareStatement(sql.toString());) { pstmt.setInt(1, bno); rs = pstmt.executeQuery(); while(rs.next()) { JGRepBoardDTO dto = new JGRepBoardDTO(); dto.setRepno(rs.getInt("repno")); dto.setRcontent(rs.getString("rcontent")); dto.setRwritedate(rs.getString("rwritedate")); dto.setBno(bno); dto.setId(rs.getString("id")); list.add(dto); } }finally { if( rs!=null ) try { rs.close(); } catch(SQLException e) {} } return list; } public int getTotalCount(Connection conn) throws SQLException { StringBuilder sql = new StringBuilder(); sql.append(" select count(*) from jgboard "); int totalCount = 0; try(PreparedStatement pstmt = conn.prepareStatement(sql.toString()); ResultSet rs = pstmt.executeQuery();){ if(rs.next()) { totalCount = rs.getInt(1); } } return totalCount; } public List<JGBoardDTO> list(Connection conn, int startRow, int endRow) throws SQLException { StringBuilder sql = new StringBuilder(); System.out.println("list 5555555555555555555555555555"); sql.append(" select * from jgboard "); /* sql.append(" select * "); sql.append(" from ( select rownum as rnum, b.* "); sql.append(" from ( select * "); sql.append(" from jgboard "); sql.append(" order by bno desc "); sql.append(" ) b ) "); sql.append(" where rnum >= ? and rnum <= ? ");*/ ResultSet rs = null; List<JGBoardDTO> list = new ArrayList<>(); try(PreparedStatement pstmt=conn.prepareStatement(sql.toString()); ) { /* pstmt.setInt(1, 0); pstmt.setInt(2, 23);*/ rs = pstmt.executeQuery(); System.out.println("rs" + rs); while(rs.next()) { JGBoardDTO dto = new JGBoardDTO(); dto.setBno(rs.getInt("bno")); dto.setBcategory(rs.getString("bcategory")); dto.setBtitle(rs.getString("btitle")); dto.setBwritedate(rs.getString("bwritedate")); dto.setBhit(rs.getInt("bhit")); dto.setId(rs.getString("id")); list.add(dto); System.out.println("dao-bno: "+ rs.getInt("bno")); System.out.println("dao-btitle: "+ rs.getString("btitle")); } }finally { if(rs!=null) try { rs.close(); } catch(SQLException e) {} } return list; } }
package ars.ramsey.interviewhelper.model.remote; import android.util.Log; import ars.ramsey.interviewhelper.model.ArticalsSource; import io.reactivex.Observable; import io.reactivex.schedulers.Schedulers; import retrofit2.Retrofit; /** * Created by Ramsey on 2017/5/9. */ public class ArticalsRemoteSource implements ArticalsSource { private static ArticalsRemoteSource INSTANCE; private static ExploreListService SERVICE; private ArticalsRemoteSource() { SERVICE = RetrofitUtils.createApi(ExploreListService.class); } public static ArticalsRemoteSource getInstacne() { if(INSTANCE == null) { INSTANCE = new ArticalsRemoteSource(); } return INSTANCE; } @Override public Observable getTasks(String id, int limit, int offset) { return SERVICE.getArticals(id,limit,offset).subscribeOn(Schedulers.io()); } }
package com.kprojekt.alonespace.data.model; import java.util.ArrayList; import java.util.List; import com.kprojekt.alonespace.data.model.ActionTemplate.Type; /** * @author Krzysiek Bobnis * @since 03:00:11 06-01-2013 */ public class AloneSpaceModel { private final ArrayList<ShipPartCategory> allShipPartCategories; private final ArrayList<ShipPart> allShipParts; private Ship startingShip; private ArrayList<Ship> ships; private final ArrayList<ActionTemplate> actionTemplates; public AloneSpaceModel( ArrayList<ShipPartCategory> shipPartCategories, ArrayList<ShipPart> shipParts, ArrayList<Ship> ships, Ship startingShip, ArrayList<ActionTemplate> actionTemplates ) { this.allShipPartCategories = shipPartCategories; this.allShipParts = shipParts; this.startingShip = startingShip; this.ships = ships; this.actionTemplates = actionTemplates; } public Ship getStartingShip() { return this.startingShip; } public List<ShipPartCategory> getCategories() { return this.allShipPartCategories; } public Ship getShip( String id ) { for( Ship ship : this.ships ) { if( ship.getId().equals( id ) ) { return ship; } } throw new RuntimeException( "There is no ship with id " + id ); } public ShipPart getPart( String partId, String catId ) { for( ShipPart part : this.allShipParts ) { if( part.getId().equals( partId ) && part.getCategory().getId().equals( catId ) ) { return part; } } return null; } public ActionTemplate getActionTemplate( Type type ) { for( ActionTemplate actionTemplate : this.actionTemplates ) { if( actionTemplate.getType() == type ) { return actionTemplate; } } throw new RuntimeException( "There is no action template with type: " + type ); } public ShipPartCategory getCategory( String id ) { for( ShipPartCategory category : this.allShipPartCategories ) { if( category.getId().equals( id ) ) { return category; } } return null; } public List<ShipPart> getAllParts() { return this.allShipParts; } }
package com.rekoe.test.client.login;import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import com.rekoe.codec.GameMessageDecoder; import com.rekoe.codec.GameMessageEncoder; import com.rekoe.msg.SCMessageRecognizer; import com.rekoe.test.client.SimpleClientHandler; /** * @author 科技㊣²º¹³ * Feb 15, 2013 11:44:13 AM * http://www.rekoe.com * QQ:5382211 */ public class Login { public static void main(String[] args) { ClientBootstrap _bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); _bootstrap.setPipelineFactory(new SimpleClientPipelineFactory()); ChannelFuture _future = _bootstrap.connect(new InetSocketAddress("localhost",8166)); _future.getChannel().getCloseFuture().awaitUninterruptibly(); _bootstrap.releaseExternalResources(); } private static class SimpleClientPipelineFactory implements ChannelPipelineFactory { /** 解码器 */ private GameMessageDecoder decoder = new GameMessageDecoder(new SCMessageRecognizer()); /** 编码器 */ private GameMessageEncoder encoder = new GameMessageEncoder(); /** 消息处理器 */ private SimpleClientHandler handler = new SimpleClientHandler(); public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("decoder", decoder); pipeline.addLast("encoder", encoder); pipeline.addLast("handler", handler); return pipeline; } } }
package Add; public class counter { int count; public counter() { count =0; } public int getcount() { return count; } public void setcount() { count = count+1; } }
package tw9a; import java.util.Scanner; public class TW9a { public static void main(String[] args) { String inputline; String []allWords; Scanner in = new Scanner(System.in); System.out.println("Enter a sentence:"); inputline = in.next(); allWords = inputline.split(" "); for(String s : allWords) { if(isPalindrome(s, 0, s.length()-1)) { System.out.println(s.toUpperCase()); System.out.println("It is a Palindrome"); } else { System.out.println(reverseString(s).toLowerCase()); System.out.println("Its is not Palindrome"); } } } public static boolean isPalindrome(String myWord, int s, int t) { if(myWord.charAt(s) == myWord.charAt(t)) { if(s<t) return isPalindrome(myWord, s+1, t-1); else { if(s==t) return true; } } return false; } public static String reverseString(String s) { String rS = ""; for(int i=s.length()-1; i>=0; i--) { rS = rS+s.charAt(i); } return rS; } }
package com.tencent.mm.plugin.hp.tinker; import com.tencent.mm.kernel.g; import com.tencent.mm.model.au; import com.tencent.mm.plugin.boots.a.c; import com.tencent.mm.plugin.hp.b.b; import com.tencent.mm.protocal.c.bsw; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.ao; import com.tencent.mm.sdk.platformtools.x; import com.tinkerboots.sdk.a.a.a; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; public final class f extends a { public final boolean aWu() { return super.aWu(); } public final void E(Map<String, String> map) { super.E(map); b.rl(2); String str = "tinker_id_" + com.tencent.mm.loader.stub.a.baseRevision(); String str2 = com.tencent.mm.loader.stub.a.PATCH_REV == null ? "" : "tinker_id_" + com.tencent.mm.loader.stub.a.PATCH_REV; List linkedList = new LinkedList(); for (String str3 : map.keySet()) { bsw bsw = new bsw(); bsw.aAL = str3; bsw.value = (String) map.get(str3); linkedList.add(bsw); } StringBuilder stringBuilder = new StringBuilder(); Iterator it = linkedList.iterator(); while (it.hasNext()) { bsw bsw2 = (bsw) it.next(); stringBuilder.append(bsw2.aAL).append(":").append(bsw2.value).append("\n"); } x.i("Tinker.TinkerPatchRequestCallback", "checkAvailableUpdate BaseID:%s PatchID:%s config:%s", new Object[]{str, str2, stringBuilder.toString()}); au.DF().a(new com.tencent.mm.plugin.hp.c.a(str, str2, linkedList), 0); } public final void aWv() { super.aWv(); com.tinkerboots.sdk.a.cJC().gy("uin", String.valueOf(((long) com.tencent.mm.kernel.a.Dz()) & 4294967295L)).gy("network", String.valueOf(ao.isWifi(ad.getContext()) ? 3 : 2)); List<com.tencent.mm.plugin.boots.a.a> aua = ((c) g.l(c.class)).aua(); if (aua != null) { for (com.tencent.mm.plugin.boots.a.a aVar : aua) { com.tinkerboots.sdk.a.cJC().gy(Integer.toHexString(aVar.field_key), String.valueOf(aVar.field_dau)); } } } }
/* Purpose: Description: History: 2013/7/10, Created by dennis Copyright (C) 2013 Potix Corporation. All Rights Reserved. */ package org.zkoss.zss.app.ui.dlg; import java.util.Map; import org.zkoss.lang.Strings; import org.zkoss.zk.ui.Executions; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.select.annotation.Listen; import org.zkoss.zk.ui.select.annotation.Wire; import org.zkoss.zul.Textbox; import org.zkoss.zul.Window; /** * * @author dennis * */ public class SaveBookAsCtrl extends DlgCtrlBase{ private static final long serialVersionUID = 1L; public final static String ARG_NAME = "name"; public static final String ON_SAVE = "onSave"; @Wire Textbox bookName; private final static String URI = "~./zssapp/dlg/saveBookAs.zul"; public static void show(EventListener<DlgCallbackEvent> callback,String name) { Map arg = newArg(callback); arg.put(ARG_NAME, name); Window comp = (Window)Executions.createComponents(URI, null, arg); comp.doModal(); return; } @Listen("onClick=#save; onOK=#saveAsDlg") public void onSave(){ if(Strings.isBlank(bookName.getValue())){ bookName.setErrorMessage("empty name is not allowed"); return; } postCallback(ON_SAVE, newMap(newEntry(ARG_NAME, bookName.getValue()))); detach(); } @Listen("onClick=#cancel; onCancel=#saveAsDlg") public void onCancel(){ detach(); } }
package com.project.loginservice.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "bill_details_table") public class BillDetailsEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "bill_details_id") Integer id; @ManyToOne @JoinColumn(name = "bill_id") BillEntity billId; @ManyToOne @JoinColumn(name = "item_id") ItemEntity itemId; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public BillEntity getBillId() { return billId; } public void setBillId(BillEntity billId) { this.billId = billId; } public ItemEntity getItemId() { return itemId; } public void setItemId(ItemEntity itemId) { this.itemId = itemId; } public BillDetailsEntity(Integer id, BillEntity billId, ItemEntity itemId) { super(); this.id = id; this.billId = billId; this.itemId = itemId; } public BillDetailsEntity() { super(); // TODO Auto-generated constructor stub } @Override public String toString() { return "BillDetailsEntity [id=" + id + ", itemId=" + itemId + "]"; } }
package zm.gov.moh.common.submodule.form.model; import com.squareup.moshi.Json; import java.io.Serializable; // Class was added to implement usage of comparison operators public class Expression implements Serializable { @Json(name = "$lt") private String lessThan; String $lte; String $eq; String $ne; String $gt; String $gte; String[] $in; String[] $nin; public String getLessThan() { return lessThan; } public void setLessThan(String lessThan) { this.lessThan = lessThan; } }
package com.tencent.mm.platformtools; public final class g { }
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.servlet.admin; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.Calendar; import java.util.InputMismatchException; import javax.jcr.Node; import javax.jcr.Session; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.jackrabbit.JcrConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.openkm.api.OKMFolder; import com.openkm.api.OKMRepository; import com.openkm.automation.AutomationException; import com.openkm.bean.ContentInfo; import com.openkm.bean.Folder; import com.openkm.bean.Repository; import com.openkm.core.AccessDeniedException; import com.openkm.core.Config; import com.openkm.core.DatabaseException; import com.openkm.core.FileSizeExceededException; import com.openkm.core.ItemExistsException; import com.openkm.core.MimeTypeConfig; import com.openkm.core.PathNotFoundException; import com.openkm.core.RepositoryException; import com.openkm.core.UnsupportedMimeTypeException; import com.openkm.core.UserQuotaExceededException; import com.openkm.core.VirusDetectedException; import com.openkm.extension.core.ExtensionException; import com.openkm.module.jcr.base.BaseFolderModule; import com.openkm.module.jcr.stuff.JCRUtils; import com.openkm.util.Benchmark; import com.openkm.util.FormatUtil; import com.openkm.util.UserActivity; import com.openkm.util.WebUtils; import com.openkm.util.impexp.HTMLInfoDecorator; import com.openkm.util.impexp.ImpExpStats; import com.openkm.util.impexp.RepositoryImporter; /** * Benchmark servlet */ public class BenchmarkServlet extends BaseServlet { private static final long serialVersionUID = 1L; private static Logger log = LoggerFactory.getLogger(BenchmarkServlet.class); private static String BM_FOLDER = "benchmark"; private static final String[][] breadcrumb = new String[][] { new String[] { "experimental.jsp", "Experimental" }, new String[] { "benchmark.jsp", "Benchmark" } }; @Override public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String method = request.getMethod(); if (checkMultipleInstancesAccess(request, response)) { if (method.equals(METHOD_GET)) { doGet(request, response); } else if (method.equals(METHOD_POST)) { doPost(request, response); } } } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String action = request.getParameter("action") != null ? request.getParameter("action") : ""; updateSessionManager(request); if (action.equals("okmImport")) { okmImport(request, response, BM_FOLDER + "_okm_import"); } else if (action.equals("okmCopy")) { okmCopy(request, response); } else if (action.equals("okmApiHighGenerate")) { okmApiHighGenerate(request, response, BM_FOLDER + "_okm_api_high"); } else if (action.equals("okmApiLowGenerate")) { okmApiLowGenerate(request, response, BM_FOLDER + "_okm_api_low"); } else if (action.equals("okmRawGenerate")) { okmRawGenerate(request, response, BM_FOLDER + "_okm_raw"); } else if (action.equals("jcrGenerate")) { jcrGenerate(request, response, BM_FOLDER + "_jcr"); } else { ServletContext sc = getServletContext(); sc.getRequestDispatcher("/admin/benchmark.jsp").forward(request, response); } } /** * Load documents into repository several times */ private void okmImport(HttpServletRequest request, HttpServletResponse response, String base) throws IOException { log.debug("okmImport({}, {}, {})", new Object[] { request, response, base }); String path = WebUtils.getString(request, "param1"); int times = WebUtils.getInt(request, "param2"); PrintWriter out = response.getWriter(); ImpExpStats tStats = new ImpExpStats(); long tBegin = 0, tEnd = 0; response.setContentType(MimeTypeConfig.MIME_HTML); header(out, "OpenKM import documents", breadcrumb); out.flush(); try { File dir = new File(path); int docs = FileUtils.listFiles(dir, null, true).size(); out.println("<b>- Path:</b> " + path + "<br/>"); out.println("<b>- Times:</b> " + times + "<br/>"); out.println("<b>- Documents:</b> " + docs + "<br/>"); out.flush(); Folder rootFld = OKMRepository.getInstance().getRootFolder(null); Folder fld = new Folder(); fld.setPath(rootFld.getPath() + "/" + base); OKMFolder.getInstance().create(null, fld); tBegin = System.currentTimeMillis(); for (int i = 0; i < times; i++) { out.println("<h2>Iteration " + i + "</h2>"); out.flush(); // out.println("<table class=\"results\" width=\"100%\">"); // out.println("<tr><th>#</th><th>Document</th><th>Size</th></tr>"); long begin = System.currentTimeMillis(); fld.setPath(rootFld.getPath() + "/" + base + "/" + i); OKMFolder.getInstance().create(null, fld); ImpExpStats stats = RepositoryImporter.importDocuments(null, dir, fld.getPath(), false, false, false, out, new HTMLInfoDecorator(docs)); long end = System.currentTimeMillis(); tStats.setSize(tStats.getSize() + stats.getSize()); tStats.setFolders(tStats.getFolders() + stats.getFolders()); tStats.setDocuments(tStats.getDocuments() + stats.getDocuments()); // out.println("<table>"); out.println("<br/>"); out.println("<b>Size:</b> " + FormatUtil.formatSize(stats.getSize()) + "<br/>"); out.println("<b>Folders:</b> " + stats.getFolders() + "<br/>"); out.println("<b>Documents:</b> " + stats.getDocuments() + "<br/>"); out.println("<b>Time:</b> " + FormatUtil.formatSeconds(end - begin) + "<br/>"); out.flush(); } tEnd = System.currentTimeMillis(); } catch (PathNotFoundException e) { out.println("<div class=\"warn\">PathNotFoundException: " + e.getMessage() + "</div>"); out.flush(); } catch (ItemExistsException e) { out.println("<div class=\"warn\">ItemExistsException: " + e.getMessage() + "</div>"); out.flush(); } catch (AccessDeniedException e) { out.println("<div class=\"warn\">AccessDeniedException: " + e.getMessage() + "</div>"); out.flush(); } catch (RepositoryException e) { out.println("<div class=\"warn\">RepositoryException: " + e.getMessage() + "</div>"); out.flush(); } catch (DatabaseException e) { out.println("<div class=\"warn\">DatabaseException: " + e.getMessage() + "</div>"); out.flush(); } catch (ExtensionException e) { out.println("<div class=\"warn\">ExtensionException: " + e.getMessage() + "</div>"); out.flush(); } catch (AutomationException e) { out.println("<div class=\"warn\">AutomationException: " + e.getMessage() + "</div>"); out.flush(); } out.println("<hr/>"); out.println("<b>Total size:</b> " + FormatUtil.formatSize(tStats.getSize()) + "<br/>"); out.println("<b>Total folders:</b> " + tStats.getFolders() + "<br/>"); out.println("<b>Total documents:</b> " + tStats.getDocuments() + "<br/>"); out.println("<b>Total time:</b> " + FormatUtil.formatSeconds(tEnd - tBegin) + "<br/>"); footer(out); out.flush(); out.close(); // Activity log UserActivity.log( request.getRemoteUser(), "ADMIN_BENCHMARK_OKM_IMPORT", null, null, "Size: " + FormatUtil.formatSize(tStats.getSize()) + ", Folders: " + tStats.getFolders() + ", Documents: " + tStats.getDocuments() + ", Time: " + FormatUtil.formatSeconds(tEnd - tBegin)); log.debug("okmImport: void"); } /** * Copy documents into repository several times */ private void okmCopy(HttpServletRequest request, HttpServletResponse response) throws IOException { log.debug("okmCopy({}, {})", new Object[] { request, response }); String src = WebUtils.getString(request, "param1"); String dst = WebUtils.getString(request, "param2"); int times = WebUtils.getInt(request, "param3"); PrintWriter out = response.getWriter(); ContentInfo cInfo = new ContentInfo(); long tBegin = 0, tEnd = 0; response.setContentType(MimeTypeConfig.MIME_HTML); header(out, "OpenKM copy documents", breadcrumb); out.flush(); try { cInfo = OKMFolder.getInstance().getContentInfo(null, src); out.println("<b>- Source:</b> " + src + "<br/>"); out.println("<b>- Destination:</b> " + dst + "<br/>"); out.println("<b>- Size:</b> " + FormatUtil.formatSize(cInfo.getSize()) + "<br/>"); out.println("<b>- Mails:</b> " + cInfo.getMails() + "<br/>"); out.println("<b>- Folders:</b> " + cInfo.getFolders() + "<br/>"); out.println("<b>- Documents:</b> " + cInfo.getDocuments() + "<br/>"); out.flush(); tBegin = System.currentTimeMillis(); for (int i = 0; i < times; i++) { out.println("<h2>Iteration " + i + "</h2>"); out.flush(); long begin = System.currentTimeMillis(); Folder fld = new Folder(); fld.setPath(dst + "/" + i); OKMFolder.getInstance().create(null, fld); OKMFolder.getInstance().copy(null, src, fld.getPath()); long end = System.currentTimeMillis(); out.println("<b>Time:</b> " + FormatUtil.formatSeconds(end - begin) + "<br/>"); out.flush(); } tEnd = System.currentTimeMillis(); } catch (PathNotFoundException e) { out.println("<div class=\"warn\">PathNotFoundException: " + e.getMessage() + "</div>"); out.flush(); } catch (ItemExistsException e) { out.println("<div class=\"warn\">ItemExistsException: " + e.getMessage() + "</div>"); out.flush(); } catch (AccessDeniedException e) { out.println("<div class=\"warn\">AccessDeniedException: " + e.getMessage() + "</div>"); out.flush(); } catch (RepositoryException e) { out.println("<div class=\"warn\">RepositoryException: " + e.getMessage() + "</div>"); out.flush(); } catch (DatabaseException e) { out.println("<div class=\"warn\">DatabaseException: " + e.getMessage() + "</div>"); out.flush(); } catch (UserQuotaExceededException e) { out.println("<div class=\"warn\">UserQuotaExceededException: " + e.getMessage() + "</div>"); out.flush(); } catch (ExtensionException e) { out.println("<div class=\"warn\">ExtensionException: " + e.getMessage() + "</div>"); out.flush(); } catch (AutomationException e) { out.println("<div class=\"warn\">AutomationException: " + e.getMessage() + "</div>"); out.flush(); } out.println("<hr/>"); out.println("<b>Total size:</b> " + FormatUtil.formatSize(cInfo.getSize() * times) + "<br/>"); out.println("<b>Total mails:</b> " + cInfo.getMails() * times + "<br/>"); out.println("<b>Total folders:</b> " + cInfo.getFolders() * times + "<br/>"); out.println("<b>Total documents:</b> " + cInfo.getDocuments() * times + "<br/>"); out.println("<b>Total time:</b> " + FormatUtil.formatSeconds(tEnd - tBegin) + "<br/>"); footer(out); out.flush(); out.close(); // Activity log UserActivity.log( request.getRemoteUser(), "ADMIN_BENCHMARK_OKM_COPY", null, null, "Size: " + FormatUtil.formatSize(cInfo.getSize() * times) + ", Folders: " + cInfo.getMails() * times + ", Documents: " + cInfo.getDocuments() * times + ", Time: " + FormatUtil.formatSeconds(tEnd - tBegin)); log.debug("okmCopy: void"); } /** * Generate documents into repository (OpenKM API) */ private void okmApiHighGenerate(HttpServletRequest request, HttpServletResponse response, String base) throws IOException { log.debug("okmApiHighGenerate({}, {}, {})", new Object[] { request, response }); int maxDocuments = WebUtils.getInt(request, "param1"); int maxFolder = WebUtils.getInt(request, "param2"); int maxDepth = WebUtils.getInt(request, "param3"); int maxIterations = WebUtils.getInt(request, "param4"); PrintWriter out = response.getWriter(); PrintWriter results = new PrintWriter(Config.HOME_DIR + File.separator + base + ".csv"); long tBegin = 0, tEnd = 0, pBegin = 0, pEnd = 0; Benchmark bm = null; response.setContentType(MimeTypeConfig.MIME_HTML); header(out, "OpenKM generate documents (API HIGH)", breadcrumb); out.flush(); try { bm = new Benchmark(maxDocuments, maxFolder, maxDepth); out.println("<b>- Documents:</b> " + bm.getMaxDocuments() + "<br/>"); out.println("<b>- Folders:</b> " + bm.getMaxFolders() + "<br/>"); out.println("<b>- Depth:</b> " + bm.getMaxDepth() + "<br/>"); out.println("<b>- Calibration:</b> " + bm.runCalibration() + " ms<br/>"); out.println("<b>- Calculated foldes:</b> " + bm.calculateFolders() + "<br/>"); out.println("<b>- Calculated documents:</b> " + bm.calculateDocuments() + "<br/><br/>"); results.print("\"Date\","); results.print("\"Time\","); results.print("\"Seconds\","); results.print("\"Folders\","); results.print("\"Documents\","); results.print("\"Size\"\n"); results.flush(); tBegin = System.currentTimeMillis(); for (int i = 0; i < maxIterations; i++) { out.println("<h2>Iteration " + i + "</h2>"); out.println("<table class=\"results\" width=\"80%\">"); out.println("<tr><th>Date</th><th>Partial time</th><th>Partial miliseconds</th><th>Total folders</th><th>Total documents</th><th>Total size</th></tr>"); out.flush(); Folder fld = OKMRepository.getInstance().getRootFolder(null); fld.setPath(fld.getPath() + "/" + base); if (!OKMRepository.getInstance().hasNode(null, fld.getPath())) { fld = OKMFolder.getInstance().create(null, fld); } PrintWriter pResults = new PrintWriter(Config.HOME_DIR + File.separator + base + "_" + i + ".csv"); pResults.print("\"Date\","); pResults.print("\"Time\","); pResults.print("\"Seconds\","); pResults.print("\"Folders\","); pResults.print("\"Documents\","); pResults.print("\"Size\"\n"); pResults.flush(); pBegin = System.currentTimeMillis(); bm.okmApiHighPopulate(null, fld, out, pResults); pEnd = System.currentTimeMillis(); pResults.close(); out.println("</table>"); results.print("\"" + FormatUtil.formatDate(Calendar.getInstance()) + "\","); results.print("\"" + FormatUtil.formatSeconds(pEnd - pBegin) + "\","); results.print("\"" + (pEnd - pBegin) + "\","); results.print("\"" + bm.getTotalFolders() + "\","); results.print("\"" + bm.getTotalDocuments() + "\","); results.print("\"" + FormatUtil.formatSize(bm.getTotalSize()) + "\"\n"); results.flush(); out.println("<table class=\"results\" width=\"80%\">"); out.println("<tr><th>Date</th><th>Partial time</th><th>Total folders</th><th>Total documents</th><th>Total size</th></tr>"); out.println("<td>" + FormatUtil.formatDate(Calendar.getInstance()) + "</td>"); out.println("<td>" + FormatUtil.formatSeconds(pEnd - pBegin) + "</td>"); out.println("<td>" + bm.getTotalFolders() + "</td>"); out.println("<td>" + bm.getTotalDocuments() + "</td>"); out.println("<td>" + FormatUtil.formatSize(bm.getTotalSize()) + "</td>"); out.println("</tr>"); out.println("</table>"); out.flush(); } tEnd = System.currentTimeMillis(); } catch (FileNotFoundException e) { out.println("<div class=\"warn\">FileNotFoundException: " + e.getMessage() + "</div>"); out.flush(); } catch (PathNotFoundException e) { out.println("<div class=\"warn\">PathNotFoundException: " + e.getMessage() + "</div>"); out.flush(); } catch (ItemExistsException e) { out.println("<div class=\"warn\">ItemExistsException: " + e.getMessage() + "</div>"); out.flush(); } catch (AccessDeniedException e) { out.println("<div class=\"warn\">AccessDeniedException: " + e.getMessage() + "</div>"); out.flush(); } catch (RepositoryException e) { out.println("<div class=\"warn\">RepositoryException: " + e.getMessage() + "</div>"); out.flush(); } catch (DatabaseException e) { out.println("<div class=\"warn\">DatabaseException: " + e.getMessage() + "</div>"); out.flush(); } catch (UserQuotaExceededException e) { out.println("<div class=\"warn\">UserQuotaExceededException: " + e.getMessage() + "</div>"); out.flush(); } catch (InputMismatchException e) { out.println("<div class=\"warn\">InputMismatchException: " + e.getMessage() + "</div>"); out.flush(); } catch (UnsupportedMimeTypeException e) { out.println("<div class=\"warn\">UnsupportedMimeTypeException: " + e.getMessage() + "</div>"); out.flush(); } catch (FileSizeExceededException e) { out.println("<div class=\"warn\">FileSizeExceededException: " + e.getMessage() + "</div>"); out.flush(); } catch (VirusDetectedException e) { out.println("<div class=\"warn\">VirusDetectedException: " + e.getMessage() + "</div>"); out.flush(); } catch (ExtensionException e) { out.println("<div class=\"warn\">ExtensionException: " + e.getMessage() + "</div>"); out.flush(); } catch (AutomationException e) { out.println("<div class=\"warn\">AutomationException: " + e.getMessage() + "</div>"); out.flush(); } long elapse = tEnd - tBegin; if (bm != null) { out.println("<hr/>"); out.println("<b>Total size:</b> " + FormatUtil.formatSize(bm.getTotalSize()) + "<br/>"); out.println("<b>Total folders:</b> " + bm.getTotalFolders() + "<br/>"); out.println("<b>Total documents:</b> " + bm.getTotalDocuments() + "<br/>"); out.println("<b>Total time:</b> " + FormatUtil.formatSeconds(elapse) + "<br/>"); out.println("<b>Documents per second:</b> " + bm.getTotalDocuments() / (elapse / 1000) + "<br/>"); } footer(out); out.flush(); out.close(); results.close(); // Activity log UserActivity.log(request.getRemoteUser(), "ADMIN_BENCHMARK_OKM_API_HIGH", null, null, "Size: " + FormatUtil.formatSize(bm == null ? 0 : bm.getTotalSize()) + ", Folders: " + (bm == null? 0 : bm.getTotalFolders()) + ", Documents: " + (bm == null? 0 : bm.getTotalDocuments()) + ", Time: " + FormatUtil.formatSeconds(elapse)); log.debug("okmApiHighGenerate: void"); } /** * Generate documents into repository (OpenKM RAW) */ private void okmApiLowGenerate(HttpServletRequest request, HttpServletResponse response, String base) throws IOException { log.debug("okmApiLowGenerate({}, {}, {})", new Object[] { request, response, base }); int maxDocuments = WebUtils.getInt(request, "param1"); int maxFolder = WebUtils.getInt(request, "param2"); int maxDepth = WebUtils.getInt(request, "param3"); int maxIterations = WebUtils.getInt(request, "param4"); PrintWriter out = response.getWriter(); PrintWriter results = new PrintWriter(Config.HOME_DIR + File.separator + base + ".csv"); long tBegin = 0, tEnd = 0, pBegin = 0, pEnd = 0; Benchmark bm = null; Session session = null; response.setContentType(MimeTypeConfig.MIME_HTML); header(out, "OpenKM generate documents (API LOW)", breadcrumb); out.flush(); try { session = JCRUtils.getSession(); bm = new Benchmark(maxDocuments, maxFolder, maxDepth); out.println("<b>- Documents:</b> " + bm.getMaxDocuments() + "<br/>"); out.println("<b>- Folders:</b> " + bm.getMaxFolders() + "<br/>"); out.println("<b>- Depth:</b> " + bm.getMaxDepth() + "<br/>"); out.println("<b>- Calibration:</b> " + bm.runCalibration() + " ms<br/>"); out.println("<b>- Calculated foldes:</b> " + bm.calculateFolders() + "<br/>"); out.println("<b>- Calculated documents:</b> " + bm.calculateDocuments() + "<br/><br/>"); results.print("\"Date\","); results.print("\"Time\","); results.print("\"Seconds\","); results.print("\"Folders\","); results.print("\"Documents\","); results.print("\"Size\"\n"); results.flush(); tBegin = System.currentTimeMillis(); for (int i = 0; i < maxIterations; i++) { out.println("<h2>Iteration " + i + "</h2>"); out.println("<table class=\"results\" width=\"80%\">"); out.println("<tr><th>Date</th><th>Partial time</th><th>Partial miliseconds</th><th>Total folders</th><th>Total documents</th><th>Total size</th></tr>"); out.flush(); Node rootNode = session.getRootNode().getNode(Repository.ROOT); Node baseNode = null; if (rootNode.hasNode(base)) { baseNode = rootNode.getNode(base); } else { baseNode = BaseFolderModule.create(session, rootNode, base); } PrintWriter pResults = new PrintWriter(Config.HOME_DIR + File.separator + base + "_" + i + ".csv"); pResults.print("\"Date\","); pResults.print("\"Time\","); pResults.print("\"Seconds\","); pResults.print("\"Folders\","); pResults.print("\"Documents\","); pResults.print("\"Size\"\n"); pResults.flush(); pBegin = System.currentTimeMillis(); bm.okmApiLowPopulate(session, baseNode, out, pResults); pEnd = System.currentTimeMillis(); pResults.close(); out.println("</table>"); results.print("\"" + FormatUtil.formatDate(Calendar.getInstance()) + "\","); results.print("\"" + FormatUtil.formatSeconds(pEnd - pBegin) + "\","); results.print("\"" + (pEnd - pBegin) + "\","); results.print("\"" + bm.getTotalFolders() + "\","); results.print("\"" + bm.getTotalDocuments() + "\","); results.print("\"" + FormatUtil.formatSize(bm.getTotalSize()) + "\"\n"); results.flush(); out.println("<table class=\"results\" width=\"80%\">"); out.println("<tr><th>Date</th><th>Partial time</th><th>Total folders</th><th>Total documents</th><th>Total size</th></tr>"); out.println("<td>" + FormatUtil.formatDate(Calendar.getInstance()) + "</td>"); out.println("<td>" + FormatUtil.formatSeconds(pEnd - pBegin) + "</td>"); out.println("<td>" + bm.getTotalFolders() + "</td>"); out.println("<td>" + bm.getTotalDocuments() + "</td>"); out.println("<td>" + FormatUtil.formatSize(bm.getTotalSize()) + "</td>"); out.println("</tr>"); out.println("</table>"); out.flush(); } tEnd = System.currentTimeMillis(); } catch (FileNotFoundException e) { out.println("<div class=\"warn\">FileNotFoundException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.PathNotFoundException e) { out.println("<div class=\"warn\">PathNotFoundException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.ItemExistsException e) { out.println("<div class=\"warn\">ItemExistsException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.AccessDeniedException e) { out.println("<div class=\"warn\">AccessDeniedException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.RepositoryException e) { out.println("<div class=\"warn\">RepositoryException: " + e.getMessage() + "</div>"); out.flush(); } catch (InputMismatchException e) { out.println("<div class=\"warn\">InputMismatchException: " + e.getMessage() + "</div>"); out.flush(); } catch (UserQuotaExceededException e) { out.println("<div class=\"warn\">UserQuotaExceededException: " + e.getMessage() + "</div>"); out.flush(); } catch (DatabaseException e) { out.println("<div class=\"warn\">DatabaseException: " + e.getMessage() + "</div>"); out.flush(); } finally { JCRUtils.logout(session); } long elapse = tEnd - tBegin; out.println("<hr/>"); out.println("<b>Total size:</b> " + FormatUtil.formatSize(bm.getTotalSize()) + "<br/>"); out.println("<b>Total folders:</b> " + bm.getTotalFolders() + "<br/>"); out.println("<b>Total documents:</b> " + bm.getTotalDocuments() + "<br/>"); out.println("<b>Total time:</b> " + FormatUtil.formatSeconds(elapse) + "<br/>"); out.println("<b>Documents per second:</b> " + bm.getTotalDocuments() / (elapse / 1000) + "<br/>"); footer(out); out.flush(); out.close(); results.close(); // Activity log UserActivity.log(request.getRemoteUser(), "ADMIN_BENCHMARK_OKM_API_LOW", null, null, "Size: " + FormatUtil.formatSize(bm.getTotalSize()) + ", Folders: " + bm.getTotalFolders() + ", Documents: " + bm.getTotalDocuments() + ", Time: " + FormatUtil.formatSeconds(elapse)); log.debug("okmApiLowGenerate: void"); } /** * Generate documents into repository (OpenKM RAW) */ private void okmRawGenerate(HttpServletRequest request, HttpServletResponse response, String base) throws IOException { log.debug("okmRawGenerate({}, {}, {})", new Object[] { request, response, base }); int maxDocuments = WebUtils.getInt(request, "param1"); int maxFolder = WebUtils.getInt(request, "param2"); int maxDepth = WebUtils.getInt(request, "param3"); int maxIterations = WebUtils.getInt(request, "param4"); PrintWriter out = response.getWriter(); PrintWriter results = new PrintWriter(Config.HOME_DIR + File.separator + base + ".csv"); long tBegin = 0, tEnd = 0, pBegin = 0, pEnd = 0; Benchmark bm = null; Session session = null; response.setContentType(MimeTypeConfig.MIME_HTML); header(out, "OpenKM generate documents (RAW)", breadcrumb); out.flush(); try { session = JCRUtils.getSession(); bm = new Benchmark(maxDocuments, maxFolder, maxDepth); out.println("<b>- Documents:</b> " + bm.getMaxDocuments() + "<br/>"); out.println("<b>- Folders:</b> " + bm.getMaxFolders() + "<br/>"); out.println("<b>- Depth:</b> " + bm.getMaxDepth() + "<br/>"); out.println("<b>- Calibration:</b> " + bm.runCalibration() + " ms<br/>"); out.println("<b>- Calculated foldes:</b> " + bm.calculateFolders() + "<br/>"); out.println("<b>- Calculated documents:</b> " + bm.calculateDocuments() + "<br/><br/>"); results.print("\"Date\","); results.print("\"Time\","); results.print("\"Seconds\","); results.print("\"Folders\","); results.print("\"Documents\","); results.print("\"Size\"\n"); results.flush(); tBegin = System.currentTimeMillis(); for (int i = 0; i < maxIterations; i++) { out.println("<h2>Iteration " + i + "</h2>"); out.println("<table class=\"results\" width=\"80%\">"); out.println("<tr><th>Date</th><th>Partial time</th><th>Partial miliseconds</th><th>Total folders</th><th>Total documents</th><th>Total size</th></tr>"); out.flush(); Node rootNode = session.getRootNode().getNode(Repository.ROOT); Node baseNode = null; if (rootNode.hasNode(base)) { baseNode = rootNode.getNode(base); } else { baseNode = BaseFolderModule.create(session, rootNode, base); } PrintWriter pResults = new PrintWriter(Config.HOME_DIR + File.separator + base + "_" + i + ".csv"); pResults.print("\"Date\","); pResults.print("\"Time\","); pResults.print("\"Seconds\","); pResults.print("\"Folders\","); pResults.print("\"Documents\","); pResults.print("\"Size\"\n"); pResults.flush(); pBegin = System.currentTimeMillis(); bm.okmRawPopulate(session, baseNode, out, pResults); pEnd = System.currentTimeMillis(); pResults.close(); out.println("</table>"); results.print("\"" + FormatUtil.formatDate(Calendar.getInstance()) + "\","); results.print("\"" + FormatUtil.formatSeconds(pEnd - pBegin) + "\","); results.print("\"" + (pEnd - pBegin) + "\","); results.print("\"" + bm.getTotalFolders() + "\","); results.print("\"" + bm.getTotalDocuments() + "\","); results.print("\"" + FormatUtil.formatSize(bm.getTotalSize()) + "\"\n"); results.flush(); out.println("<table class=\"results\" width=\"80%\">"); out.println("<tr><th>Date</th><th>Partial time</th><th>Total folders</th><th>Total documents</th><th>Total size</th></tr>"); out.println("<td>" + FormatUtil.formatDate(Calendar.getInstance()) + "</td>"); out.println("<td>" + FormatUtil.formatSeconds(pEnd - pBegin) + "</td>"); out.println("<td>" + bm.getTotalFolders() + "</td>"); out.println("<td>" + bm.getTotalDocuments() + "</td>"); out.println("<td>" + FormatUtil.formatSize(bm.getTotalSize()) + "</td>"); out.println("</tr>"); out.println("</table>"); out.flush(); } tEnd = System.currentTimeMillis(); } catch (FileNotFoundException e) { out.println("<div class=\"warn\">FileNotFoundException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.PathNotFoundException e) { out.println("<div class=\"warn\">PathNotFoundException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.ItemExistsException e) { out.println("<div class=\"warn\">ItemExistsException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.AccessDeniedException e) { out.println("<div class=\"warn\">AccessDeniedException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.RepositoryException e) { out.println("<div class=\"warn\">RepositoryException: " + e.getMessage() + "</div>"); out.flush(); } catch (InputMismatchException e) { out.println("<div class=\"warn\">InputMismatchException: " + e.getMessage() + "</div>"); out.flush(); } catch (DatabaseException e) { out.println("<div class=\"warn\">DatabaseException: " + e.getMessage() + "</div>"); out.flush(); } finally { JCRUtils.logout(session); } long elapse = tEnd - tBegin; out.println("<hr/>"); out.println("<b>Total size:</b> " + FormatUtil.formatSize(bm.getTotalSize()) + "<br/>"); out.println("<b>Total folders:</b> " + bm.getTotalFolders() + "<br/>"); out.println("<b>Total documents:</b> " + bm.getTotalDocuments() + "<br/>"); out.println("<b>Total time:</b> " + FormatUtil.formatSeconds(elapse) + "<br/>"); out.println("<b>Documents per second:</b> " + bm.getTotalDocuments() / (elapse / 1000) + "<br/>"); footer(out); out.flush(); out.close(); results.close(); // Activity log UserActivity.log(request.getRemoteUser(), "ADMIN_BENCHMARK_OKM_RAW", null, null, "Size: " + FormatUtil.formatSize(bm.getTotalSize()) + ", Folders: " + bm.getTotalFolders() + ", Documents: " + bm.getTotalDocuments() + ", Time: " + FormatUtil.formatSeconds(elapse)); log.debug("okmRawGenerate: void"); } /** * Generate documents into repository (Jackrabbit) */ private void jcrGenerate(HttpServletRequest request, HttpServletResponse response, String base) throws IOException { log.debug("jcrGenerate({}, {}, {})", new Object[] { request, response, base }); int maxDocuments = WebUtils.getInt(request, "param1"); int maxFolder = WebUtils.getInt(request, "param2"); int maxDepth = WebUtils.getInt(request, "param3"); int maxIterations = WebUtils.getInt(request, "param4"); PrintWriter out = response.getWriter(); PrintWriter results = new PrintWriter(Config.HOME_DIR + File.separator + base + ".csv"); long tBegin = 0, tEnd = 0, pBegin = 0, pEnd = 0; Benchmark bm = null; Session session = null; response.setContentType(MimeTypeConfig.MIME_HTML); header(out, "Jackrabbit generate documents", breadcrumb); out.flush(); try { session = JCRUtils.getSession(); bm = new Benchmark(maxDocuments, maxFolder, maxDepth); out.println("<b>- Documents:</b> " + bm.getMaxDocuments() + "<br/>"); out.println("<b>- Folders:</b> " + bm.getMaxFolders() + "<br/>"); out.println("<b>- Depth:</b> " + bm.getMaxDepth() + "<br/>"); out.println("<b>- Calibration:</b> " + bm.runCalibration() + " ms<br/>"); out.println("<b>- Calculated foldes:</b> " + bm.calculateFolders() + "<br/>"); out.println("<b>- Calculated documents:</b> " + bm.calculateDocuments() + "<br/><br/>"); results.print("\"Date\","); results.print("\"Time\","); results.print("\"Seconds\","); results.print("\"Folders\","); results.print("\"Documents\","); results.print("\"Size\"\n"); results.flush(); tBegin = System.currentTimeMillis(); for (int i = 0; i < maxIterations; i++) { out.println("<h2>Iteration " + i + "</h2>"); out.println("<table class=\"results\" width=\"80%\">"); out.println("<tr><th>Date</th><th>Partial time</th><th>Partial miliseconds</th><th>Total folders</th><th>Total documents</th><th>Total size</th></tr>"); out.flush(); Node rootNode = session.getRootNode().getNode(Repository.ROOT); Node baseNode = null; if (rootNode.hasNode(base)) { baseNode = rootNode.getNode(base); } else { baseNode = rootNode.addNode(base, JcrConstants.NT_FOLDER); rootNode.save(); } PrintWriter pResults = new PrintWriter(Config.HOME_DIR + File.separator + base + "_" + i + ".csv"); pResults.print("\"Date\","); pResults.print("\"Time\","); pResults.print("\"Seconds\","); pResults.print("\"Folders\","); pResults.print("\"Documents\","); pResults.print("\"Size\"\n"); pResults.flush(); pBegin = System.currentTimeMillis(); bm.jcrPopulate(session, baseNode, out, pResults); pEnd = System.currentTimeMillis(); pResults.close(); out.println("</table>"); results.print("\"" + FormatUtil.formatDate(Calendar.getInstance()) + "\","); results.print("\"" + FormatUtil.formatSeconds(pEnd - pBegin) + "\","); results.print("\"" + (pEnd - pBegin) + "\","); results.print("\"" + bm.getTotalFolders() + "\","); results.print("\"" + bm.getTotalDocuments() + "\","); results.print("\"" + FormatUtil.formatSize(bm.getTotalSize()) + "\"\n"); results.flush(); out.println("<table class=\"results\" width=\"80%\">"); out.println("<tr><th>Date</th><th>Partial time</th><th>Total folders</th><th>Total documents</th><th>Total size</th></tr>"); out.println("<td>" + FormatUtil.formatDate(Calendar.getInstance()) + "</td>"); out.println("<td>" + FormatUtil.formatSeconds(pEnd - pBegin) + "</td>"); out.println("<td>" + bm.getTotalFolders() + "</td>"); out.println("<td>" + bm.getTotalDocuments() + "</td>"); out.println("<td>" + FormatUtil.formatSize(bm.getTotalSize()) + "</td>"); out.println("</tr>"); out.println("</table>"); out.flush(); } tEnd = System.currentTimeMillis(); } catch (FileNotFoundException e) { out.println("<div class=\"warn\">FileNotFoundException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.PathNotFoundException e) { out.println("<div class=\"warn\">PathNotFoundException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.ItemExistsException e) { out.println("<div class=\"warn\">ItemExistsException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.AccessDeniedException e) { out.println("<div class=\"warn\">AccessDeniedException: " + e.getMessage() + "</div>"); out.flush(); } catch (javax.jcr.RepositoryException e) { out.println("<div class=\"warn\">RepositoryException: " + e.getMessage() + "</div>"); out.flush(); } catch (InputMismatchException e) { out.println("<div class=\"warn\">InputMismatchException: " + e.getMessage() + "</div>"); out.flush(); } catch (DatabaseException e) { out.println("<div class=\"warn\">DatabaseException: " + e.getMessage() + "</div>"); out.flush(); } finally { JCRUtils.logout(session); } long elapse = tEnd - tBegin; out.println("<hr/>"); out.println("<b>Total size:</b> " + FormatUtil.formatSize(bm.getTotalSize()) + "<br/>"); out.println("<b>Total folders:</b> " + bm.getTotalFolders() + "<br/>"); out.println("<b>Total documents:</b> " + bm.getTotalDocuments() + "<br/>"); out.println("<b>Total time:</b> " + FormatUtil.formatSeconds(elapse) + "<br/>"); out.println("<b>Documents per second:</b> " + bm.getTotalDocuments() / (elapse / 1000) + "<br/>"); footer(out); out.flush(); out.close(); results.close(); // Activity log UserActivity.log(request.getRemoteUser(), "ADMIN_BENCHMARK_JCR", null, null, "Size: " + FormatUtil.formatSize(bm.getTotalSize()) + ", Folders: " + bm.getTotalFolders() + ", Documents: " + bm.getTotalDocuments() + ", Time: " + FormatUtil.formatSeconds(elapse)); log.debug("jcrGenerate: void"); } }
package com.tt.miniapp.video.plugin.base; public interface IVideoPlugin { IVideoPluginHost getHost(); int getPluginType(); boolean handleVideoEvent(IVideoPluginEvent paramIVideoPluginEvent); void onRegister(IVideoPluginHost paramIVideoPluginHost); void onUnregister(IVideoPluginHost paramIVideoPluginHost); void setHost(IVideoPluginHost paramIVideoPluginHost); } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\video\plugin\base\IVideoPlugin.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
package lambdas; public class Calculator { interface IntegerMath{ int operation(int a, int b); } public int operateBinary(int a, int b, IntegerMath op) { return op.operation(a, b); } public static void main(String[] args) { // TODO Auto-generated method stub Calculator myCalc = new Calculator(); IntegerMath addition = (a, b) -> a + b; IntegerMath substraction = (a, b) -> a - b; System.out.println("Addition: " + myCalc.operateBinary(20, 10, addition)); System.out.println("Subtraction: " + myCalc.operateBinary(20, 10, substraction)); } }
package com.tencent.mm.plugin.shake.ui; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import com.tencent.mm.R; import com.tencent.mm.ui.base.h; class ShakeSayHiListUI$3 implements OnMenuItemClickListener { final /* synthetic */ ShakeSayHiListUI nbq; ShakeSayHiListUI$3(ShakeSayHiListUI shakeSayHiListUI) { this.nbq = shakeSayHiListUI; } public final boolean onMenuItemClick(MenuItem menuItem) { h.a(this.nbq.mController.tml, true, this.nbq.getString(R.l.say_hi_clean_all_title), "", this.nbq.getString(R.l.say_hi_clean_all_btn), this.nbq.getString(R.l.app_cancel), new 1(this), new 2(this)); return true; } }
package cn.wycclub.service; import cn.wycclub.dao.mapper.ProductInfoMapper; import cn.wycclub.dao.po.PageSelect; import cn.wycclub.dao.po.ProductInfo; import cn.wycclub.dao.po.ProductInfoExample; import cn.wycclub.dto.PageInputByProduct; import cn.wycclub.dto.PageResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * 商品业务逻辑层 * * @author WuYuchen * @create 2018-02-14 14:28 **/ @Service public class BusinessProductServiceImpl implements BusinessProductService { @Autowired private ProductInfoMapper productInfoMapper; /** * 获取商品分页 * */ @Override public PageResult<ProductInfo> getProductPage(PageInputByProduct pageInputByProduct) { PageResult<ProductInfo> pageResult = new PageResult<>(); ProductInfoExample example = new ProductInfoExample(); ProductInfoExample.Criteria criteria = example.createCriteria(); //判断分页条件中是否包含品牌信息 String brand = pageInputByProduct.getBrand(); if (brand != null && !"".equals(brand)) { criteria.andBrandEqualTo(brand); } //分页查询信息 PageSelect pageSelect = new PageSelect(); pageSelect.setOffset(pageInputByProduct.getStartIndex()); pageSelect.setLimit(pageInputByProduct.getPageSize()); example.setPageSelect(pageSelect); //返回分页信息整理 pageResult.setList(productInfoMapper.selectByExample(example)); pageResult.setCurrentPage(pageInputByProduct.getCurrentPage()); pageResult.setPageSize(pageInputByProduct.getPageSize()); pageResult.setTotalRecord(productInfoMapper.countByExample(example)); return pageResult; } @Override public ProductInfo getProductById(Integer id) { return productInfoMapper.selectByPrimaryKey(id); } @Override public List<ProductInfo> getProductByIndexPage(Integer count) { return productInfoMapper.selectProductByRadom(count); } @Override public List<String> getAllBrand() { return productInfoMapper.selectBrund(); } }
package fr.cp.translate.api; import java.io.Serializable; public class Translate implements Serializable { private static final long serialVersionUID = 1L; private long id; private String comment; public Translate(){ } public Translate(String comment) { super(); this.comment = comment; } public String getComment() { return comment; } public long getId() { return id; } public void setId(long getTranslateId) { this.id = getTranslateId; } }
package com.nibado.fastcollections.lookup.trove; import com.nibado.fastcollections.lookup.IntLookup; import gnu.trove.set.hash.TIntHashSet; import java.util.List; public class TroveHashSetIntLookup implements IntLookup { private final TIntHashSet set; public TroveHashSetIntLookup(List<Integer> data, float loadFactor) { set = new TIntHashSet(data.size(), loadFactor); set.addAll(data); } @Override public boolean contains(int value) { return set.contains(value); } }
public class PPM { public static void main(String[] args) { int x = 200; int y = 100; printPPMHeader(x, y); Hitable[] lst = new Hitable[2]; lst[0] = new Sphere(new Vector(0, 0, -1), 0.5f); lst[1] = new Sphere(new Vector(0, -100.5f, -1), 100); Hitable world = new HitableList(lst); printImage(x, y, world); } public static void printPPMHeader(int length, int height) { String header = String.format("P3\n%d %d\n255\n", length, height); System.out.println(header); } public static void printImage(int length, int height, Hitable world) { Vector origin = new Vector(0, 0, 0); Vector horizontal = new Vector(4, 0, 0); Vector vertical = new Vector(0, 2, 0); Vector lower_left_corner = new Vector(-2, -1, -1); for (int j = height - 1; j >= 0; j--) { for (int i = 0; i < length; i++) { Vector x_offset = horizontal.mul((float) i / length); Vector y_offset = vertical.mul((float) j / height); Vector pixel_position = lower_left_corner.add(x_offset).add(y_offset); Ray r = new Ray(origin, pixel_position); Color col = color(r, world); int r_val = Math.round(255 * col.r); int g_val = Math.round(255 * col.g); int b_val = Math.round(255 * col.b); String pixel = String.format("%d %d %d\n", r_val, g_val, b_val); System.out.println(pixel); } } } public static void printImage1(int length, int height) { for (int j = height - 1; j >= 0; j--) { for (int i = 0; i < length; i++) { float r = (float) i / length; // percentage of red increases from left to right float g = (float) j / height; // percentage of green decreases from top to bottom float b = (float) 0.2; // percentage of blue stays constant int r_val = Math.round(255 * r); int g_val = Math.round(255 * g); int b_val = Math.round(255 * b); String pixel = String.format("%d %d %d\n", r_val, g_val, b_val); System.out.println(pixel); } } } public static Color color(Ray r, Hitable world) { HitRecord rec = new HitRecord(); if (world.hit(r, 0, 2, rec)) { Color col = new Color(rec.normal.x + 1, rec.normal.y + 1, rec.normal.z + 1); return col.mul(0.5f); } else { Vector unit_direction = r.direction.unitVector(); float t = 0.5f * (unit_direction.y + 1); // t depends on the y of the unit vector Color white = new Color(1, 1, 1); Color blue = new Color(0.5f, 0.7f, 1); return white.mul(1-t).add(blue.mul(t)); // large t means more blue, less white } } }
package com.tencent.mm.plugin.monitor; import com.tencent.mm.sdk.platformtools.x; class b$10 implements Runnable { final /* synthetic */ b lsb; b$10(b bVar) { this.lsb = bVar; } public final void run() { x.i("MicroMsg.SubCoreBaseMonitor", "summerhv reportHeavyUserRunnable run"); b.h(this.lsb); } }
public class LinkedListDeque<Blorp> { public class Node{ public Blorp head; public Node next; public Node prev; public Node(Node p, Blorp h, Node n) { prev = p; head = h; next = n; } } private Node sentinel; private int size; public LinkedListDeque() { size = 0; sentinel = new Node(null,null,null); sentinel.prev = sentinel; sentinel.next = sentinel; } public Blorp getRecursive(int index) { return null; } public void addFirst(Blorp i) { //Node oldFirst = sentinel.next; /*cant create (maybe) first node when there is no nodes (cant retain first node)*/ Node firstNode = new Node(sentinel,i,sentinel.next); sentinel.next = firstNode; //sentinel.prev = firstNode; if (size>1) { sentinel.next.next.prev = firstNode; } size += 1; } // maybe the bad guy is this public void addLast (Blorp i) { sentinel.prev.next = new Node(sentinel.prev,i,sentinel); sentinel.prev = sentinel.prev.next; size += 1; } public boolean isEmpty() { if (size == 0) { return true; } return false; } public int size() { return size; } public void printDeque() { Node beginning = sentinel.next; while (beginning != sentinel) { System.out.print(beginning.head + " "); beginning = beginning.next; } } //} public Blorp removeFirst() { if (sentinel.next == sentinel) { return null; } Node first = sentinel.next; first.next.prev = sentinel; sentinel.next = first.next;//.next; size -= 1; return first.head; } public Blorp removeLast() { Node last = sentinel.prev; last.prev.next = sentinel; sentinel.prev = last.prev; size -= 1; return last.head; } public Blorp get(int index) { if (index == 0) { return sentinel.next.head; } Node beginning=sentinel.next; while (index != 0) { beginning = beginning.next; index -= 1; } return beginning.head; } }
package com.company; /** * Created by Marina on 24.01.16. */ public class Sea2 { public static void main(String[] args) { char[][] Tab = { {'0', '0', '0', '0','0', '0','0', '0','0', '0'}, {'0', '*', '0', '*', '*', '0', '*','0', '0', '*'} }; for (int i = 0; i < 2; i++) { for (int j = 0; j < 10; j++) { System.out.print(Tab[i][j] + "\t"); } System.out.println(); } } }
package pkgPolymorphism; import java.util.*; public class ShapeTest { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); double radius=0.0,length=0.0,width=0.0,side=0.0; boolean filled=false; String color=""; System.out.println("Enter radius,color and filled for circle:"); radius=sc.nextDouble(); color=sc.next(); filled=sc.nextBoolean(); Circle c=new Circle(radius,color,filled); System.out.println("For circle:"); System.out.println("Area="+c.getArea()+" Perimeter="+c.getPerimeter()); System.out.println("Details="+c.toString()); System.out.println("Enter width,length,color and filled for Rectangle:"); width=sc.nextDouble(); length=sc.nextDouble(); color=sc.next(); filled=sc.nextBoolean(); Rectangle r=new Rectangle(width,length,color,filled); System.out.println("For Rectangle:"); System.out.println("Area="+r.getArea()+" Perimeter="+r.getPerimeter()); System.out.println("Details="+r.toString()); System.out.println("Enter side,color and filled for Sqaure:"); side=sc.nextDouble(); color=sc.next(); filled=sc.nextBoolean(); sc.close(); Square s=new Square(side,color,filled); System.out.println("For Sqaure:"); System.out.println("Details="+s.toString()); } }
package exercise1.person; import org.junit.jupiter.api.*; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class EmployeeTest { @AfterAll static void done() { Logger log = LoggerFactory.getLogger(EmployeeTest.class); log.info("@AfterAll - executed after all test methods."); } @Test public void testEmployeeGetSalaryCheckCorrectResultSalary(){ Manager manager = new Manager("managername","manager", 300, 5, null); Employee employee = new Employee("emp", "employee", 200, 1, manager); double tmpSalary = employee.getSalary(); assertEquals(tmpSalary, 200); } }
package java00; import java.util.Scanner; public class java0053 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scn = new Scanner(System.in); int a = (int) (Math.random() * 100 + 1); while (true) { System.out.println("Input Value:"); int val = scn.nextInt(); if (val == a) { System.out.println("True"); break; } else if (val > a) { System.out.println("Too big"); } else if (val < a) { System.out.println("Too small"); } } } }
package com.lupan.javaStudy.chapter16; /** * TODO 取钱线程 * * @author lupan * @version 2016/1/25 0025 */ public class TakeThread implements Runnable{ //单次取款额度 private final int TAKEA_MOUNT = 800; //账户 private Account account; public TakeThread(){ } public TakeThread(Account account){ this.account = account; } public Account getAccount() { return account; } public void setAccount(Account account) { this.account = account; } @Override public void run(){ // synchronized (account){ // if(account.getBalance()-TAKEA_MOUNT < 0){ // System.out.println(Thread.currentThread().getName()+":余额不足,不能取钱!"); // }else{ // // try { // Thread.sleep(1); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // account.setBalance(account.getBalance() - TAKEA_MOUNT); // // System.out.println(Thread.currentThread().getName()+":取钱成功,余额为:"+account.getBalance()); // // } // } this.account.take(); } }
package jpa.project.service; import jpa.project.advide.exception.CResourceNotExistException; import jpa.project.advide.exception.CUserNotFoundException; import jpa.project.entity.*; import jpa.project.model.dto.member.MemberRegisterRequestDto; import jpa.project.model.dto.registedShoes.RegistedShoesDto; import jpa.project.repository.member.MemberRepository; import jpa.project.repository.registedShoes.RegistedShoesRepository; import jpa.project.repository.shoesInSize.ShoesInSizeRepository; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Slice; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @SpringBootTest @Transactional class RegistedShoesServiceTest { @Autowired RegistedShoesService registedShoesService; @Autowired ShoesInSizeRepository shoesInSizeRepository; @Autowired MemberRepository memberRepository; @Autowired MemberService memberService; @Autowired SignService signService; @Autowired RegistedShoesRepository registedShoesRepository; @Autowired EntityManager em; @Test public void 입찰가격변경()throws Exception{ //given MemberRegisterRequestDto member=new MemberRegisterRequestDto("s","ss","zzz"); signService.signup(member); Member member1 = memberRepository.findByUsername("s").orElseThrow(CUserNotFoundException::new); Brand asics = Brand.createBrand("asics", "1111"); em.persist(asics); ShoesSize shoesSize = ShoesSize.createShoesSize("7"); em.persist(shoesSize); ShoesInSize shoesInSize = ShoesInSize.createShoesInSize(shoesSize); Shoes zzz = Shoes.createShoes("zzz", asics, shoesInSize); em.persist(zzz); RegistedShoesDto registedShoesDto = registedShoesService.registShoes(member1.getUsername(), shoesInSize.getId(), 9, TradeStatus.SELL); RegistedShoesDto registedShoesDto1 = registedShoesService.registShoes(member1.getUsername(), shoesInSize.getId(), 11, TradeStatus.SELL); RegistedShoesDto registedShoesDto2 = registedShoesService.registShoes(member1.getUsername(), shoesInSize.getId(), 10, TradeStatus.SELL); em.flush(); em.clear(); RegistedShoes registedShoes = registedShoesRepository.findById(registedShoesDto.getId()).orElseThrow(CResourceNotExistException::new); // //when registedShoesService.update(registedShoes.getId(),member1.getUsername(),5); //then assertThat(registedShoes.getPrice()).isEqualTo(5); assertThat(registedShoes.getShoesInSize().getShoes().getPrice()).isEqualTo(5); // } @Test public void 입찰정보조회()throws Exception{ MemberRegisterRequestDto member=new MemberRegisterRequestDto("s","ss","zzz"); signService.signup(member); Member member1 = memberRepository.findByUsername("s").orElseThrow(CUserNotFoundException::new); Brand asics = Brand.createBrand("asics", "1111"); em.persist(asics); ShoesSize shoesSize = ShoesSize.createShoesSize("7"); em.persist(shoesSize); ShoesInSize shoesInSize = ShoesInSize.createShoesInSize(shoesSize); Shoes zzz = Shoes.createShoes("zzz", asics, shoesInSize); em.persist(zzz); RegistedShoesDto registedShoesDto = registedShoesService.registShoes(member1.getUsername(), shoesInSize.getId(), 9, TradeStatus.SELL); RegistedShoesDto registedShoesDto1 = registedShoesService.registShoes(member1.getUsername(), shoesInSize.getId(), 11, TradeStatus.SELL); RegistedShoesDto registedShoesDto2 = registedShoesService.registShoes(member1.getUsername(), shoesInSize.getId(), 10, TradeStatus.BUY); em.flush(); em.clear(); //when Slice<RegistedShoesDto> registedShoesByTradeStatus = registedShoesService.findRegistedShoesByTradeStatus(member1.getId(), null, TradeStatus.BUY, 1); Slice<RegistedShoesDto> registedShoesByTradeStatusS = registedShoesService.findRegistedShoesByTradeStatus(member1.getId(), null, TradeStatus.SELL, 1); Long last = registedShoesByTradeStatusS.getContent().get(0).getId(); Slice<RegistedShoesDto> registedShoesByTradeStatus1 = registedShoesService.findRegistedShoesByTradeStatus(member1.getId(), last, TradeStatus.SELL, 1); //then assertThat(registedShoesByTradeStatus.hasNext()).isFalse(); assertThat(registedShoesByTradeStatus.getSize()).isEqualTo(1); assertThat(registedShoesByTradeStatusS.hasNext()).isTrue() ; assertThat(registedShoesByTradeStatusS.getSize()).isEqualTo(1); assertThat(registedShoesByTradeStatus1.getSize()).isEqualTo(1); assertThat(registedShoesByTradeStatus1.hasNext()).isFalse(); } @Test public void 입찰삭제()throws Exception{ MemberRegisterRequestDto member=new MemberRegisterRequestDto("s","ss","zzz"); signService.signup(member); Member member1 = memberRepository.findByUsername("s").orElseThrow(CUserNotFoundException::new); Brand asics = Brand.createBrand("asics", "1111"); em.persist(asics); ShoesSize shoesSize = ShoesSize.createShoesSize("7"); em.persist(shoesSize); ShoesInSize shoesInSize = ShoesInSize.createShoesInSize(shoesSize); Shoes zzz = Shoes.createShoes("zzz", asics, shoesInSize); em.persist(zzz); RegistedShoesDto registedShoesDto = registedShoesService.registShoes(member1.getUsername(), shoesInSize.getId(), 9, TradeStatus.SELL); RegistedShoesDto registedShoesDto1 = registedShoesService.registShoes(member1.getUsername(), shoesInSize.getId(), 11, TradeStatus.SELL); RegistedShoesDto registedShoesDto2 = registedShoesService.registShoes(member1.getUsername(), shoesInSize.getId(), 10, TradeStatus.SELL); //when registedShoesService.delete(registedShoesDto.getId(),member.getUsername()); RegistedShoes registedShoes = registedShoesRepository.findById(registedShoesDto1.getId()).orElseThrow(CResourceNotExistException::new); //then assertThat(registedShoes.getShoesInSize().getShoes().getPrice()).isEqualTo(10); assertThatThrownBy(() -> registedShoesRepository.findById(registedShoesDto.getId()).orElseThrow(CResourceNotExistException::new)) .isInstanceOf(CResourceNotExistException.class); } }
import java.util.ArrayList; public class Forecast implements Display { private ArrayList<Data> dataArrayList = new ArrayList<>(); @Override public void update(ArrayList<Data> dataArrayList) { this.dataArrayList = dataArrayList; this.display(); } private void display() { int end = dataArrayList.size() - 1; double humidity = dataArrayList.get(end).getHumidity(); if (humidity > 0.8) { System.out.println("Forecast rain."); } else if (humidity < 0.2) { System.out.println("Forecast sunny."); } else { System.out.println("Forecast cloudy."); } } @Override public String getType() { return "Forecast"; } }
package com.tencent.mm.plugin.webview.ui.tools.jsapi; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Parcelable; import com.tencent.mm.R; import com.tencent.mm.pluginsdk.ui.tools.AppChooserUI; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.MMActivity; import com.tencent.mm.ui.MMActivity.a; import com.tencent.tmassistantsdk.storage.table.DownloadSettingTable$Columns; import java.lang.ref.WeakReference; import java.util.ArrayList; public final class j implements a { WeakReference<Context> YC; com.tencent.mm.modelgeo.c dMm = null; com.tencent.mm.modelgeo.b kHU = null; int pSW; boolean qkm = false; int qkn; e qko; e qkp; String qkq; d qkr; com.tencent.mm.modelgeo.b.a qks = null; com.tencent.mm.modelgeo.b.a qkt = null; com.tencent.mm.modelgeo.a.a qku = null; final Runnable qkv = new 1(this); private static final class b extends f { private b() { super((byte) 0); } /* synthetic */ b(byte b) { this(); } protected final void a(Context context, e eVar, e eVar2, String str) { if (context == null) { super.a(context, eVar, eVar2, str); return; } String str2 = "android.intent.action.VIEW"; Intent intent = new Intent(str2, Uri.parse(String.format("androidamap://navi?sourceApplication=%s&lat=%f&lon=%f&dev=1&style=2", new Object[]{"MicroMessager", Double.valueOf(eVar2.latitude), Double.valueOf(eVar2.longitude)}))); intent.addCategory("android.intent.category.DEFAULT"); intent.setPackage(com.tencent.mm.pluginsdk.model.a.a.qyL.getPackage()); context.startActivity(intent); } protected final String getPackageName() { return com.tencent.mm.pluginsdk.model.a.a.qyL.getPackage(); } } private static final class c extends f { private c() { super((byte) 0); } /* synthetic */ c(byte b) { this(); } protected final void a(Context context, e eVar, e eVar2, String str) { if (context == null) { super.a(context, eVar, eVar2, str); return; } String format = String.format("http://maps.google.com/maps?f=d&daddr=%f,%f", new Object[]{Double.valueOf(eVar2.latitude), Double.valueOf(eVar2.longitude)}); if (eVar != null) { format = format + String.format("&saddr=%f,%f", new Object[]{Double.valueOf(eVar.latitude), Double.valueOf(eVar.longitude)}); } Intent intent = new Intent("android.intent.action.VIEW", Uri.parse(format)); intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity"); context.startActivity(intent); } protected final String getPackageName() { return com.tencent.mm.pluginsdk.model.a.a.qyI.getPackage(); } } interface d { void Bf(int i); void Bg(int i); void pT(int i); void uX(int i); } private static final class e { double latitude; double longitude; String qky; /* synthetic */ e(double d, double d2, byte b) { this(d, d2); } private e(double d, double d2) { this.latitude = d; this.longitude = d2; this.qky = null; } } public final void b(int i, int i2, Intent intent) { Context context = (Context) this.YC.get(); if (!(this.qkr == null || context == null)) { if (!this.qkm) { x.e("MicroMsg.OpenMapNavigator", "onActivityResult called without msgId attached..."); } else if (i != 33) { x.e("MicroMsg.OpenMapNavigator", "onActivityResult, mismatched request_code = %d", new Object[]{Integer.valueOf(i)}); this.qkr.pT(this.pSW); } else if (i2 == 4097 || i2 == 0) { this.qkr.Bf(this.pSW); } else if (i2 == -1) { String stringExtra = intent.getStringExtra("selectpkg"); if (bi.oW(stringExtra)) { x.e("MicroMsg.OpenMapNavigator", "onActivityResult, get null packageName"); this.qkr.pT(this.pSW); } else { f cVar = com.tencent.mm.pluginsdk.model.a.a.qyI.getPackage().equals(stringExtra) ? new c() : com.tencent.mm.pluginsdk.model.a.a.qyK.getPackage().equals(stringExtra) ? new a((byte) 0) : com.tencent.mm.pluginsdk.model.a.a.qyJ.getPackage().equals(stringExtra) ? new g((byte) 0) : com.tencent.mm.pluginsdk.model.a.a.qyL.getPackage().equals(stringExtra) ? new b() : new h((byte) 0); cVar.a(context, this.qko, this.qkp, this.qkq); this.qkr.uX(this.pSW); } } else { x.e("MicroMsg.OpenMapNavigator", "onActivityResult, not support result_code = %d", new Object[]{Integer.valueOf(i2)}); this.qkr.pT(this.pSW); } } if (this.qkm && this.qkr != null) { this.qkr.Bg(this.pSW); } this.qkm = false; this.qkn = com.tencent.mm.pluginsdk.model.a.a.qyH.code; this.qko = null; this.qkp = null; this.YC = null; this.qkr = null; this.qkq = null; this.qks = null; this.qkt = null; if (!(this.dMm == null || this.qku == null)) { this.dMm.c(this.qku); } this.dMm = null; this.qku = null; if (this.kHU != null) { if (this.qks != null) { this.kHU.a(this.qks); } if (this.qkt != null) { this.kHU.a(this.qkt); } } this.kHU = null; this.qks = null; this.qkt = null; } j() { } final void bYu() { Context context = null; this.qku = null; this.qks = null; this.qkt = null; if (this.YC != null) { context = (Context) this.YC.get(); } if (context != null) { Intent intent = new Intent(context, AppChooserUI.class); ArrayList arrayList = new ArrayList(5); arrayList.add(com.tencent.mm.pluginsdk.model.a.a.qyH.getPackage()); arrayList.add(com.tencent.mm.pluginsdk.model.a.a.qyI.getPackage()); arrayList.add(com.tencent.mm.pluginsdk.model.a.a.qyJ.getPackage()); arrayList.add(com.tencent.mm.pluginsdk.model.a.a.qyK.getPackage()); arrayList.add(com.tencent.mm.pluginsdk.model.a.a.qyL.getPackage()); intent.putStringArrayListExtra("targetwhitelist", arrayList); Parcelable intent2 = new Intent("android.intent.action.VIEW", Uri.parse(String.format("geo:%f,%f", new Object[]{Double.valueOf(this.qkp.latitude), Double.valueOf(this.qkp.longitude)}))); intent.putExtra("targetintent", intent2); Bundle bundle = new Bundle(2); bundle.putInt("key_map_app", this.qkn); bundle.putParcelable("key_target_intent", intent2); intent.putExtra("key_recommend_params", bundle); intent.putExtra(DownloadSettingTable$Columns.TYPE, 2); intent.putExtra("title", context.getString(R.l.location_info_send_tip)); ((MMActivity) context).b(this, intent, 33); } } }