text
stringlengths
10
2.72M
package com.tencent.mm.plugin.wallet_core.model; import com.tencent.mm.g.c.cl; import com.tencent.mm.sdk.e.c.a; import java.lang.reflect.Field; public final class k extends cl { public static a dhO; static { a aVar = new a(); aVar.sKy = new Field[7]; aVar.columns = new String[8]; StringBuilder stringBuilder = new StringBuilder(); aVar.columns[0] = "title"; aVar.sKA.put("title", "TEXT PRIMARY KEY "); stringBuilder.append(" title TEXT PRIMARY KEY "); stringBuilder.append(", "); aVar.sKz = "title"; aVar.columns[1] = "loan_jump_url"; aVar.sKA.put("loan_jump_url", "TEXT"); stringBuilder.append(" loan_jump_url TEXT"); stringBuilder.append(", "); aVar.columns[2] = "red_dot_index"; aVar.sKA.put("red_dot_index", "INTEGER"); stringBuilder.append(" red_dot_index INTEGER"); stringBuilder.append(", "); aVar.columns[3] = "is_show_entry"; aVar.sKA.put("is_show_entry", "INTEGER"); stringBuilder.append(" is_show_entry INTEGER"); stringBuilder.append(", "); aVar.columns[4] = "tips"; aVar.sKA.put("tips", "TEXT"); stringBuilder.append(" tips TEXT"); stringBuilder.append(", "); aVar.columns[5] = "is_overdue"; aVar.sKA.put("is_overdue", "INTEGER"); stringBuilder.append(" is_overdue INTEGER"); stringBuilder.append(", "); aVar.columns[6] = "available_otb"; aVar.sKA.put("available_otb", "TEXT"); stringBuilder.append(" available_otb TEXT"); aVar.columns[7] = "rowid"; aVar.sql = stringBuilder.toString(); dhO = aVar; } protected final a AX() { return dhO; } }
package org.rw.crow.security; import java.io.IOException; import sun.misc.BASE64Decoder; /** * Common data decode. * @author Crow * @date 2015年8月4日 */ public class CommonDecode { public static String Base64(String msg){ BASE64Decoder decoder = new BASE64Decoder(); byte[] byteData = null; String clearText = ""; try { byteData = decoder.decodeBuffer(msg); clearText = new String(byteData); } catch (IOException e) { e.printStackTrace(); } return clearText; } }
package com.tencent.mm.pluginsdk.nfc; import android.os.Parcel; import android.os.Parcelable.Creator; class NfcAID$1 implements Creator<NfcAID> { NfcAID$1() { } public final /* synthetic */ Object createFromParcel(Parcel parcel) { return new NfcAID(parcel); } public final /* bridge */ /* synthetic */ Object[] newArray(int i) { return new NfcAID[i]; } }
package br.com.projetoDAO.DAO; import br.com.projetoDAO.Model.Pessoa; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import org.junit.Ignore; public class PessaoDAOTest { Pessoa p; Pessoa p1; Pessoa p2; public PessaoDAOTest() { // p = new Pessoa("paulo", "aluno"); //p1 = new Pessoa("coroline", "programdora"); } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of consultar method, of class PessaoDAO. */ @Test @Ignore public void testConsultar() { System.out.println("consultar"); PessaoDAO instance = new PessaoDAO(); assertTrue(instance.consultar()); } /** * Test of inserir method, of class PessaoDAO. */ @Test @Ignore public void testInserir() { System.out.println("inserir"); PessaoDAO pd = new PessaoDAO(); Pessoa p = new Pessoa("carla", "faxineira"); assertTrue(pd.inserir(p)); } @Test @Ignore public void testatualizar() { System.out.println("Atulalizar"); PessaoDAO pd1 = new PessaoDAO(); Pessoa p1 = new Pessoa(7, "Joao", "administração"); assertTrue(pd1.atualizar(p1)); } @Test public void testdeletar() { System.out.println("deletar"); PessaoDAO pd2 = new PessaoDAO(); assertTrue(pd2.deletar(6)); } @Test @Ignore public void testconsultaporId() { System.out.println("Consulta por ID"); PessaoDAO pd3 = new PessaoDAO(); assertTrue(pd3.consultaporId(1)); } }
package com.ibm.training.bootcamp.rest.sample01.service; import java.util.List; import com.ibm.training.bootcamp.rest.sample01.domain.ExpenseCategory; public interface ExpenseCategoryService { public List<ExpenseCategory> findAll(); public List<ExpenseCategory> findByName(String categoryName); public void add(ExpenseCategory category); //public void upsert(ExpenseCategory category); }
package com.farukcankaya.springcase.campaign; import com.farukcankaya.springcase.campaign.entity.Campaign; import com.farukcankaya.springcase.common.ListResponse; import com.farukcankaya.springcase.common.MissingParameterException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; @RestController @RequestMapping("/v1/campaigns") public class CampaignRestController { private CampaignService campaignService; @Autowired public CampaignRestController(CampaignService campaignService) { this.campaignService = campaignService; } @GetMapping @ResponseStatus(HttpStatus.OK) public ListResponse<Campaign> index() { List<Campaign> campaignList = campaignService.getAllCampaigns(); return new ListResponse<>(campaignList); } @GetMapping( value = "/{campaignId}", produces = {MediaType.APPLICATION_JSON_VALUE} ) @ResponseStatus(HttpStatus.OK) public ResponseEntity<Campaign> show(@PathVariable Long campaignId) { Campaign campaign = this.campaignService.getCampaignById(campaignId); return new ResponseEntity<>(campaign, HttpStatus.OK); } @PostMapping(consumes = {MediaType.APPLICATION_JSON_VALUE}) @ResponseStatus(HttpStatus.CREATED) public ResponseEntity<Campaign> create(@Valid @RequestBody Campaign campaign) { Campaign savedCampaign = campaignService.addCampaign(campaign); return new ResponseEntity<>(savedCampaign, HttpStatus.CREATED); } @PutMapping( value = "/{campaignId}", consumes = {MediaType.APPLICATION_JSON_VALUE} ) @ResponseStatus(HttpStatus.OK) public ResponseEntity<Campaign> update( @PathVariable Long campaignId, @Valid @RequestBody Campaign campaign) { campaignService.updateCampaign(campaignId, campaign); return new ResponseEntity<>(campaign, HttpStatus.OK); } @DeleteMapping(value = "/{campaignId}") @ResponseStatus(HttpStatus.NO_CONTENT) public ResponseEntity<Campaign> destroy(@PathVariable Long campaignId) { campaignService.deleteCampaign(campaignId); return ResponseEntity.noContent().build(); } }
package com.tencent.mm.cache; import android.graphics.Canvas; import android.graphics.PorterDuff.Mode; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.t.e; import java.util.Iterator; import java.util.ListIterator; import java.util.Stack; public final class c implements d<com.tencent.mm.t.c> { public Stack<com.tencent.mm.t.c> dai; public Stack<com.tencent.mm.t.c> daj; private int dal; public final void onCreate() { x.i("MicroMsg.EmojiAndTextCache", "[onCreate]"); this.dai = new Stack(); } public final void onDestroy() { Iterator it; x.i("MicroMsg.EmojiAndTextCache", "[onDestroy]"); if (this.dai != null) { it = this.dai.iterator(); while (it.hasNext()) { ((com.tencent.mm.t.c) it.next()).clear(); } this.dai.clear(); } if (this.daj != null) { it = this.daj.iterator(); while (it.hasNext()) { ((com.tencent.mm.t.c) it.next()).clear(); } this.daj.clear(); } } public final void aV(boolean z) { x.i("MicroMsg.EmojiAndTextCache", "[onSave] size:%s isExit:%s", new Object[]{Integer.valueOf(this.dai.size()), Boolean.valueOf(z)}); if (this.daj != null) { this.daj.clear(); } this.daj = new Stack(); Iterator it = this.dai.iterator(); while (it.hasNext()) { this.daj.push(((com.tencent.mm.t.c) it.next()).CL()); } x.i("MicroMsg.EmojiAndTextCache", "[onSave] mLastStack size:%s", new Object[]{Integer.valueOf(this.daj.size())}); if (z) { this.dai.clear(); it = this.daj.iterator(); while (it.hasNext()) { com.tencent.mm.t.c cVar = (com.tencent.mm.t.c) it.next(); x.d("MicroMsg.EmojiItem", "[recycleBitmap]"); if (!(cVar.dnJ == null || cVar.dnJ.isRecycled())) { cVar.dnJ.recycle(); } } } } public final void yo() { x.i("MicroMsg.EmojiAndTextCache", "[onRestore] size:%s isExit:%s", new Object[]{Integer.valueOf(this.dai.size()), Boolean.valueOf(false)}); this.dai.clear(); if (this.daj != null) { x.i("MicroMsg.EmojiAndTextCache", "[onRestore] %s", new Object[]{Integer.valueOf(this.daj.size())}); this.dai.addAll(this.daj); } x.i("MicroMsg.EmojiAndTextCache", "[onRestore] mCurStack size:%s ", new Object[]{Integer.valueOf(this.dai.size())}); Iterator it = this.dai.iterator(); while (it.hasNext()) { ((com.tencent.mm.t.c) it.next()).CG(); } } public final void a(Canvas canvas, boolean z) { com.tencent.mm.t.c cVar; if (z) { canvas.drawColor(0, Mode.CLEAR); Iterator it = this.dai.iterator(); while (it.hasNext()) { cVar = (com.tencent.mm.t.c) it.next(); if (!cVar.dnN) { cVar.draw(canvas); } } return; } cVar = ys(); if (cVar != null && !cVar.dnN) { cVar.draw(canvas); } } public final void c(Canvas canvas) { Iterator it = this.dai.iterator(); while (it.hasNext()) { com.tencent.mm.t.c cVar = (com.tencent.mm.t.c) it.next(); cVar.setSelected(false); cVar.draw(canvas); } } /* renamed from: yr */ public final com.tencent.mm.t.c pop() { return (com.tencent.mm.t.c) this.dai.pop(); } public final com.tencent.mm.t.c ys() { if (this.dai == null || this.dai.size() <= 0) { return null; } return (com.tencent.mm.t.c) this.dai.peek(); } /* renamed from: a */ public final void add(com.tencent.mm.t.c cVar) { if (this.dai != null) { this.dai.push(cVar); } } public final int aW(boolean z) { if (z) { if (this.dai != null) { return this.dai.size(); } return 0; } else if (this.daj != null) { return this.daj.size(); } else { return 0; } } public final void vN() { this.dal++; } public final void b(com.tencent.mm.t.c cVar) { if (cVar != null) { this.dai.remove(this.dai.indexOf(cVar)); this.dai.push(cVar); } } public final ListIterator<com.tencent.mm.t.c> yt() { return this.dai.listIterator(this.dai.size()); } public final int[] yu() { int[] iArr = new int[2]; if (this.daj != null) { Iterator it = this.daj.iterator(); while (it.hasNext()) { if (((com.tencent.mm.t.c) it.next()) instanceof e) { iArr[1] = iArr[1] + 1; } else { iArr[0] = iArr[0] + 1; } } } return iArr; } }
package com.jachin.shopping.po; import org.springframework.stereotype.Repository; @Repository public class Address { private Integer addressid; private Integer userid; private String address; public Integer getAddressid() { return addressid; } public void setAddressid(Integer addressid) { this.addressid = addressid; } public Integer getUserid() { return userid; } public void setUserid(Integer userid) { this.userid = userid; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address == null ? null : address.trim(); } }
package com.example; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import com.example.util.ApplicationConfFactory; public class DataLoaderImpl implements DataLoader { public List<Group> loadGroups() { List<Group> groups = new ArrayList<>(); //String sql = "SELECT * FROM \"GROUP_FUNCTION\""; // Works for PostgreSQL and Oracle; String sql = "SELECT gf.\"ID\", gf.\"NAME\", gf.\"DESCR\", gf.\"CTIME\"," + " COUNT(f.\"ID\") as \"ALL\"," + " COUNT(CASE f.\"IS_ACTIVE\" WHEN 'N' THEN 1 ELSE NULL END) as \"INACTIVE\"" + " FROM \"GROUP_FUNCTION\" gf LEFT JOIN \"FUNCTIONS\" f ON gf.\"ID\" = f.\"ID_GROUP\"" + " GROUP BY gf.\"ID\", gf.\"NAME\", gf.\"DESCR\", gf.\"CTIME\"" + " ORDER BY gf.\"ID\""; try (Connection connection = ApplicationConfFactory.getInstance().getConnection(); Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(sql)) { while (rs.next()) { groups.add(new Group(rs.getInt("ID"), rs.getString("NAME"), rs.getString("DESCR"), rs.getDate("CTIME"), rs.getInt("INACTIVE"), rs.getInt("ALL") )); } } catch (SQLException ex) { ex.printStackTrace(); } return groups; } public List<Function> loadFunctions(Group group) { List<Function> functions = new ArrayList<>(); if (group == null) return functions; try (Connection connection = ApplicationConfFactory.getInstance().getConnection(); Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM \"FUNCTIONS\" WHERE \"ID_GROUP\" = " + group.getId() + " ORDER BY \"ID\"")) { while (rs.next()) { functions.add(new Function(rs.getInt("ID"), rs.getString("NAME"), rs.getString("DESCR"), rs.getDate("CTIME"), rs.getString("IS_ACTIVE"))); } } catch (SQLException ex) { ex.printStackTrace(); } return functions; } public List<Parameter> loadParameters(Function function) { List<Parameter> parameters = new ArrayList<>(); if (function == null) return parameters; try (Connection connection = ApplicationConfFactory.getInstance().getConnection(); Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM \"FUN_PARAM\" WHERE \"ID_FUN\" = " + function.getId() + " ORDER BY \"ID\"")) { while (rs.next()) { parameters.add(new Parameter(rs.getInt("ID"), rs.getString("NAME"), rs.getString("DESCR"), rs.getDate("CTIME"))); } } catch (SQLException ex) { ex.printStackTrace(); } return parameters; } }
package com.isystk.sample.web.base.util; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.validation.Errors; import org.springframework.web.multipart.MultipartFile; import javax.imageio.IIOException; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import java.io.IOException; import java.util.Iterator; /** * 入力チェックユーティリティ */ public class WebValidateUtils { /** * ファイルの拡張子をチェックします。 * * @param file ファイル * @param extensions 対応する拡張子 * @return true / false */ public static boolean isExtension(MultipartFile file, String[] extensions) { if (file == null) { return false; } String fileName = file.getResource().getFilename(); if (extensions == null || extensions.length == 0) { return (FilenameUtils.indexOfExtension(fileName) == -1); } String fileExt = FilenameUtils.getExtension(fileName); for (int i = 0; i < extensions.length; i++) { if (fileExt.equalsIgnoreCase(extensions[i])) { return true; } } return false; } /** * ファイルの拡張子をチェックします。(エラーメッセージも同時に追加) * * @param propertyName プロパティ名 * @param file ファイル * @param extensions 対応する拡張子 * @param messages メッセージ * @param itemName 項目名(表示文字列) */ public static void isExtensionChk(String propertyName, MultipartFile file, String[] extensions, Errors errors, String itemName) { if (!isExtension(file, extensions)) { errors.rejectValue(propertyName, "errors.isextension", new Object[]{propertyName}, ""); } } /** * ファイルサイズをチェックします。 * * @param file ファイル * @param maxSize 最大のファイルサイズ(バイト) * @return true / false */ public static boolean maxFileSize(MultipartFile file, long maxSize) { if (file == null) { return false; } if (maxSize < file.getSize()) { return false; } return true; } /** * ファイルサイズをチェックします。(エラーメッセージも同時に追加) * * @param propertyName プロパティ名 * @param file ファイル * @param maxSize 最大のファイルサイズ(バイト) * @param messages メッセージ * @param itemName 項目名(表示文字列) */ public static void maxFileSizeChk(String propertyName, MultipartFile file, long maxSize, Errors errors, String itemName) { if (!maxFileSize(file, maxSize)) { errors.rejectValue(propertyName, "errors.maxfilesize", new Object[]{propertyName}, ""); } } /** * 画像ファイルかどうかをチェックします。 * * @param imageFile 画像ファイル * @return true / false */ public static boolean isImageFile(MultipartFile imageFile) { if (imageFile == null) { return false; } ImageInputStream is = null; try { is = ImageIO.createImageInputStream(imageFile.getInputStream()); Iterator<ImageReader> i = ImageIO.getImageReaders(is); while (i.hasNext()) { return true; } } catch (IOException e) { } finally { if (is != null) { try { is.close(); } catch (IOException e1) { } } } return false; } /** * 画像ファイルかどうかをチェックします。(エラーメッセージも同時に追加) * * @param propertyName プロパティ名 * @param file ファイル * @param messages メッセージ * @param itemName 項目名(表示文字列) */ public static void isImageFileChk(String propertyName, MultipartFile imageFile, Errors errors, String itemName) { if (!isImageFile(imageFile)) { errors.rejectValue(propertyName, "errors.isImageFile", new Object[]{propertyName}, ""); } } /** * 画像がCMYKであるかどうか * * @param imageFile * @return true:CMYK、false:CMYKでない */ public static boolean isCmykImageChk(MultipartFile imageFile) { try { ImageIO.read(imageFile.getInputStream()); } catch (IIOException e) { if (!StringUtils.isEmpty(e.getMessage()) && e.getMessage().equals("Unsupported Image Type")) { // CMYKの場合当該例外が発生する return true; } return false; } catch (Exception e) { return false; } return false; } }
package com.fountainhead.client.place; public class NameTokens { public static final String dialogSamplePage = "!dialogPage"; public static final String adminPage = "!adminPage"; public static final String homeNewsPage = "!homeNewsPage"; public static final String infoInfoPage = "!homeInfoPage"; public static final String settingsPage = "!settingsPage"; public static final String loginPage = "!loginPage"; public static final String myloginpage = "myloginpage"; public static final String signInPage = "SignInPage"; public static final String mainPage = "MainPage"; public static final String errorPage = "ErrorPage"; /** * @return the signinpage */ public static String getSigninpage() { return signInPage; } /** * @return the mainpage */ public static String getMainpage() { return mainPage; } /** * @return the errorpage */ public static String getErrorpage() { return errorPage; } public static String getDialogSamplePage() { return dialogSamplePage; } public static String getAdminPage() { return adminPage; } public static String getHomeNewsPage() { return homeNewsPage; } public static String getHomeInfoPage() { return infoInfoPage; } public static String getSettingsPage() { return settingsPage; } /** * @return the loginpage */ public static String getLoginpage() { return loginPage; } public static String getMyloginpage() { return myloginpage; } }
package tests; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import lib.text.TextRenderer; import math.geom.Point2f; import org.lwjgl.LWJGLException; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.DisplayMode; import org.newdawn.slick.opengl.Texture; import org.newdawn.slick.opengl.TextureLoader; import static org.lwjgl.opengl.GL11.*; public class QuadTest { boolean closeRequested = false; double width = 600; double height = 600; int fps = 60; int mouseX = 0; int mouseY = 0; Texture javaTex; TextRenderer text; public QuadTest() throws LWJGLException, FileNotFoundException, IOException { init(); while(!closeRequested) { closeRequested = Display.isCloseRequested(); processInput(); renderScene(); Display.update(); Display.sync(fps); } onClose(); } private void init() throws LWJGLException, FileNotFoundException, IOException { Display.setDisplayMode(new DisplayMode((int)width, (int)height)); Display.setTitle("Fun with shapes"); Display.setFullscreen(true); Display.create(); //glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, width, height, 0.0, 1.0, -1.0); glMatrixMode(GL_MODELVIEW); glEnable(GL_TEXTURE_2D); glLoadIdentity(); /*glLoadIdentity(); glShadeModel(GL_SMOOTH); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearDepth(1.0f); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);*/ javaTex = loadTexture("Java"); text = new TextRenderer(new File("res/font1.jpg")); } int count = 0; private void renderScene() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); // glColor3f(0.0f, 1.0f, 0.0f); drawSquare(mouseX-50, (float)height-mouseY-50, 0, 100, javaTex); text.renderText(count + "", new Point2f(0.0f, 0.0f), 30.0f, 50.0f); count++; } private void drawSquare(float sx, float sy, float sz, float size, Texture t) { t.bind(); //glColor3f(0.0f, 1.0f, 0.0f); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3f(sx, sy, sz); glTexCoord2f(1, 0); glVertex3f(sx+size, sy, sz); glTexCoord2f(1, 1); glVertex3f(sx+size, sy+size, sz); glTexCoord2f(0, 1); glVertex3f(sx, sy+size, sz); glEnd(); } private void processInput() { //System.out.println("Mouse at position (" + Mouse.getX() + ", " + Mouse.getY() + ")"); if(Mouse.isButtonDown(0)) { //System.out.println("Left mouse button is down"); mouseX = Mouse.getX(); mouseY = Mouse.getY(); } while(Keyboard.next()) { if(Keyboard.getEventKey() == Keyboard.KEY_SPACE) { if(Keyboard.getEventKeyState()) System.out.println("Space bar down"); else System.out.println("Space bar up"); } else if(Keyboard.getEventKey() == Keyboard.KEY_ESCAPE) { closeRequested = true; } } } private void onClose() { Display.destroy(); } private Texture loadTexture(String name) { try { return TextureLoader.getTexture("png", new FileInputStream(new File("res/" + name + ".png"))); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public static void main(String[] args) throws LWJGLException, FileNotFoundException, IOException { new QuadTest(); } }
package HI; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import problemDomain.Cashier; import problemDomain.Person; import problemDomain.Store; public class EditCashier extends JPanel { private JTextField textField_8; private JTextField textField_7; private JTextField textField_4; private JTextField textField_3; private JTextField textField_2; private JTextField textField_1; private JTextField textField_9; private JTextField textField_5; private JTextField textField_6; /** * Create the panel. */ public EditCashier(Store store, JFrame frame, Boolean isAdd, Cashier cashier) { setLayout(null); textField_8 = new JTextField(); textField_8.setColumns(10); textField_8.setBounds(88, 176, 86, 20); if (!isAdd) { textField_8.setText(cashier.getPassword()); } add(textField_8); JLabel label = new JLabel("Number:"); label.setBounds(10, 51, 68, 14); add(label); JLabel label_1 = new JLabel("Edit Cashier"); label_1.setBounds(178, 11, 72, 14); add(label_1); JButton button = new JButton("Save"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { cashier.setNumber(textField_1.getText()); cashier.getPerson().setName(textField_2.getText()); cashier.getPerson().setAddress(textField_3.getText()); cashier.getPerson().setCity(textField_4.getText()); cashier.getPerson().setState(textField_5.getText()); cashier.getPerson().setZip(textField_6.getText()); cashier.getPerson().setPhone(textField_7.getText()); cashier.setPassword(textField_8.getText()); cashier.getPerson().setSSN(textField_9.getText()); if (isAdd) { store.addCashier(cashier); } frame.getContentPane().removeAll(); frame.getContentPane().add(new SelectCashier(store, frame)); frame.getContentPane().revalidate(); } }); button.setBounds(51, 247, 89, 23); add(button); JButton button_1 = new JButton("Cancel"); button_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.getContentPane().removeAll(); frame.getContentPane().add(new SelectCashier(store, frame)); frame.getContentPane().revalidate(); } }); button_1.setBounds(213, 247, 89, 23); add(button_1); JLabel lblNewLabel = new JLabel("Name:"); lblNewLabel.setBounds(10, 76, 46, 14); add(lblNewLabel); JLabel lblAddress = new JLabel("Address:"); lblAddress.setBounds(10, 104, 68, 14); add(lblAddress); JLabel lblNewLabel_1 = new JLabel("City:"); lblNewLabel_1.setBounds(10, 129, 46, 14); add(lblNewLabel_1); JLabel lblPhone = new JLabel("Phone:"); lblPhone.setBounds(10, 154, 46, 14); add(lblPhone); JLabel lblPassword = new JLabel("Password:"); lblPassword.setBounds(10, 179, 68, 14); add(lblPassword); textField_7 = new JTextField(); textField_7.setBounds(88, 151, 129, 20); if (!isAdd) { textField_7.setText(cashier.getPerson().getPhone()); } add(textField_7); textField_7.setColumns(10); textField_4 = new JTextField(); textField_4.setBounds(88, 126, 129, 20); if (!isAdd) { textField_4.setText(cashier.getPerson().getCity()); } add(textField_4); textField_4.setColumns(10); textField_3 = new JTextField(); textField_3.setBounds(88, 101, 129, 20); if (!isAdd) { textField_3.setText(cashier.getPerson().getAddress()); } add(textField_3); textField_3.setColumns(10); textField_2 = new JTextField(); textField_2.setBounds(88, 73, 129, 20); if (!isAdd) { textField_2.setText(cashier.getName()); } add(textField_2); textField_2.setColumns(10); textField_1 = new JTextField(); textField_1.setBounds(88, 48, 86, 20); if (!isAdd) { textField_1.setText(cashier.getNumber()); } add(textField_1); textField_1.setColumns(10); JLabel lblSsn = new JLabel("SSN:"); lblSsn.setBounds(256, 51, 46, 14); add(lblSsn); textField_9 = new JTextField(); textField_9.setBounds(294, 48, 117, 20); if (!isAdd) { textField_9.setText(cashier.getPerson().getSSN()); } add(textField_9); textField_9.setColumns(10); JLabel lblState = new JLabel("State:"); lblState.setBounds(238, 129, 46, 14); add(lblState); textField_5 = new JTextField(); textField_5.setBounds(282, 126, 46, 20); if (!isAdd) { textField_5.setText(cashier.getPerson().getState()); } add(textField_5); textField_5.setColumns(10); JLabel lblZip = new JLabel("Zip:"); lblZip.setBounds(350, 129, 46, 14); add(lblZip); textField_6 = new JTextField(); textField_6.setBounds(383, 126, 46, 20); if (!isAdd) { textField_6.setText(cashier.getPerson().getZip()); } add(textField_6); textField_6.setColumns(10); } }
package com.allianz.ExpenseTracker.Reports; import java.awt.Color; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JViewport; import javax.swing.SwingUtilities; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.Element; import javax.swing.text.Position; import javax.swing.text.StyleConstants; import javax.swing.text.html.HTML; import javax.swing.text.html.HTMLDocument; import org.apache.commons.lang.StringUtils; import org.apache.regexp.RE; import org.jdom.Attribute; import org.jfree.ui.RefineryUtilities; import com.allianz.ExpenseTracker.DBO.PerformDataBaseOperation; import com.allianz.ExpenseTracker.Objects.DefaultComponents; import com.allianz.ExpenseTracker.Objects.ObjectsBankDetailReport; import com.allianz.ExpenseTracker.Objects.ObjectsExpenseReport; import com.allianz.ExpenseTracker.Objects.ObjectsExpenseTracker; import com.allianz.ExpenseTracker.Objects.objItemundAmount; import com.allianz.ExpenseTracker.Panels.PnlBankItemDetailsAnzeigen; import com.allianz.ExpenseTracker.Panels.PnlExpenseTrackerHome; import com.allianz.ExpenseTracker.Steurung.Categories; import com.allianz.ExpenseTracker.Steurung.SteurungBankDetailsReport; import com.allianz.ExpenseTracker.Steurung.SteurungDetailsAnzeigen; public class pnlBankDetailReport { objItemundAmount obj; pnlBankDetailReport report; ObjectsExpenseReport objReport = new ObjectsExpenseReport(); ObjectsExpenseTracker expenseObj = new ObjectsExpenseTracker(); JFrame frmReport; JPanel pnlReport; JLabel lblMain; JButton btnMain; JButton btnHome; JLabel lblDatumVon; JLabel lblDatumBis; JLabel lblOr; JLabel lblMonth; JLabel lblYear; JTextField txtDatumVon; JTextField txtDatumBis; JButton btnSuchen; JComboBox<?> cmpCategory; JButton btnShow; JEditorPane edHTMLHeaderPane; JEditorPane edHTMLPane; JScrollPane scrHTMLPane, cScpHtml; JButton btnBack; String date; private String rgbBackSelected = null; private String rgbFrontSelected = null; private String rgbBack = null; private String rgbFront = null; protected Element suchergebnisRoot; List<Attribute> mAttributeVerlaufEintrag = new ArrayList<Attribute>(); SteurungBankDetailsReport steurungExpRep = new SteurungBankDetailsReport(); SteurungDetailsAnzeigen steurungDetAnz = new SteurungDetailsAnzeigen(); ObjectsBankDetailReport dates = new ObjectsBankDetailReport(); Categories category = new Categories(); JEditorPane editor; int posX, posY; public JEditorPane getEditor() { return editor; } public void setEditor(JEditorPane editor) { this.editor = editor; } public int getPosX() { return posX; } public void setPosX(int posX) { this.posX = posX; } public int getPosY() { return posY; } public void setPosY(int posY) { this.posY = posY; } public pnlBankDetailReport() { dates.setFlagShow("N"); initialize(); } public pnlBankDetailReport(String frmDate, String toDate, String strFlagShow) { dates = new ObjectsBankDetailReport(frmDate, toDate); dates.setFlagShow(strFlagShow); initialize(); } public void pnlExpenseReportSuchen() { initialize(); } private void initialize() { // TODO Auto-generated method stub DefaultComponents expenseTracker = new DefaultComponents(); frmReport = expenseTracker.getMainFrame(); lblMain = expenseTracker.getMainLabel(); btnMain = expenseTracker.getMainButton(); btnHome = expenseTracker.getHomeButton(); try { createComponents(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } addToFrame(); setFrmReport(frmReport); expenseObj.setFrmReport(frmReport); } public JFrame getFrmReport() { return frmReport; } public void setFrmReport(JFrame frmReport) { this.frmReport = frmReport; } private void createComponents() throws IOException { // TODO Auto-generated method stub lblDatumVon = new JLabel("Date From:"); lblDatumVon.setBounds(50, 75, 100, 25); txtDatumVon = new JTextField(); txtDatumVon.setBounds(150, 75, 80, 25); txtDatumVon.setText(dates.frmDate); lblDatumBis = new JLabel("Date Till:"); lblDatumBis.setBounds(275, 75, 100, 25); txtDatumBis = new JTextField(); txtDatumBis.setBounds(400, 75, 80, 25); txtDatumBis.setText(dates.toDate); btnSuchen = new JButton("SEARCH"); btnSuchen.setBounds(550, 75, 100, 25); btnSuchen.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub frmReport.dispose(); dates = new ObjectsBankDetailReport(txtDatumVon.getText(),txtDatumBis.getText()); dates.setFlagShow("N"); pnlExpenseReportSuchen(); getFrmReport().setVisible(true); } }); PerformDataBaseOperation bankNameDB = new PerformDataBaseOperation(); ArrayList<String > bankName = bankNameDB.readBankNameDB(); cmpCategory = new JComboBox<Object>(bankName.toArray()); cmpCategory.setBounds(50, 165, 225, 25); if (dates.getFlagShow().equals("Y")) { cmpCategory.setSelectedItem(dates.getCategShow()); } btnShow = new JButton("Show"); btnShow.setBounds(300, 165, 100, 25); btnShow.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub dates.setCategShow(cmpCategory.getSelectedItem().toString()); dates.setFlagShow("Y"); frmReport.dispose(); pnlExpenseReportSuchen(); getFrmReport().setVisible(true); } }); edHTMLPane = new JEditorPane(); edHTMLPane.setEditable(false); edHTMLPane.setContentType("text/html; charset=UTF-8"); initializeMouseListener(); edHTMLHeaderPane = new JEditorPane(); edHTMLHeaderPane.setName("HtmlHeaderPane"); edHTMLHeaderPane.setEditable(false); edHTMLHeaderPane.setContentType("text/html; charset=UTF-8"); cScpHtml = new JScrollPane(edHTMLPane); cScpHtml.setName("Scrollpane"); cScpHtml.setHorizontalScrollBarPolicy(javax.swing.JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); cScpHtml.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); cScpHtml.setViewportView(edHTMLPane); JViewport viewportHeader = new JViewport(); viewportHeader.setView(edHTMLHeaderPane); cScpHtml.setColumnHeaderView(viewportHeader); cScpHtml.getViewport().setBackground(edHTMLHeaderPane.getBackground()); edHTMLHeaderPane.setText(steurungExpRep.initializeHTMLHeader()); edHTMLPane.setText(steurungExpRep.initializeHTML(dates)); cScpHtml.setBounds(20, 200, 750, 510); SwingUtilities.invokeLater(new Runnable() { public void run() { cScpHtml.getViewport().setViewPosition( new Point(0, 0) ); } }); btnBack = new JButton("BACK"); btnBack.setBounds(300, 720, 150, 30); btnBack.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub frmReport.dispose(); PnlExpenseTrackerHome expenseHome = new PnlExpenseTrackerHome(); expenseHome.getFrmTrackerHome().setVisible(true); } }); edHTMLPane.addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent e) { // TODO Auto-generated method stub if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { String id = (String) e.getSourceElement().getAttributes() .getAttribute(HTML.Attribute.ID); if (id != null && id.startsWith("#posItem")) { doItemDetailsAnzeigen(id); } } } }); } private void doItemDetailsAnzeigen(String id) { // TODO Auto-generated method stub String sindex = id.substring(8); int index = Integer.parseInt(sindex); if (steurungExpRep.getListOfTransactions().size() < index) { } else { obj = steurungExpRep.getListOfTransactions().get(index-1); createObjReport(); PnlBankItemDetailsAnzeigen details = new PnlBankItemDetailsAnzeigen(objReport,"N"); details.getFrmItemDetails().setVisible(true); } } private void addToFrame() { // TODO Auto-generated method stub frmReport.add(lblMain); frmReport.add(btnMain); frmReport.add(btnHome); frmReport.add(lblDatumVon); frmReport.add(txtDatumVon); frmReport.add(lblDatumBis); frmReport.add(txtDatumBis); frmReport.add(btnSuchen); frmReport.add(cmpCategory); frmReport.add(btnShow); frmReport.add(cScpHtml); frmReport.add(btnBack); RefineryUtilities.centerFrameOnScreen(frmReport); } private void initializeMouseListener() { edHTMLPane.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent e) { mouseReleasedHtmlHeaderPane(e); } }); } protected void mouseReleasedHtmlHeaderPane(MouseEvent e) { if (e.getButton() == 1 && e.getClickCount() == 1) { Position.Bias bias[] = new Position.Bias[1]; int pos = ((JEditorPane) e.getSource()).getUI().viewToModel( (JEditorPane) e.getSource(), new Point(e.getX(), e.getY()), bias); HTMLDocument htmlDoc = (HTMLDocument) ((JEditorPane) e.getSource()) .getDocument(); Element elem = htmlDoc.getCharacterElement(pos); Object imageLoc = null; if (elem != null && elem.getAttributes().getAttribute( StyleConstants.NameAttribute) == HTML.Tag.IMG) imageLoc = elem.getAttributes().getAttribute(HTML.Attribute.ID); // Ein zusammengehöriges Tabellenelement kann aus mehreren TR // bestehen: // deshalb erstmal zurück bis eine ID auftaucht und von da an wieder // vorwärts bis zur nächsten ID E140572 while (elem != null && elem.getAttributes().getAttribute( StyleConstants.NameAttribute) != HTML.Tag.TR) { elem = elem.getParentElement(); } if (elem == null) return; Element elemParent = elem.getParentElement(); Object desel = null; Element deselElem = null; for (int i = 0; i < elemParent.getElementCount(); i++) { if (elemParent.getElement(i).getAttributes().getAttribute( HTML.Attribute.ID) != null && elemParent.getElement(i).getAttributes() .getAttribute(HTML.Attribute.BGCOLOR) != null && elemParent.getElement(i).getAttributes() .getAttribute(HTML.Attribute.BGCOLOR) .equals("#" + getRgbBackSelected())) { desel = elemParent.getElement(i).getAttributes() .getAttribute(HTML.Attribute.ID); deselElem = elemParent.getElement(i); } if (desel != null && deselElem != null && deselElem != elem) { toggleRowSelection(e, deselElem, desel); desel = null; deselElem = null; } } Object loc = elem.getAttributes().getAttribute(HTML.Attribute.ID); if (imageLoc != null) { // doExpandCollapseEntry(e, elem, imageLoc); // Elem neu ermitteln, weil geändert elem = htmlDoc.getCharacterElement(pos); while (elem != null && elem.getAttributes().getAttribute( StyleConstants.NameAttribute) != HTML.Tag.TR) elem = elem.getParentElement(); } // Erste TR zu der angeklickten TR-Gruppe finden und diese markieren if (loc == null || ((String) loc).startsWith("#posSubTr")) { elemParent = elem.getParentElement(); int idxNewElementToSelect = -1; for (int i = 0; i < elemParent.getElementCount(); i++) { if (elemParent.getElement(i).getAttributes().getAttribute( HTML.Attribute.ID) != null && ((String) elemParent.getElement(i) .getAttributes().getAttribute( HTML.Attribute.ID)) .startsWith("#posTr")) { loc = elemParent.getElement(i).getAttributes() .getAttribute(HTML.Attribute.ID); idxNewElementToSelect = i; } if (elemParent.getElement(i).equals(elem)) i = elemParent.getElementCount(); } if (idxNewElementToSelect > -1) elem = elemParent.getElement(idxNewElementToSelect); } if (loc == null) return; toggleRowSelection(e, elem, loc); } if (e.getButton() == 3 && e.getClickCount() == 1) { JEditorPane editor = (JEditorPane) e.getSource(); setEditor(editor); setPosX(e.getX()); setPosY(e.getY()); Position.Bias bias[] = new Position.Bias[1]; int pos = ((JEditorPane) e.getSource()).getUI().viewToModel( (JEditorPane) e.getSource(), new Point(e.getX(), e.getY()), bias); HTMLDocument htmlDoc = (HTMLDocument) ((JEditorPane) e.getSource()) .getDocument(); Element elem = htmlDoc.getCharacterElement(pos); AttributeSet a = (AttributeSet) elem.getAttributes(); String id = (String) a.getAttribute(HTML.Attribute.ID); // obj = steurungDetAnz.getTheDetails(steurungExpRep,id); String sindex = id.substring(8); int index = Integer.parseInt(sindex); if (steurungExpRep.getListOfTransactions().size()>index-1){ obj = steurungExpRep.getListOfTransactions().get(index-1); createObjReport(); new PumBankTrackerReport(objReport); } // for (int i = 0; i < elem.getElementCount(); i++) { // if ((elem != null) && ((String) elem.getElement(i).getAttributes().getAttribute( // HTML.Attribute.ID)).startsWith("#posTr")) { // System.out.println(elem.getAttributes().getAttribute( // StyleConstants.NameAttribute)); // elem = elem.getParentElement(); // Object loc = elem.getElement(i).getAttributes() // .getAttribute(HTML.Attribute.ID); // System.out.println(elem); // } // } } } private void createObjReport() { // TODO Auto-generated method stub objReport.setFrmReport(frmReport); objReport.setEditor(editor); objReport.setPosX(getPosX()); objReport.setPosY(getPosY()); objReport.setObj(obj); objReport.setVonDate(txtDatumVon.getText()); objReport.setBisDate(txtDatumBis.getText()); } private void toggleRowSelection(MouseEvent e, Element elem, Object loc) { HTMLDocument htmlDoc = (HTMLDocument) ((JEditorPane) e.getSource()) .getDocument(); String htmlTxt = (String) ((JEditorPane) e.getSource()).getText(); boolean setAltBgColor = getOddElement((String) loc); int startIdx = htmlTxt.substring(0, htmlTxt.indexOf((String) loc)) .lastIndexOf("<"); int endIdx = htmlTxt.indexOf("</tr>", startIdx); String textTr = htmlTxt.substring(startIdx, endIdx); Object bgColor = elem.getAttributes().getAttribute( HTML.Attribute.BGCOLOR); String bgColorNewTxt = ""; String fgColorNewTxt = ""; if (bgColor != null && bgColor.equals("#" + getRgbBackSelected())) { if (!setAltBgColor) bgColorNewTxt = " bgcolor=\"#" + getRgbBack() + "\""; else bgColorNewTxt = " bgcolor=\"#" + getRgbBackAlternate() + "\""; fgColorNewTxt = " color=\"#" + getRgbFront() + "\""; textTr = StringUtils.replace(textTr, "\"yellow\"", "\"blue\""); // removeSelectedList((String) loc); } else { bgColorNewTxt = " bgcolor=\"#" + getRgbBackSelected() + "\""; fgColorNewTxt = " color=\"#" + getRgbFrontSelected() + "\""; textTr = StringUtils.replace(textTr, "\"blue\"", "\"yellow\""); // addSelList((String) loc); } textTr = textTr.substring(0, textTr.indexOf(">")) + bgColorNewTxt + fgColorNewTxt + textTr.substring(textTr.indexOf(">")) + "</tr>"; try { try { htmlDoc.setOuterHTML(elem, textTr); // System.out.println("content= " + // getPanel().getHtmlPane().getText()); //Steph Test } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } catch (BadLocationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // System.out.println("content= " + getPanel().getHtmlPane().getText()); // //Steph Test } private String getStringRGBfromColor(Color mBgCol) { String r = StringUtils.leftPad(Integer.toHexString(mBgCol.getRed()), 2, "0"); String g = StringUtils.leftPad(Integer.toHexString(mBgCol.getGreen()), 2, "0"); String b = StringUtils.leftPad(Integer.toHexString(mBgCol.getBlue()), 2, "0"); String rgb = r + g + b; return rgb; } private String getRgbBackSelected() { if (rgbBackSelected == null) setRgbBackSelected(getStringRGBfromColor(edHTMLPane.getSelectionColor())); return rgbBackSelected; } private void setRgbBackSelected(String rgbBackSelected) { this.rgbBackSelected = rgbBackSelected; } private boolean getOddElement(String loc) { RE re = new RE("#posTr(\\d+)"); if (re.match(loc)) { String sindex = loc.substring(re.getParenStart(1), re .getParenEnd(1)); int index = Integer.parseInt(sindex); return index % 2 == 0; } return false; } private String getRgbBack() { if (rgbBack == null) setRgbBack(getStringRGBfromColor(edHTMLPane.getBackground())); return rgbBack; } private void setRgbBack(String rgbBack) { this.rgbBack = rgbBack; } private String getRgbBackAlternate() { return "eeeeee"; } private String getRgbFront() { if (rgbFront == null) setRgbFront(getStringRGBfromColor(edHTMLPane.getForeground())); return rgbFront; } private void setRgbFront(String rgbFront) { this.rgbFront = rgbFront; } private String getRgbFrontSelected() { if (rgbFrontSelected == null) setRgbFrontSelected(getStringRGBfromColor(edHTMLPane.getSelectedTextColor())); return rgbFrontSelected; } private void setRgbFrontSelected(String rgbFrontSelected) { this.rgbFrontSelected = rgbFrontSelected; } }
package pe.egcc.controller; import java.io.IOException; import java.util.List; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import pe.egcc.eureka.service.PartidaService; @WebServlet({ "/PartidaController", "/ConsultarPartidas" }) public class PartidaController extends HttpServlet { private static final long serialVersionUID = 1L; protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Datos String oficina = request.getParameter("oficina"); String registro = request.getParameter("registro"); String partida = request.getParameter("partida"); String detalle = request.getParameter("detalle"); String abc = request.getParameter("things"); // Proceso PartidaService partidaService; partidaService = new PartidaService(); partidaService.spNuevaPartida(oficina, registro, partida, detalle); request.setAttribute("message", partidaService.getMensaje()); // Forward List<Map<String, ?>> lista = partidaService.traerPartidas(); request.setAttribute("lista", lista); RequestDispatcher rd = request.getRequestDispatcher("partidas.jsp"); rd.forward(request, response); } /* public List<String> getItems() { List<String> list = new ArrayList<String>(); list.add("Thing1"); list.add("Thing2"); list.add("Thing3"); return list; } * */ }
/* * Copyright © 2019 The GWT Project Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gwtproject.dom.client; import com.google.gwt.junit.client.GWTTestCase; /** Tests for {@link ImageElement}. */ public class ImageElementTest extends GWTTestCase { @Override public String getModuleName() { return "org.gwtproject.dom.DOMTest"; } public void testSetSrc() { // The parent element will actually load the image. ImageElement parent = Document.get().createImageElement(); parent.setSrc("largeImage0.jpg"); assertTrue(parent.getSrc().endsWith("largeImage0.jpg")); // The child element does not have its source set until the parent loads. ImageElement child = Document.get().createImageElement(); child.setSrc("largeImage0.jpg"); assertTrue(child.getSrc().endsWith("largeImage0.jpg")); child.setSrc("smallImage1.jpg"); assertTrue(child.getSrc().endsWith("smallImage1.jpg")); } public void testSetSrcCloneParent() { // The parent element will actually load the image. ImageElement parent = Document.get().createImageElement(); parent.setSrc("largeImage1.jpg"); assertTrue(parent.getSrc().endsWith("largeImage1.jpg")); // The child element does not have its source set until the parent loads. ImageElement child = Document.get().createImageElement(); child.setSrc("largeImage1.jpg"); assertTrue(child.getSrc().endsWith("largeImage1.jpg")); // The parent clone will have its source set. We call setSrc to convert it // to a child. final ImageElement cloneParent = parent.cloneNode(true).cast(); cloneParent.setSrc("largeImage1.jpg"); assertTrue(cloneParent.getSrc().endsWith("largeImage1.jpg")); cloneParent.setSrc("smallImage1.jpg"); assertTrue(cloneParent.getSrc().endsWith("smallImage1.jpg")); } public void testSetSrcCloneChild() { // The parent element will actually load the image. ImageElement parent = Document.get().createImageElement(); parent.setSrc("largeImage2.jpg"); assertTrue(parent.getSrc().endsWith("largeImage2.jpg")); // The child element does not have its source set until the parent loads. ImageElement child = Document.get().createImageElement(); child.setSrc("largeImage2.jpg"); assertTrue(child.getSrc().endsWith("largeImage2.jpg")); // The child clone will not have its source set. We call setSrc to ensure // it is registered as a child. final ImageElement cloneChild = parent.cloneNode(true).cast(); cloneChild.setSrc("largeImage2.jpg"); assertTrue(cloneChild.getSrc().endsWith("largeImage2.jpg")); cloneChild.setSrc("smallImage2.jpg"); assertTrue(cloneChild.getSrc().endsWith("smallImage2.jpg")); } }
package org.gooru.dap.jobs.processors.dbutils; import java.util.Iterator; import org.skife.jdbi.v2.sqlobject.BindBean; import org.skife.jdbi.v2.sqlobject.SqlBatch; import org.skife.jdbi.v2.sqlobject.customizers.BatchChunkSize; public interface LearnerProfileCompetencyStatusDao { @SqlBatch("insert into learner_profile_competency_status (user_id, tx_subject_code, gut_code, status) values (:userId, :txSubjectCode, :gutCode, :status) " + "ON CONFLICT (user_id, gut_code) DO NOTHING;") @BatchChunkSize(1000) void insertAll(@BindBean Iterator<LearnerProfileCompetencyStatusBean> learnerProfileCompetencyStatusBean); }
package valatava.lab.warehouse.service; import java.util.List; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import valatava.lab.warehouse.model.Store; import valatava.lab.warehouse.repository.StoreRepository; /** * Service class for managing stores. * * @author Yuriy Govorushkin */ @Service @Transactional public class StoreService { private final StoreRepository storeRepository; public StoreService(StoreRepository storeRepository) { this.storeRepository = storeRepository; } public void save(Store store) { storeRepository.save(store); } public Store findStore(Long id) { return storeRepository.findById(id).orElseThrow(IllegalArgumentException::new); } public List<Store> findAll() { return storeRepository.findAll(); } }
package com.tencent.mm.g.a; public final class td$b { }
package com.markhetherington.thisishow.ui.activites; import android.support.design.widget.TabLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.markhetherington.thisishow.R; import com.markhetherington.thisishow.models.Project; import com.markhetherington.thisishow.ui.fragments.ProjectFeedFragment; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; public class HomeActivity extends AppCompatActivity implements ProjectFeedFragment.OnListFragmentInteractionListener { @Bind(R.id.toolbar) Toolbar mToolbar; @Bind(R.id.container) ViewPager mViewPager; @Bind(R.id.tabs) TabLayout mTabLayout; private SectionsPagerAdapter mSectionsPagerAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); ButterKnife.bind(this); setSupportActionBar(mToolbar); // Create the adapter that will return a fragment for each of the three // primary sections of the activity. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); mViewPager.setAdapter(mSectionsPagerAdapter); mTabLayout.setupWithViewPager(mViewPager); } @OnClick(R.id.fab) public void onFabClicked(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } @Override public void onListFragmentInteraction(Project project) { } public class SectionsPagerAdapter extends FragmentPagerAdapter { public SectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { return ProjectFeedFragment.newInstance(position); } @Override public int getCount() { return 3; } @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return "FEED"; case 1: return "EXPLORE"; case 2: return "ME"; } return null; } } }
package task110; /** * @author Igor */ public class Train { public static void main(String[] args) { } }
package logic.managers; import java.util.*; import logic.game.*; /** Clase que controla la gestión de los zombies */ public class ZombieManager { // Atributes private int zombie_to_play; private Game game; private Random rand; private double freq; // Methods /** Constructor de ZombieManager, recibe los parametros necesarios del enumerado Level */ public ZombieManager(Game game, Level level, long seed){ this.game = game; this.zombie_to_play = level.GetNZombies(); this.rand = new Random(seed); this.freq = level.GetFreq(); } public int GetZRemaining() { return this.zombie_to_play; } /** Añade un zombie al juego si el random que sale es menor a la frequencia de spawn y reduce el númerod e zombies en espera de salir */ public void AddZombie () { if ((rand.nextDouble() < this.freq) && (this.zombie_to_play > 0)) { game.AddZombie(); this.zombie_to_play--; } } }
package shaders; import java.util.HashMap; import java.util.Map; public class ShaderCache { private Map<Integer,Boolean> booleanUniforms = new HashMap<Integer,Boolean>(); private Map<Integer,Float> floatUniforms = new HashMap<Integer,Float>(); public boolean needsUpdating(Integer location, boolean value){ Boolean currentValue = booleanUniforms.get(location); if(currentValue==null||currentValue!=value){ booleanUniforms.put(location, value); return true; }else{ return false; } } public boolean needsUpdating(int location, float value){ Float currentValue = floatUniforms.get(location); if(currentValue==null||currentValue!=value){ floatUniforms.put(location, value); return true; }else{ return false; } } }
public class Sort { public static void main(String[] args) { System.out.println("Integers sorting:"); Integer [] iArr = {10,3,1,4,5,8} ; Selection <Integer> intSelection = new Selection(iArr); intSelection.sort(); intSelection.printArray(); System.out.println("\nDoubles sorting:"); Double [] dArr = {10.22,3.1,1.7,4.2,4.4,5.9} ; Selection <Double> doubleSelection = new Selection(dArr); doubleSelection.sort(); doubleSelection.printArray(); System.out.println("\nStrings sorting:"); String [] sArr = {"sugar","apple","milk","coffe","water","bread"}; Selection <String> stringSelection = new Selection(sArr); stringSelection.sort(); stringSelection.printArray(); } }
/** * Copyright (C) 2014 Stratio (http://stratio.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.stratio.ingestion.sink.mongodb; import static org.fest.assertions.Assertions.assertThat; import java.lang.reflect.Field; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.flume.Channel; import org.apache.flume.Context; import org.apache.flume.Event; import org.apache.flume.Transaction; import org.apache.flume.channel.MemoryChannel; import org.apache.flume.conf.Configurables; import org.apache.flume.event.EventBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mockito; import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import com.github.fakemongo.Fongo; import com.google.common.base.Charsets; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.stratio.ingestion.sink.mongodb.exception.MongoSinkException; @RunWith(JUnit4.class) public class MongoSinkTest { private Fongo fongo; private MongoSink mongoSink; private Channel channel; private void setField(Object obj, String fieldName, Object val) throws Exception { Field field = obj.getClass().getDeclaredField(fieldName); field.setAccessible(true); field.set(obj, val); field.setAccessible(false); } private void injectFongo(MongoSink mongoSink) { try { MongoClient mongoClient = fongo.getMongo(); DB mongoDefaultDb = mongoClient.getDB("test"); DBCollection mongoDefaultCollection = mongoDefaultDb.getCollection("test"); setField(mongoSink, "mongoClient", mongoClient); setField(mongoSink, "mongoDefaultDb", mongoDefaultDb); setField(mongoSink, "mongoDefaultCollection", mongoDefaultCollection); } catch (Exception ex) { throw new RuntimeException(ex); } } @Before public void prepareMongo() throws Exception { fongo = new Fongo("mongo test server"); Context mongoContext = new Context(); mongoContext.put("batchSize", "1"); mongoContext.put("mappingFile", "/mapping_definition_1.json"); mongoContext.put("mongoUri", "INJECTED"); mongoSink = new MongoSink(); injectFongo(mongoSink); Configurables.configure(mongoSink, mongoContext); Context channelContext = new Context(); channelContext.put("capacity", "10000"); channelContext.put("transactionCapacity", "200"); channel = new MemoryChannel(); channel.setName("junitChannel"); Configurables.configure(channel, channelContext); mongoSink.setChannel(channel); channel.start(); mongoSink.start(); } @After public void tearDownMongo() { channel.stop(); mongoSink.stop(); } @Test public void basicTest() throws Exception { Transaction tx = channel.getTransaction(); tx.begin(); ObjectNode jsonBody = new ObjectNode(JsonNodeFactory.instance); jsonBody.put("myString", "foo"); jsonBody.put("myInt32", 32); Map<String, String> headers = new HashMap<String, String>(); headers.put("myString", "bar"); // Overwrites the value defined in JSON body headers.put("myInt64", "64"); headers.put("myBoolean", "true"); headers.put("myDouble", "1.0"); headers.put("myNull", null); Date myDate = new Date(); headers.put("myDate", Long.toString(myDate.getTime())); headers.put("myString2", "baz"); Event event = EventBuilder.withBody(jsonBody.toString().getBytes(Charsets.UTF_8), headers); channel.put(event); tx.commit(); tx.close(); mongoSink.process(); DBObject result = fongo.getDB("test").getCollection("test").findOne(); System.out.println(result.toString()); assertThat(result).isNotNull(); assertThat(result.get("myString")).isEqualTo("bar"); assertThat(result.get("myInt32")).isEqualTo(32); assertThat(result.get("myInt32")).isInstanceOf(Integer.class); assertThat(result.get("myInt64")).isEqualTo(64L); assertThat(result.get("myInt64")).isInstanceOf(Long.class); assertThat(result.get("myBoolean")).isEqualTo(true); assertThat(result.get("myDouble")).isEqualTo(1.0); assertThat(result.get("myNull")).isNull(); assertThat(result.get("myDate")).isEqualTo(myDate); assertThat(result.get("myString2")).isNull(); assertThat(result.get("myStringMapped")).isEqualTo("baz"); } @Test public void emptyChannel() throws Exception { mongoSink.process(); assertThat(fongo.getDB("test").getCollection("test").count()).isEqualTo(0); } @Test public void batchSize() throws Exception { setField(mongoSink, "batchSize", 100); for (int i = 0; i < 200; i++) { Transaction tx = channel.getTransaction(); tx.begin(); Event event = EventBuilder.withBody("{ }".getBytes(Charsets.UTF_8)); channel.put(event); tx.commit(); tx.close(); } mongoSink.process(); assertThat(fongo.getDB("test").getCollection("test").count()).isEqualTo(100); } @Test public void noFullBatch() throws Exception { setField(mongoSink, "batchSize", 5); for (int i = 0; i < 3; i++) { Transaction tx = channel.getTransaction(); tx.begin(); Event event = EventBuilder.withBody("{ }".getBytes(Charsets.UTF_8)); channel.put(event); tx.commit(); tx.close(); } mongoSink.process(); assertThat(fongo.getDB("test").getCollection("test").count()).isEqualTo(3); } @Test(expected = MongoSinkException.class) public void errorOnProcess() throws Exception { DBCollection mockedCollection = Mockito.mock(DBCollection.class); Mockito.when(mockedCollection.save(Mockito.any(DBObject.class))).thenThrow(Error.class); setField(mongoSink, "mongoDefaultCollection", mockedCollection); Transaction tx = channel.getTransaction(); tx.begin(); Event event = EventBuilder.withBody("{ }".getBytes(Charsets.UTF_8)); channel.put(event); tx.commit(); tx.close(); mongoSink.process(); } @Test(expected = MongoSinkException.class) public void confSingleModeWithNoDefaultDB() throws Exception { final MongoSink mongoSink = new MongoSink(); final Context context = new Context(); context.put("dynamic", "false"); context.put("mongoUri", "mongodb://localhost:10000"); Configurables.configure(mongoSink, context); } @Test(expected = MongoSinkException.class) public void confSingleModeWithNoDefaultDBCollection() throws Exception { final MongoSink mongoSink = new MongoSink(); final Context context = new Context(); context.put("dynamic", "false"); context.put("mongoUri", "mongodb://localhost:10000/test"); Configurables.configure(mongoSink, context); } }
package com.tencent.mm.plugin.profile.ui; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import com.tencent.mm.model.au; import com.tencent.mm.openim.b.f; import com.tencent.mm.plugin.profile.ui.SayHiWithSnsPermissionUI.6; class SayHiWithSnsPermissionUI$6$1 implements OnCancelListener { final /* synthetic */ f lYj; final /* synthetic */ 6 lYk; SayHiWithSnsPermissionUI$6$1(6 6, f fVar) { this.lYk = 6; this.lYj = fVar; } public final void onCancel(DialogInterface dialogInterface) { au.DF().c(this.lYj); } }
package org.gnunet.integration.internal.models; public class ActorImpls { public String iName; public String implName; }
package dev.etna.jabberclient.xmpp; import android.content.Context; public class XMPPServiceException extends Exception { //////////////////////////////////////////////////////////// // ATTRIBUTES //////////////////////////////////////////////////////////// private XMPPServiceError error = null; //////////////////////////////////////////////////////////// // CONSTRUCTORS //////////////////////////////////////////////////////////// public XMPPServiceException(XMPPServiceError error, Context context, Throwable wrappedThrowable) { super(error.getLabel(context), wrappedThrowable); this.error = error; } public XMPPServiceException(String message, Throwable wrappedThrowable) { super(message, wrappedThrowable); } public XMPPServiceException(String message) { super(message); } public XMPPServiceException() { super(); } //////////////////////////////////////////////////////////// // ACCESSORS & MUTATORS //////////////////////////////////////////////////////////// public XMPPServiceError getError() { return this.error; } }
package edu.calstatela.cs245.qiao.project; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.SQLException; import javax.swing.*; public class AddFrame extends BaseFrame{ public AddFrame(){ super(500, 400); setFillForm(); JButton jbtNext = new JButton("Next"); panel.add(jbtNext); NextListenerClass nextListener = new NextListenerClass(); jbtNext.addActionListener(nextListener); JButton jbtSave = new JButton("Save"); panel.add(jbtSave); SaveListenerClass saveListener = new SaveListenerClass(); jbtSave.addActionListener(saveListener); } //------------- SaveListenerClass ------------------------------------------------ class SaveListenerClass implements ActionListener{ private String id, lastName, sex, birthDate, hireDate, jobStatus, payType, salary, yearS; @Override public void actionPerformed(ActionEvent e) { id = jtfId.getText(); lastName = jtfLastName.getText(); sex = (String)jcboSex.getSelectedItem(); birthDate = jtfBirthDate.getText(); hireDate = jtfHireDate.getText(); jobStatus = (String)jcboJobStatus.getSelectedItem(); payType = (String)jcboPayType.getSelectedItem(); salary = jtfSalary.getText(); yearS = jtfYearS.getText(); if(sex.equals("Male")){ sex = "M"; }else{ sex = "F"; } if(birthDate.equals("yyyy/mm/dd") || birthDate.equals("")){ birthDate = "1900/01/01"; } if(hireDate.equals("yyyy/mm/dd") || hireDate.equals("")){ hireDate = "1900/01/01"; } if(salary.equals("")){ salary = "-1"; } if(yearS.equals("")){ yearS = "-1"; } if( (!id.equals("")) && (!Validity.isInt(id)) ){ JOptionPane.showMessageDialog(null, "Employee ID need to be number format.", "Error", JOptionPane.ERROR_MESSAGE); }else if(lastName.equals("")){ JOptionPane.showMessageDialog(null, "Employee name cannot be empty.", "Warning", JOptionPane.WARNING_MESSAGE); }else if(!Validity.isDouble(salary)){ JOptionPane.showMessageDialog(null, "Employee salary need to be number format.", "Error", JOptionPane.ERROR_MESSAGE); }else if(!Validity.isInt(yearS)){ JOptionPane.showMessageDialog(null, "Employee year of service need to be number format.", "Error", JOptionPane.ERROR_MESSAGE); }else{ try { DBConnection.openConnection(); DBConnection.insertRow(id, lastName, sex, birthDate, hireDate, jobStatus, payType, salary, yearS); JOptionPane.showMessageDialog(null, "Record saved successfully.", "Save", JOptionPane.INFORMATION_MESSAGE); DBConnection.closeStatementConnection(); } catch (SQLException e1) { JOptionPane.showMessageDialog(null, e1, "Error", JOptionPane.ERROR_MESSAGE); } } } } //--------------- NextListenerClass --------------------------------------------------- class NextListenerClass implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { jtfId.setText(null); jtfLastName.setText(null); jcboSex.setSelectedIndex(0); jtfBirthDate.setText("yyyy/mm/dd"); jtfHireDate.setText("yyyy/mm/dd"); jcboJobStatus.setSelectedIndex(0); jcboPayType.setSelectedIndex(0); jtfSalary.setText(null); jtfYearS.setText(null); } } //------------- ------------------------------------------------ }
package com.lanhuawei.rongyunlhwtext; import android.net.Uri; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import io.rong.imkit.fragment.ConversationListFragment; import io.rong.imlib.model.Conversation; /** * Created by Ivan.L on 2018/5/28 . * 会话列表 */ public class ConversationListActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_conversation_list); ConversationListFragment conversationListFragment = new ConversationListFragment(); Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon() .appendPath("conversationlist") //设置私聊会话,该会话聚合显示 .appendQueryParameter(Conversation.ConversationType.PRIVATE.getName(), "false") //设置系统会话,该会话非聚合显示 .appendQueryParameter(Conversation.ConversationType.SYSTEM.getName(), "true") .build(); conversationListFragment.setUri(uri); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.add(R.id.conversationlist,conversationListFragment); transaction.commit(); } }
package com.openkm.extension.servlet; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.dropbox.client2.DropboxAPI.Account; import com.dropbox.client2.DropboxAPI.Entry; import com.dropbox.client2.exception.DropboxException; import com.dropbox.client2.exception.DropboxIOException; import com.dropbox.client2.exception.DropboxServerException; import com.dropbox.client2.exception.DropboxUnlinkedException; import com.openkm.api.OKMDocument; import com.openkm.api.OKMFolder; import com.openkm.api.OKMRepository; import com.openkm.automation.AutomationException; import com.openkm.bean.Document; import com.openkm.bean.Folder; import com.openkm.core.AccessDeniedException; import com.openkm.core.DatabaseException; import com.openkm.core.FileSizeExceededException; import com.openkm.core.ItemExistsException; import com.openkm.core.MimeTypeConfig; import com.openkm.core.NoSuchGroupException; import com.openkm.core.ParseException; 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.dao.extension.DropboxDAO; import com.openkm.dropbox.Dropbox; import com.openkm.extension.core.ExtensionException; import com.openkm.extension.frontend.client.bean.GWTDropboxAccount; import com.openkm.extension.frontend.client.bean.GWTDropboxEntry; import com.openkm.extension.frontend.client.bean.GWTDropboxStatusListener; import com.openkm.extension.frontend.client.service.OKMDropboxService; import com.openkm.frontend.client.OKMException; import com.openkm.frontend.client.constants.service.ErrorCode; import com.openkm.principal.PrincipalAdapterException; import com.openkm.servlet.frontend.OKMRemoteServiceServlet; import com.openkm.util.FileUtils; import com.openkm.util.GWTUtil; import com.openkm.util.PathUtils; /** * DropboxServlet * * @author sochoa */ public class DropboxServlet extends OKMRemoteServiceServlet implements OKMDropboxService { private static Logger log = LoggerFactory.getLogger(DropboxServlet.class); private static final long serialVersionUID = 1L; private static final String CATEGORY_DOCUMENT = "document"; private static final String CATEGORY_FOLDER = "folder"; private Dropbox dropbox; private static final Map<String, List<GWTDropboxStatusListener>> statusMap = new HashMap<String, List<GWTDropboxStatusListener>>(); @Override public String authorize() throws OKMException { try { dropbox = new Dropbox(); } catch (DropboxUnlinkedException e) { return null; // Case not allows application } catch (DropboxServerException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (DropboxIOException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (DropboxException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } return dropbox.getInfo().url; } @Override public GWTDropboxAccount access() throws OKMException { GWTDropboxAccount gwtDropboxAccount = new GWTDropboxAccount(); try { String usrId = getThreadLocalRequest().getRemoteUser(); if (dropbox == null) { if (DropboxDAO.getInstance().findByPk(usrId) != null) { dropbox = new Dropbox(); } else { return null; } } Account account; account = dropbox.access(usrId); gwtDropboxAccount.setCountry(account.country); gwtDropboxAccount.setDisplayName(account.displayName); gwtDropboxAccount.setQuota(account.quota); gwtDropboxAccount.setQuotaNormal(account.quotaNormal); gwtDropboxAccount.setQuotaShared(account.quotaShared); gwtDropboxAccount.setReferralLink(account.referralLink); gwtDropboxAccount.setUid(account.uid); } catch (DropboxUnlinkedException e) { return null; } catch (DropboxServerException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (DropboxIOException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (DropboxException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (DatabaseException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Database), e.getMessage()); } return gwtDropboxAccount; } @Override public void exportDocument(String path, String uuid) throws OKMException { InputStream is = null; try { String docPath = OKMRepository.getInstance().getNodePath(null, uuid); Document doc = OKMDocument.getInstance().getProperties(null, docPath); is = OKMDocument.getInstance().getContent(null, docPath, true); String dbPath = path + "/" + PathUtils.getName(docPath); dropbox.uploadFile(dbPath, is, doc.getActualVersion().getSize()); } catch (PathNotFoundException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_PathNotFound), e.getMessage()); } catch (AccessDeniedException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_AccessDenied), e.getMessage()); } catch (RepositoryException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Repository), e.getMessage()); } catch (DatabaseException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Database), e.getMessage()); } catch (IOException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_IO), e.getMessage()); } catch (DropboxUnlinkedException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (DropboxServerException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (DropboxIOException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (DropboxException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } finally { IOUtils.closeQuietly(is); } } @Override public void exportFolder(String path, String uuid) throws OKMException { try { // Clean status list if (statusMap.containsKey(getThreadLocalRequest().getRemoteUser())) { statusMap.remove(getThreadLocalRequest().getRemoteUser()); } exportFolderToDropbox(path, uuid); } catch (AccessDeniedException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_AccessDenied), e.getMessage()); } catch (PathNotFoundException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_PathNotFound), e.getMessage()); } catch (RepositoryException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Repository), e.getMessage()); } catch (DatabaseException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Database), e.getMessage()); } catch (DropboxUnlinkedException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (DropboxServerException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (DropboxIOException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (DropboxException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (PrincipalAdapterException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_PrincipalAdapter), e.getMessage()); } catch (IOException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_IO), e.getMessage()); } catch (ParseException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Parse), e.getMessage()); } catch (NoSuchGroupException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_NoSuchGroup), e.getMessage()); } } @Override public List<GWTDropboxEntry> search(String query, String category) throws OKMException { List<GWTDropboxEntry> list = new ArrayList<GWTDropboxEntry>(); try { List<Entry> listEntry = dropbox.search(query); for (Entry entry : listEntry) { GWTDropboxEntry gwtDropboxEntry = copy(entry); if (category.equals(CATEGORY_FOLDER) && entry.isDir) { list.add(gwtDropboxEntry); } else if (category.equals(CATEGORY_DOCUMENT) && !entry.isDir) { // Change MIME Type to defined into OpenKM gwtDropboxEntry.setMimeType(MimeTypeConfig.mimeTypes.getContentType(entry.fileName())); list.add(gwtDropboxEntry); } else if (category.equals("")) { // Change MIME Type to defined into OpenKM gwtDropboxEntry.setMimeType(MimeTypeConfig.mimeTypes.getContentType(entry.fileName())); list.add(gwtDropboxEntry); } } } catch (DropboxUnlinkedException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (DropboxServerException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (DropboxIOException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (DropboxException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } return list; } @Override public void importDocument(GWTDropboxEntry gwtDropboxEntry, String path) throws OKMException { File tmp = null; FileOutputStream fos = null; InputStream is = null; try { tmp = FileUtils.createTempFile(); fos = new FileOutputStream(tmp); dropbox.downloadFile(gwtDropboxEntry.getPath(), fos); fos.flush(); is = new FileInputStream(tmp); Document doc = new Document(); doc.setPath(path + "/" + gwtDropboxEntry.getFileName()); doc = OKMDocument.getInstance().create(null, doc, is); addToStatus(doc); // status log } catch (IOException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_IO), e.getMessage()); } catch (DropboxException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (PathNotFoundException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_PathNotFound), e.getMessage()); } catch (RepositoryException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Repository), e.getMessage()); } catch (DatabaseException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Database), e.getMessage()); } catch (FileSizeExceededException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_FileSizeExceeded), e.getMessage()); } catch (UserQuotaExceededException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_UserQuoteExceed), e.getMessage()); } catch (VirusDetectedException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Virus), e.getMessage()); } catch (AccessDeniedException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_AccessDenied), e.getMessage()); } catch (UnsupportedMimeTypeException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_UnsupportedMimeType), e.getMessage()); } catch (ItemExistsException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_ItemExists), e.getMessage()); } catch (AutomationException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Automation), e.getMessage()); } catch (PrincipalAdapterException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_PrincipalAdapter), e.getMessage()); } catch (ParseException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Parse), e.getMessage()); } catch (NoSuchGroupException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_NoSuchGroup), e.getMessage()); } catch (ExtensionException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Extension), e.getMessage()); } finally { IOUtils.closeQuietly(fos); IOUtils.closeQuietly(is); FileUtils.deleteQuietly(tmp); } } @Override public void importFolder(GWTDropboxEntry gwtDropboxEntry, String path) throws OKMException { try { // Clean status list if (statusMap.containsKey(getThreadLocalRequest().getRemoteUser())) { statusMap.remove(getThreadLocalRequest().getRemoteUser()); } importFolderToDropbox(gwtDropboxEntry, path); } catch (PathNotFoundException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_PathNotFound), e.getMessage()); } catch (DatabaseException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Database), e.getMessage()); } catch (AccessDeniedException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_AccessDenied), e.getMessage()); } catch (AutomationException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Automation), e.getMessage()); } catch (ItemExistsException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_ItemExists), e.getMessage()); } catch (RepositoryException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Repository), e.getMessage()); } catch (DropboxUnlinkedException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (DropboxServerException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (DropboxIOException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (DropboxException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (PrincipalAdapterException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_PrincipalAdapter), e.getMessage()); } catch (IOException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_IO), e.getMessage()); } catch (ParseException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Parse), e.getMessage()); } catch (NoSuchGroupException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_NoSuchGroup), e.getMessage()); } catch (ExtensionException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Extension), e.getMessage()); } } @Override public GWTDropboxEntry getRootDropbox() throws OKMException { GWTDropboxEntry gwtDropboxEntry = new GWTDropboxEntry(); try { Entry entry = dropbox.getRoot(); gwtDropboxEntry = copy(entry); gwtDropboxEntry.setChildren(true); } catch (DropboxUnlinkedException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (DropboxServerException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (DropboxIOException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (DropboxException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } return gwtDropboxEntry; } @Override public List<GWTDropboxEntry> getChildren(String parentPath) throws OKMException { List<GWTDropboxEntry> list = new ArrayList<GWTDropboxEntry>(); try { List<Entry> listEntry = dropbox.getClildren(parentPath); for (Entry entry : listEntry) { if (entry.isDir) { GWTDropboxEntry gwtDropboxEntry = copy(entry); list.add(gwtDropboxEntry); } } } catch (DropboxUnlinkedException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (DropboxServerException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (DropboxIOException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } catch (DropboxException e) { log.error(e.getMessage(), e); throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMDropboxService, ErrorCode.CAUSE_Dropbox), e.getMessage()); } return list; } /** * copy from dropbox entry to GWTDropboxEntry */ private GWTDropboxEntry copy(Entry e) throws DropboxUnlinkedException, DropboxServerException, DropboxIOException, DropboxException { GWTDropboxEntry dropboxEntry = new GWTDropboxEntry(); dropboxEntry.setBytes(e.bytes); dropboxEntry.setClientMTime(e.clientMtime); dropboxEntry.setHash(e.hash); dropboxEntry.setIcon(e.icon); dropboxEntry.setDeleted(e.isDeleted); dropboxEntry.setDir(e.isDir); dropboxEntry.setMimeType(e.mimeType); dropboxEntry.setModified(e.modified); dropboxEntry.setPath(e.path); dropboxEntry.setRev(e.rev); dropboxEntry.setRoot(e.root); dropboxEntry.setSize(e.size); dropboxEntry.setThumbExists(e.thumbExists); dropboxEntry.setFileName(e.fileName()); dropboxEntry.setParentPath(e.parentPath()); dropboxEntry.setChildren(dropbox.ischildren(e)); return dropboxEntry; } @Override public List<GWTDropboxStatusListener> statusListener() throws OKMException { List<GWTDropboxStatusListener> doneList = new ArrayList<GWTDropboxStatusListener>(getStatusList()); getStatusList().removeAll(doneList); return doneList; } /** * exportFolderToDropbox */ private void exportFolderToDropbox(String path, String uuid) throws AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException, DropboxUnlinkedException, DropboxServerException, DropboxIOException, DropboxException, PrincipalAdapterException, IOException, ParseException, NoSuchGroupException, OKMException { String fldPath = OKMRepository.getInstance().getNodePath(null, uuid); if (!path.equals("/")) { path += "/"; } path += PathUtils.getName(fldPath); Entry entry = dropbox.createFolder(path); // export folders for (Folder folder : OKMFolder.getInstance().getChildren(null, fldPath)) { if (OKMFolder.getInstance().getChildren(null, folder.getPath()) != null) { exportFolderToDropbox(entry.path, folder.getUuid()); addToStatus(folder); // status log } } // export documents for (Document document : OKMDocument.getInstance().getChildren(null, fldPath)) { exportDocument(entry.path, document.getUuid()); addToStatus(document); // status log } } /** * importFolderToDropbox */ private void importFolderToDropbox(GWTDropboxEntry gwtDropboxEntry, String path) throws PathNotFoundException, ItemExistsException, AccessDeniedException, RepositoryException, DatabaseException, AutomationException, OKMException, DropboxUnlinkedException, DropboxServerException, DropboxIOException, DropboxException, PrincipalAdapterException, IOException, ParseException, NoSuchGroupException, ExtensionException { Folder folder = new Folder(); folder.setPath(path + "/" + gwtDropboxEntry.getFileName()); folder = OKMFolder.getInstance().create(null, folder); addToStatus(folder); // status log for (Entry entry : dropbox.getClildren(gwtDropboxEntry.getPath())) { GWTDropboxEntry dropboxEntry = copy(entry); if (dropboxEntry.isDir()) { importFolderToDropbox(dropboxEntry, folder.getPath()); } else { importDocument(dropboxEntry, folder.getPath()); } } } /** * addToStatus */ private void addToStatus(Folder folder) throws PrincipalAdapterException, IOException, ParseException, NoSuchGroupException, AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { GWTDropboxStatusListener dsl = new GWTDropboxStatusListener(); dsl.setFolder(GWTUtil.copy(folder, null)); getStatusList().add(dsl); } /** * addToStatus */ private void addToStatus(Document doc) throws PrincipalAdapterException, IOException, ParseException, NoSuchGroupException, AccessDeniedException, PathNotFoundException, RepositoryException, DatabaseException { GWTDropboxStatusListener dsl = new GWTDropboxStatusListener(); dsl.setDocument(GWTUtil.copy(doc, null)); getStatusList().add(dsl); } /** * getStatusList */ private synchronized List<GWTDropboxStatusListener> getStatusList() { List<GWTDropboxStatusListener> status = null; String user = getThreadLocalRequest().getRemoteUser(); if (statusMap.containsKey(user)) { status = statusMap.get(user); } else { status = new ArrayList<GWTDropboxStatusListener>(); statusMap.put(user, status); } return status; } }
package datastructure.fenzhi; /** * @Author weimin * @Date 2020/10/22 0022 17:46 */ public class Hanoitower { public static void main(String[] args) { hannuotower(64,'a','b','c'); } public static void hannuotower(int num,char a,char b,char c){ if(num==1){ System.out.println("第1个盘从"+a+"到"+c); }else { hannuotower(num-1,a,c,b); System.out.println("第"+num+"个盘从"+a+"到"+c); hannuotower(num-1,b,a,c); } } }
package com.example.ahmed.octopusmart.ViewHolder; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.Switch; import android.widget.TextView; import com.example.ahmed.octopusmart.R; import com.kyleduo.switchbutton.SwitchButton; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.http.Body; /** * Created by ahmed on 23/12/2017. */ public class SettingItemViewHolder extends RecyclerView.ViewHolder{ @BindView(R.id.settings_item_title) public TextView title; @BindView(R.id.settings_item_image) public ImageView imageView; @BindView(R.id.settings_item_switch) public SwitchButton mswitch; @BindView(R.id.settings_no_click) public View no_click; public SettingItemViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } }
package com.septacore.ripple.preprocess; import java.util.ArrayList; /** * Static class used to log errors */ public class PPLogger { public static void reset() { getInstance().logList.clear(); } public static boolean empty() { return getInstance().logList.isEmpty(); } public static void log(int line, int col) { log (line, col, "Unknown error"); } public static void log(int line, int col, String msg) { getInstance().addEntry(line, col, msg); } public static String getLog() { return getInstance().toString(); } private static PPLogger instance = null; private static PPLogger getInstance() { if (instance == null) { instance = new PPLogger(); } return instance; } private ArrayList<PPLogEntry> logList; private PPLogger() { logList = new ArrayList<PPLogEntry>(); } private void addEntry(int line, int col, String msg) { logList.add(new PPLogEntry(line,col,msg)); } @Override public String toString() { StringBuilder out = new StringBuilder(); for (PPLogEntry entry : logList) { out.append(entry.toString()); out.append("\n"); } return out.toString(); } private class PPLogEntry { private final int line; private final int col; private final String msg; public PPLogEntry(int line, int col, String msg) { this.line = line; this.col = col; this.msg = msg; } @Override public String toString() { return String.format("Line: %d Col: %d - %s", line,col,msg); } public int getLine() { return line; } public int getCol() { return col; } public String getMsg() { return msg; } } }
package calculadora; public class NodoString { private String dato; private NodoString siguiente; public NodoString(String d){ this.setDato(d); this.setSiguiente(null); } public String getDato() { return dato; } public void setDato(String dato) { this.dato = dato; } public NodoString getSiguiente() { return siguiente; } public void setSiguiente(NodoString siguiente) { this.siguiente = siguiente; } }
package com.example.demo; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import java.io.BufferedReader; import java.io.FileReader; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.transaction.CannotCreateTransactionException; import com.example.demo.bl.MessageService; import com.example.demo.dl.MessageEntity; import com.example.demo.dl.MessageRepository; import com.example.demo.sl.MessageController; /** * This class containing a methods designed to test the logger of * MessageController class.<br> * TID-123321 * * @author serhii.shvets * */ @RunWith(SpringRunner.class) @SpringBootTest public class MessageControllerLoggerTest { @Autowired private MessageController mesCont; @MockBean private MessageService mesService; @Autowired private MessageRepository messageRepository; /* * Properties of MessageEntity object used in the testing. */ private MessageEntity mesEntity; private String expectedDataFromMessageEntity; String penultimateLineOfLog; private final Integer messageId = 1; private final String messageInitializationText = "Some text to post into the message"; /** * Actions performed before every test:<br> * &#20 1. Creating a new MessageEntity object with specified properties<br> * &#20 2. Reading the last line of ApplicationLog.log file<br> * * */ @Before public void setup() { mesEntity = new MessageEntity(); mesEntity.setMesId(messageId.longValue()); mesEntity.setText(messageInitializationText); mesEntity.setGrId(1L); mesEntity.setDate(); expectedDataFromMessageEntity += "Message with id " + mesEntity.getMesId() + ":\n"; expectedDataFromMessageEntity += "Text of a message: \n"; expectedDataFromMessageEntity += "\t" + mesEntity.getText() + "\n"; expectedDataFromMessageEntity += "Date of posting message: \n"; expectedDataFromMessageEntity += "\t " + mesEntity.getDate().toString() + "\n\n"; penultimateLineOfLog = getLastLineFromLog(); } private String getLastLineFromLog() { String resultString = ""; BufferedReader input; try { input = new BufferedReader(new FileReader("ApplicationLog.log")); String line; while ((line = input.readLine()) != null) { resultString = line; } input.close(); return resultString; } catch (Exception e) { return ("Exception caught " + e.toString()); } } /** * Case for testing a logger of postMessage(int id, String text, int grId) * method which is posting a new MessageEntity object to the database.<br> * In this test case is tested case when whole provided data is proper. * <p> * Expected result is new line in log ApplicationLog.log file reporting that * message with provided ID was created successfully. */ @Test public void postMessageSuccesfulLoggerPositiveTest() { Mockito.when(mesService.checkMessageIfExixting(messageId)).thenReturn(false); Mockito.when(mesService.postMessage(messageId, messageInitializationText, 1)).thenReturn(mesEntity); Mockito.when(mesService.getDataFromMessageEntity(mesEntity)).thenReturn(expectedDataFromMessageEntity); mesCont.postMessage(messageId, messageInitializationText); String lastLineOfLog = getLastLineFromLog(); assertThat(lastLineOfLog).describedAs("New line to log wasnt added.").doesNotContain(penultimateLineOfLog); assertThat(lastLineOfLog).describedAs("Actual last line of log is different from the expected one.") .contains("Posted new message with id= " + messageId); } /** * Case for testing a logger of postMessage(int id, String text, int grId) * method which is posting a new MessageEntity object to the database.<br> * In this test case is tested case when provided ID is occupied. * <p> * Expected result is new line in log ApplicationLog.log file reporting that * there is no way to post a new message with provided ID since there is another * message with the same ID. */ @Test public void postMessageUnsuccesfulLoggerPositiveTest() { Mockito.when(mesService.checkMessageIfExixting(any(int.class))).thenReturn(true); mesCont.postMessage(messageId, messageInitializationText); String lastLineOfLog = getLastLineFromLog(); assertThat(lastLineOfLog).describedAs("New line to log wasnt added.").doesNotContain(penultimateLineOfLog); assertThat(lastLineOfLog).describedAs("Actual last line of log is different from the expected one.") .contains("Unable to post a new message with ID " + messageId + " since message with provided ID is already exists."); } /** * Case for testing a logger of postMessage(int id, String text, int grId) * method which is posting a new MessageEntity object to the database.<br> * In this test case tested case when there are troubles with database * connection. * <p> * Expected result is new line in log ApplicationLog.log file reporting that * there are troubles with database connection. */ @Test public void postMessageCannotCreateTransactionExceptionNegativeTest() { String textOfException = "Text of exception"; CannotCreateTransactionException exception = new CannotCreateTransactionException(textOfException); Mockito.when(mesService.checkMessageIfExixting(any(int.class))).thenThrow(exception); mesCont.postMessage(messageId, messageInitializationText); String lastLineOfLog = getLastLineFromLog(); assertThat(lastLineOfLog).describedAs("New line to log wasnt added.").doesNotContain(penultimateLineOfLog); assertThat(lastLineOfLog).describedAs("Actual last line of log is different from the expected one.") .contains("Wrong database connection parameters. " + exception.toString()); } }
package com.fillikenesucn.petcare.adapters; import android.app.AlertDialog; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.widget.Toast; import com.fillikenesucn.petcare.R; import com.fillikenesucn.petcare.models.Acontecimiento; import com.fillikenesucn.petcare.models.Pet; import java.util.ArrayList; import java.util.Random; /** * Esta clase representa a un helper para la obtencion de información global para toda la aplicación * @author: Marcelo Lazo Chavez * @version: 2/04/2020 */ public class DataHelper { /** * Función que se encarga de retornar todas las especies del sistema * @return un listado con todas las especies del sistema (gatos y perros) */ public static ArrayList<String> GetSpecies(){ ArrayList<String> pets = new ArrayList<>(); pets.add(0, "Seleccione Especie"); pets.add("Perro"); pets.add("Gato"); return pets; } /** * Función que retorna un drawable con colores aleatorios * @return retorna un drawable de tipo rectangle con colores aleatorios */ public static GradientDrawable GetRandomColor(){ Random r = new Random(); int red=r.nextInt(255 - 0 + 1)+0; int green=r.nextInt(255 - 0 + 1)+0; int blue=r.nextInt(255 - 0 + 1)+0; GradientDrawable draw = new GradientDrawable(); draw.setShape(GradientDrawable.RECTANGLE); draw.setColor(Color.rgb(red,green,blue)); return draw; } /** * Función que se encarga de generar un dialog de alerta para la aplicación * @param context contexto asociado a la vista que llama a la función * @param tittle String que representa al titulo del dialog * @param description String que representa a la descripcion del dialog * @return Retorna un constructor de un dialog de alerta con los datos entregados como parámetros */ public static AlertDialog.Builder CreateAlertDialog(Context context, String tittle, String description){ AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setCancelable(true); builder.setTitle(tittle); builder.setMessage(description); return builder; } /** * Función que se encarga de verificar si una mascota es valida para registrarla * @param context contexto actual de la aplicación * @param pet objeto mascota con los datos a evaluar * @return retorna true si es una mascota valida, en caso contrario retorna false */ public static boolean VerificarMascotaValida(Context context, Pet pet){ int errorOcurred = 0; // NOMBRE, DIRECCION Y NACIMIENTO errorOcurred += VerificarString(context, pet.getName(), "Nombre Requerido"); errorOcurred += VerificarString(context, pet.getAddress(), "Dirección Requerida"); errorOcurred += VerificarString(context, pet.getBirthdate(), "Fecha de Nacimiento Requerida"); // VERIFICAR EPC if( pet.getEPC().equals(GetDefaultTagRFID()) ){ Toast.makeText(context,"Seleccione Tag Valido",Toast.LENGTH_SHORT).show(); errorOcurred++; } // ESPECIE if(DataHelper.GetSpecies().get(0).equals(pet.getSpecies())){ Toast.makeText(context,"Seleccione una Especie",Toast.LENGTH_SHORT).show(); errorOcurred++; } return errorOcurred > 0 ? false : true; } /** * Función que verifica si un string esta vacio * @param context contexto actual de la aplicación * @param txtEvaluate string a evaluar * @param error string que se desplegará como información al usuarios * @return retorna 1 si esta vacio y 0 si no lo esta */ public static int VerificarString(Context context, String txtEvaluate, String error){ if(txtEvaluate.isEmpty()){ Toast.makeText(context,error, Toast.LENGTH_SHORT).show(); return 1; }else{ return 0; } } /** * Función que se encarga de verificar si un acontecimiento es valido para registrarlo * @param context contexto actual de la aplicación * @param acontecimiento Objeto acontecimiento con los datos a validar * @param epc valor del epc asociado a la mascota del ascontecimiento * @return retorna true si el acontecimiento es valido, en caso contrario false */ public static boolean VerificarAcontecimientoValido(Context context,Acontecimiento acontecimiento, String epc){ int errorOcurred = 0; // TITULO Y FECHA errorOcurred += VerificarString(context, acontecimiento.getTitulo(), "Titulo Requerido"); errorOcurred += VerificarString(context, acontecimiento.getTitulo(), "Fecha Requerida"); if( epc.equals(GetDefaultTagRFID()) ){ Toast.makeText(context,"Seleccione Tag Valido",Toast.LENGTH_SHORT).show(); errorOcurred++; } return errorOcurred > 0 ? false : true; } /** * Función que retorna el string definido como el tag por defecto de la aplicación * @return retorna el string default */ public static String GetDefaultTagRFID(){ return "TAG: XXXX-XXXXXX-XXXXX"; } /** * Método que se encargá de retornar un listado con los identificadores de las imagenes estaticas * de los perros * @return retorna un listado con identificadores numericos de imagenes */ public static ArrayList<Integer> GetDogsImages(){ // DOGS ArrayList<Integer> dogDrawList = new ArrayList<>(); dogDrawList.add(R.drawable.perro1); dogDrawList.add(R.drawable.perro2); dogDrawList.add(R.drawable.perro3); dogDrawList.add(R.drawable.perro4); dogDrawList.add(R.drawable.perro5); dogDrawList.add(R.drawable.perro6); dogDrawList.add(R.drawable.perro7); dogDrawList.add(R.drawable.perro8); dogDrawList.add(R.drawable.perro9); return dogDrawList; } /** * Método que se encargá de retornar un listado con los identificadores de las imagenes estaticas * de los gatos * @return retorna un listado con identificadores numericos de imagenes */ public static ArrayList<Integer> GetCatsImages(){ // CATS ArrayList<Integer> catDrawList = new ArrayList<>(); catDrawList.add(R.drawable.gato1); catDrawList.add(R.drawable.gato2); catDrawList.add(R.drawable.gato3); catDrawList.add(R.drawable.gato4); return catDrawList; } }
package com.ftd.schaepher.coursemanagement.tools; import com.ftd.schaepher.coursemanagement.pojo.TableUserDepartmentHead; import com.ftd.schaepher.coursemanagement.pojo.TableUserTeacher; import com.ftd.schaepher.coursemanagement.pojo.TableUserTeachingOffice; import junit.framework.Assert; import junit.framework.TestCase; import java.util.ArrayList; import java.util.List; /** * Created by Schaepher on 2015/11/20. */ public class JsonToolsTest extends TestCase { String jsonString; List<TableUserTeacher> expectedList; @Override protected void setUp() throws Exception { super.setUp(); jsonString = "[{\"workNumber\":\"00001\",\"password\":\"00001\"," + "\"name\":\"西瓜\",\"sex\":\"男\",\"birthday\":\"1994\"," + "\"department\":\"\",\"telephone\":\"\",\"email\":\"\"}," + "{\"workNumber\":\"00002\",\"password\":\"00002\"," + "\"name\":\"南瓜\",\"sex\":\"男\",\"birthday\":\"1994\"," + "\"department\":\"\",\"telephone\":\"\",\"email\":\"\"}]"; expectedList = new ArrayList<>(); TableUserTeacher teacher1 = new TableUserTeacher(); teacher1.setWorkNumber("00001"); teacher1.setPassword("00001"); teacher1.setName("西瓜"); teacher1.setSex("男"); teacher1.setBirthday("1994"); teacher1.setDepartment(""); teacher1.setTelephone(""); teacher1.setEmail(""); expectedList.add(teacher1); TableUserTeacher teacher2 = new TableUserTeacher(); teacher2.setWorkNumber("00002"); teacher2.setPassword("00002"); teacher2.setName("南瓜"); teacher2.setSex("男"); teacher2.setBirthday("1994"); teacher2.setDepartment(""); teacher2.setTelephone(""); teacher2.setEmail(""); expectedList.add(teacher2); } @Override protected void runTest() throws Throwable { super.runTest(); } public void testGetJsonList() { List<TableUserTeacher> actualList = JsonTools.getJsonList(jsonString, TableUserTeacher.class); Assert.assertEquals(expectedList.toString(), actualList.toString()); } public void testGetJsonArrayString() { String jsonString = JsonTools.getJsonString(expectedList); List<TableUserTeacher> actualList = JsonTools.getJsonList(jsonString, TableUserTeacher.class); Assert.assertEquals(expectedList.toString(), actualList.toString()); } public void testGetJsonObject() { String jsonString = "{\"workNumber\":\"00001\",\"password\":\"00001\"," + "\"name\":\"西瓜\",\"sex\":\"男\",\"birthday\":\"1994\"," + "\"department\":\"\",\"telephone\":\"\",\"email\":\"\"}"; TableUserDepartmentHead expectHead = new TableUserDepartmentHead(); expectHead.setWorkNumber("00001"); expectHead.setPassword("00001"); expectHead.setName("西瓜"); expectHead.setSex("男"); expectHead.setBirthday("1994"); expectHead.setDepartment(""); expectHead.setTelephone(""); expectHead.setEmail(""); TableUserDepartmentHead actualHead = JsonTools.getJsonObject(jsonString,TableUserDepartmentHead.class); Assert.assertEquals(expectHead.toString(),actualHead.toString()); } public void testGetJsonObjectString(){ TableUserTeachingOffice expectOffice = new TableUserTeachingOffice(); expectOffice.setWorkNumber("00001"); expectOffice.setPassword("00001"); expectOffice.setName("南瓜"); expectOffice.setTelephone("119"); expectOffice.setEmail("123459876@qq.com"); String jsonArrayString = JsonTools.getJsonString(expectOffice); List<TableUserTeachingOffice> actualList = JsonTools.getJsonList(jsonArrayString, TableUserTeachingOffice.class); Assert.assertEquals(expectOffice.toString(),actualList.get(0).toString()); } }
package be.spring.app.model; import com.google.common.collect.Sets; import javax.persistence.*; import java.util.Set; /** * Created by u0090265 on 10/1/14. */ @Entity @Table(name = "doodle") public class Doodle { private long id; private Set<Presence> presences; @Id @GeneratedValue(strategy = GenerationType.TABLE) @Column(name = "id") public long getId() { return id; } public void setId(long id) { this.id = id; } @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @JoinColumn(name = "doodle_id") public Set<Presence> getPresences() { if (presences == null) presences = Sets.newHashSet(); return presences; } public void setPresences(Set<Presence> presences) { this.presences = presences; } @Transient public Presence.PresenceType isPresent(final Account account) { if (account == null) return Presence.PresenceType.ANONYMOUS; for (Presence p : getPresences()) { if (p.getAccount().equals(account)) { return p.isPresent() ? Presence.PresenceType.PRESENT : Presence.PresenceType.NOT_PRESENT; } } return Presence.PresenceType.NOT_FILLED_IN; } @Transient public int countPresences() { int i = 0; for (Presence p : getPresences()) { if (p.isPresent()) { i++; } } return i; } public Presence getPresenceFor(Account account) { if (presences == null) return null; for (Presence p : getPresences()) { if (p.getAccount().equals(account)) { return p; } } return null; } }
package ltim.master; import android.app.AlertDialog; import android.app.ListActivity; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.Toast; import db.ItemContract; import db.ItemDBHelper; public class Practica extends ListActivity { private Cursor cursor; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); updateUI(); } @Override protected void onRestart() { super.onRestart(); updateUI(); } public void updateUI() { ItemDBHelper helper = new ItemDBHelper(Practica.this); SQLiteDatabase sqlDB = helper.getReadableDatabase(); helper.onCreate(sqlDB); cursor = sqlDB.query(ItemContract.TABLE, new String[]{ItemContract.Columns._ID, ItemContract.Columns.ITEM, ItemContract.Columns.IMAGE}, null,null,null,null,null); SimpleCursorAdapter listAdapter = new SimpleCursorAdapter( this, R.layout.item, cursor, new String[] {ItemContract.Columns.ITEM, ItemContract.Columns.IMAGE}, new int[] {R.id.taskTextView, R.id.productImage}, 0 ); this.setListAdapter(listAdapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); MenuItem btn = menu.findItem(R.id.action_add_task); btn.setVisible(false); //Ocultam el botó del menú return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_add_task: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Afegir un element"); builder.setMessage("Introdueix el nom del nou element"); final EditText inputField = new EditText(this); builder.setView(inputField); builder.setPositiveButton("Afegir", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { String task = inputField.getText().toString(); ItemDBHelper helper = new ItemDBHelper(Practica.this); SQLiteDatabase db = helper.getWritableDatabase(); ContentValues values = new ContentValues(); values.clear(); values.put(ItemContract.Columns.ITEM,task); db.insertWithOnConflict(ItemContract.TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE); updateUI(); } }); builder.setNegativeButton("Cancelar",null); builder.create().show(); return true; case R.id.switch_activity: // Canviam d'Activity Intent i = new Intent(this, Categories.class); startActivity(i); return true; default: return false; } } /** * Es crida quan es pitja el botó "fet" * @param view */ public void onDoneButtonClick(View view) { View v = (View) view.getParent(); TextView taskTextView = (TextView) v.findViewById(R.id.taskTextView); String task = taskTextView.getText().toString(); String sql = String.format("DELETE FROM %s WHERE %s = '%s'", ItemContract.TABLE, ItemContract.Columns.ITEM, task); ItemDBHelper helper = new ItemDBHelper(Practica.this); SQLiteDatabase sqlDB = helper.getWritableDatabase(); sqlDB.execSQL(sql); String msg = "L'element \"" + task + "\" ha estat marcat com a \"comprat\""; Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); updateUI(); } }
package com.project.common_basic.hybrid.jscall; import com.project.common_basic.hybrid.BaseJsCallProcessor; import com.project.common_basic.hybrid.JsCallData; import com.project.common_basic.hybrid.NativeComponentProvider; import com.project.common_basic.mvp.NearWebLogicView; import org.json.JSONException; import org.json.JSONObject; /** * JS调用Toast提示 * * @author yamlee */ public class ToastProcessor extends BaseJsCallProcessor { public static final String FUNC_NAME = "toast"; private NearWebLogicView view; public ToastProcessor(NativeComponentProvider componentProvider) { super(componentProvider); } @Override public boolean onHandleJsQuest(JsCallData callData) { if (FUNC_NAME.equals(callData.getFunc())) { view = componentProvider.provideWebLogicView(); JSONObject jsonObject = null; try { jsonObject = new JSONObject(callData.getParams()); String msg = (String) jsonObject.get("msg"); view.showToast(msg); return true; } catch (JSONException e) { e.printStackTrace(); } } return false; } @Override public String getFuncName() { return FUNC_NAME; } }
package com.example.myretrofitapplication.constants; public class Constants { public static class baseUrl{ public final static String BASE_URL="http://komaltikka.freevar.com/user_retrotesting/"; } }
package edu.washington.cs.cse403d.coauthor.client.graphviz; import java.awt.Point; import java.awt.event.MouseEvent; import java.rmi.Naming; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.swing.JToolTip; import prefuse.Constants; import prefuse.Display; import prefuse.Visualization; import prefuse.action.ActionList; import prefuse.action.RepaintAction; import prefuse.action.animate.LocationAnimator; import prefuse.action.animate.PolarLocationAnimator; import prefuse.action.assignment.ColorAction; import prefuse.action.assignment.DataColorAction; import prefuse.action.layout.graph.ForceDirectedLayout; import prefuse.action.layout.graph.RadialTreeLayout; import prefuse.activity.Activity; import prefuse.activity.SlowInSlowOutPacer; import prefuse.controls.Control; import prefuse.controls.ControlAdapter; import prefuse.controls.DragControl; import prefuse.controls.FocusControl; import prefuse.controls.NeighborHighlightControl; import prefuse.controls.PanControl; import prefuse.controls.WheelZoomControl; import prefuse.controls.ZoomControl; import prefuse.controls.ZoomToFitControl; import prefuse.data.Graph; import prefuse.data.Node; import prefuse.data.Tuple; import prefuse.data.event.TupleSetListener; import prefuse.data.search.PrefixSearchTupleSet; import prefuse.data.tuple.TupleSet; import prefuse.render.DefaultRendererFactory; import prefuse.render.EdgeRenderer; import prefuse.render.LabelRenderer; import prefuse.util.ColorLib; import prefuse.util.display.DisplayLib; import prefuse.util.force.ForceSimulator; import prefuse.visual.VisualGraph; import prefuse.visual.VisualItem; import prefuse.visual.expression.InGroupPredicate; import edu.washington.cs.cse403d.coauthor.client.Services; import edu.washington.cs.cse403d.coauthor.client.searchui.AuthorResult; import edu.washington.cs.cse403d.coauthor.shared.CoauthorDataServiceInterface; /** * @author Sergey * abstract parent class for the various visualization objects; contains * methods common to all visualizations (initializing display/visualization, * adding co-authors to a single node, querying the backend for co-authors of * a single node, and redrawing the visualization */ public abstract class VisualExplorer { public static final String HOSTNAME = "attu2.cs.washington.edu"; protected Graph coAuthors; protected Visualization colorLayoutVis; protected Display dispCtrls; protected CoauthorDataServiceInterface backend; protected ActionList radialActionsArrangement; protected ActionList radialActionsSpacing; protected ActionList fdlActionsArrangement; protected ActionList fdlActionsRuntime; protected ForceDirectedLayout fdlLayout; protected ForceDirectedLayout spacingLayout; protected RadialTreeLayout radialArrangementLayout; protected PrefixSearchTupleSet searchTupleSet; protected DisplayLib dispActions; private boolean isInFDL; protected ActionList highlightControl; private String draw = "draw"; private final int ADD_COAUTHORS_CAP = 100; private final int MAX_CONCURRENT_THREADS = 20; /** * @return the underlying graph data structure */ public Graph getGraph(){ return this.coAuthors; } /** * @return the Visualization that sets all the colors and node layouts */ public Visualization getVisualization(){ return this.colorLayoutVis; } /** * Display is added into a JFrame/other gui object * @return the display for this graph visualization */ public Display getDisplay(){ return this.dispCtrls; } /** * Sets up a connection to the backend */ public void databaseInit(){ try { backend = (CoauthorDataServiceInterface) Naming.lookup("rmi://" + HOSTNAME + "/" + CoauthorDataServiceInterface.SERVICE_NAME); } catch (Exception e) { e.printStackTrace(); return; } } /** * sends a request to the backend for a list of co-authors of the passed authorName * @param authorName * @return a list of co-author names for the given author */ protected List<String> getCoAuthorList(String authorName){ String centerNode = authorName; List<String> coAu = null; try{ coAu = backend.getCoauthors(centerNode); } catch (RemoteException e) { e.printStackTrace(); } return coAu; } /** * used to find the Node in the prefuse graph that has authorName in it's name * @param authorName * @return */ protected Node findAuthor(String authorName){ Iterator authItr = this.coAuthors.nodes(); Node searchedFor = null; while(authItr.hasNext()){ Node current = (Node) authItr.next(); if(current.get("name").equals(authorName)){ searchedFor = current; } } return searchedFor; } /** * protected method to add the co-authors of the passed authorName and visualize them * figure out how to coherently add the names to the graph * @param authorName */ protected void addCoAuthors(String authorName){ List<String> moreAuthors = getCoAuthorList(authorName); synchronized (this.colorLayoutVis){ Node addTo = findAuthor(authorName); VisualItem addToVisItem = this.colorLayoutVis.getVisualItem("graph.nodes", addTo); // look for returned authors already in the graph; remove all authors already in // the graph from the search results Iterator authItr = this.coAuthors.nodes(); while(authItr.hasNext()){ Node current = (Node) authItr.next(); if(moreAuthors.contains(current.get("name"))){ // the graph already contains a node for one of the returned coauthors if(this.coAuthors.getEdge(addTo, current) == null) { this.coAuthors.addEdge(addTo, current); // add an edge between the clicked-on node and the coauthor node it has in the graph } moreAuthors.remove(current.get("name")); } } // add nodes for all query-returned co-authors that were not originally in the graph Iterator coAuItr = moreAuthors.iterator(); while(coAuItr.hasNext()){ String current = (String) coAuItr.next(); Node added = this.coAuthors.addNode(); added.set("name", current); added.set("visited",0); VisualItem addedVisItem = this.colorLayoutVis.getVisualItem("graph.nodes", added); addedVisItem.setEndX(addToVisItem.getX()); addedVisItem.setEndY(addToVisItem.getY()); this.searchTupleSet.index(addedVisItem,"name"); this.coAuthors.addEdge(addTo, added); } addTo.setInt("visited", 1); } this.updateVis(); } /** * adds coauthor nodes to all nodes currently in the graph */ public boolean addCoAuthorsToAllNodes(){ Iterator graphItr = this.coAuthors.nodes(); int nodeCt = this.coAuthors.getNodeCount(); ExecutorService pool = Executors.newFixedThreadPool(MAX_CONCURRENT_THREADS); if(nodeCt < ADD_COAUTHORS_CAP){ for (int i = 0; i < nodeCt; i++){ Node current = (Node) graphItr.next(); final String nodeName = (String) current.get("name"); pool.execute(new Runnable() { @Override public void run() { addCoAuthors(nodeName); } }); } if(this.isInFDL){ this.switchToFDL(); }else{ this.switchToRadialLayout(); } return true; }else { return false; } } /** * removes all children at the node with the passed authorName, assumes that * input is a valid node in the graph * @param authorName */ public void removeCoAuthors(String authorName){ synchronized(this.colorLayoutVis){ Node removeCoAuthorsFrom = findAuthor(authorName); Iterator childItr = removeCoAuthorsFrom.children(); while(childItr.hasNext()){ Node currentNode = (Node) childItr.next(); if (currentNode.getChildCount() > 0) this.removeCoAuthors(currentNode.getString("name")); this.coAuthors.removeNode(currentNode); } }} /** * removes all nodes that have degree 0 from the graph */ public void trimOneDegree(){ synchronized (this.colorLayoutVis){ Iterator nodeItr = this.coAuthors.nodes(); List<Integer> toBeDeleted = new ArrayList<Integer>(); while(nodeItr.hasNext()){ Node currentNode = (Node) nodeItr.next(); if (currentNode.getDegree() == 1){ toBeDeleted.add(currentNode.getRow()); } } for(int i =0; i<toBeDeleted.size();i++){ Node deleted = this.coAuthors.getNode(toBeDeleted.get(i)); this.coAuthors.removeNode(deleted); } } } /** * initializes the visualization parameters * * only used in constructor * @param initialGraph */ protected void visualizationInit(){ // add the graph to the visualization as the data group "graph" // nodes and edges are accessible as "graph.nodes" and "graph.edges" this.colorLayoutVis = new Visualization(); VisualGraph vg = (VisualGraph) this.colorLayoutVis.add("graph", this.coAuthors); this.colorLayoutVis.setInteractive("graph.edges", null, false); // -- 3. the renderers and renderer factory --------------------------- // draw the "name" label for NodeItems LabelRenderer labels = new LabelRenderer("name"); labels.setRoundedCorner(8, 8); // round the corners EdgeRenderer edges = new EdgeRenderer(); DefaultRendererFactory initialRf = new DefaultRendererFactory(labels); initialRf.add(new InGroupPredicate("graph.edges"), edges); this.colorLayoutVis.setRendererFactory(initialRf); initFdlAnimation(); initRadialAnimation(); ActionList draw = new ActionList(); draw.add(new ColorAction("graph.nodes", VisualItem.FILLCOLOR, ColorLib.green(1))); draw.add(new ColorAction("graph.nodes", VisualItem.STROKECOLOR, 0)); draw.add(new ColorAction("graph.nodes", VisualItem.TEXTCOLOR, ColorLib.rgb(0,0,0))); draw.add(new ColorAction("graph.edges", VisualItem.FILLCOLOR, ColorLib.gray(200))); draw.add(new ColorAction("graph.edges", VisualItem.STROKECOLOR, ColorLib.gray(200))); draw.add(new RepaintAction()); int[] palette = new int[] { ColorLib.rgb(190,190,255),ColorLib.rgb(255,180,180) }; // map nominal data values to colors using our provided palette DataColorAction fill = new DataColorAction("graph.nodes", "visited", Constants.NOMINAL, VisualItem.FILLCOLOR, palette); fill.add("_fixed", ColorLib.rgb(255,0,255)); fill.add("ingroup('_search_')", ColorLib.rgb(100,240,75)); fill.add("_highlight", ColorLib.rgb(255,100,100)); this.highlightControl = new ActionList(Activity.INFINITY); highlightControl.add(new RepaintAction()); highlightControl.add(fill); searchTupleSet = new PrefixSearchTupleSet(); searchTupleSet.setDelimiterString(","); this.colorLayoutVis.addFocusGroup(Visualization.SEARCH_ITEMS, searchTupleSet); searchTupleSet.addTupleSetListener(new TupleSetListener(){ @Override public void tupleSetChanged(TupleSet arg0, Tuple[] arg1, Tuple[] arg2) { colorLayoutVis.cancel("highlight"); colorLayoutVis.run("highlight"); colorLayoutVis.repaint(); } }); this.colorLayoutVis.putAction("draw", draw); this.colorLayoutVis.putAction("highlight", highlightControl); this.colorLayoutVis.runAfter(this.draw,"highlight"); this.switchToFDL(); } protected void initFdlAnimation(){ this.fdlActionsArrangement = new ActionList(500); // default behavior returns a force-directed layout fdlLayout = new ForceDirectedLayout("graph"); ForceSimulator fsim = ((ForceDirectedLayout) fdlLayout).getForceSimulator(); fsim.getForces()[0].setParameter(0, -8f); fsim.getForces()[0].setParameter(1, 200); fsim.getForces()[1].setParameter(0, .02f); fsim.getForces()[2].setParameter(1, 100); LocationAnimator transition = new LocationAnimator(); transition.setPacingFunction(new SlowInSlowOutPacer()); this.fdlActionsRuntime = new ActionList(3000); this.fdlActionsRuntime.add(transition); this.fdlActionsRuntime.setPacingFunction(new SlowInSlowOutPacer()); this.fdlActionsRuntime.add(fdlLayout); } protected void initRadialAnimation(){ this.radialArrangementLayout = new RadialTreeLayout("graph", 200); this.radialArrangementLayout.setAutoScale(false); ActionList arrangement = new ActionList(500); arrangement.add(this.radialArrangementLayout); PolarLocationAnimator pl = new PolarLocationAnimator(); pl.setPacingFunction(new SlowInSlowOutPacer()); arrangement.add(pl); this.radialActionsArrangement = arrangement; } /** * use this to update the graph display when there are any changes to the * underlying data structures, i.e. adding nodes to the table */ public void updateVis(){ synchronized(this.colorLayoutVis){ colorLayoutVis.run(draw); if (!this.isInFDL){ this.colorLayoutVis.run("arrange"); }else{ this.colorLayoutVis.run("ForceLayout"); } colorLayoutVis.setInteractive("graph.edges", null, false); }} public void switchToRadialLayout(){ synchronized(this.colorLayoutVis){ this.colorLayoutVis.removeAction("ForceLayout"); this.colorLayoutVis.putAction("arrange", this.radialActionsArrangement); this.colorLayoutVis.runAfter(draw, "arrange"); this.colorLayoutVis.runAfter("arrange", "spacing"); this.updateVis(); this.isInFDL = false; }} public void switchToFDL(){ synchronized(this.colorLayoutVis){ this.colorLayoutVis.removeAction("arrange"); this.colorLayoutVis.putAction("ForceLayout", this.fdlActionsRuntime); this.colorLayoutVis.runAfter(draw, "ForceLayout"); this.updateVis(); this.isInFDL = true; }} /** * initializes the display * * only used in constructor * @param initialVis */ protected void displayInit(){ // -- 5. the display and interactive controls ------------------------- Display d = new Display(this.colorLayoutVis); // control to detect when a node has been clicked on and perform the appropriate actions Control nodeClicked = new ControlAdapter(){ public void itemClicked(VisualItem item, MouseEvent e ){ VisualExplorer.this.coAuthors.nodes(); addCoAuthors(item.getString("name")); Services.getBrowser().go(new AuthorResult(item.getString("name"))); } }; d.setSize(500, 500); d.addControlListener(new DragControl()); d.addControlListener(new PanControl()); d.addControlListener(new ZoomControl(1)); d.addControlListener(new WheelZoomControl()); d.addControlListener(new ZoomToFitControl()); d.addControlListener(new NeighborHighlightControl()); d.addControlListener(new FocusControl(2)); d.addControlListener(nodeClicked); JToolTip tip = d.createToolTip(); tip.setToolTipText("Visualization controls: ** Click on a node to expand its coauthors. ** Use mouse wheel to zoom in/out." + "** Right click to auto-zoom to size of graph."); d.setCustomToolTip(tip); d.setBackgroundImage("logo_bg.png", true, false); this.dispCtrls = d; d.panTo(new Point(0,0)); } }
import java.awt.Color; import java.awt.Graphics; /** * The base class used for all shapes. * * Implements all basic behavior for shapes. * * All concrete shape types should inherit from this class. */ public abstract class AbstractShape implements Shape { protected int x,y; protected int width, height; protected Color color; }
package com.smxknife.java2.nio.selector; import org.junit.jupiter.api.Test; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.nio.channels.ServerSocketChannel; import java.util.concurrent.TimeUnit; /** * @author smxknife * 2020/10/13 */ public class _03_ServerSocketChannel_Backlog { // backlog测试server端 @Test public void backlogServerTest() { try(ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) { serverSocketChannel.bind(new InetSocketAddress("localhost", 6666), 60); ServerSocket serverSocket = serverSocketChannel.socket(); TimeUnit.SECONDS.sleep(20); // 在accept之前阻塞,让client都进入队列 boolean isRun = true; while (isRun) { Socket socket = serverSocket.accept(); socket.close(); } serverSocket.close(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } } // backlog测试client端 @Test public void backlogClientTest() throws IOException { for (int i = 0; i < 100; i++) { Socket socket = new Socket("localhost", 6666); socket.close(); System.out.println("客户端连接个数为:" + i); } } }
import java.util.Scanner; public class exer36 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int c1 = 0; int c2 = 0; int c3 = 0; int c4 = 0; int c5 = 0; int c6 = 0; float cont = 0; System.out.println("Digite 0 - Para finalizar o conjunto de votos"); System.out.println("1 - Farias;"); System.out.println("2 - Maria;"); System.out.println("3 - Alberto;"); System.out.println("4 - Ana;"); System.out.println("5 - Voto nulo;"); System.out.println("6 - Voto em branco;"); while(true) { System.out.println("Digite seu voto:"); int c = input.nextInt(); if( c == 0) break; if(c == 1) { c1++; cont++; }if(c == 2) { c2++; cont++; }if(c == 3) { c3++; cont++; }if( c == 4) { c4++; cont++; }if(c == 5) { c5++; cont++; }if(c ==6) { c6++; cont++; } } System.out.println("Quantidade de votos de cada candidato: "); System.out.println("Farias = " + c1); System.out.println("Maria = " + c2); System.out.println("Alberto = " + c3); System.out.println("Ana = " + c4); System.out.println("Total de votos nulos: " + c5); System.out.println("Total de votos em branco: " + c6); float percentualnulo = ((c5*100)/ cont); float percentualbranco = ((c6*100)/cont); System.out.println("Percentual de votos nulos: " + percentualnulo+"%"); System.out.println("Percentual de votos em branco: " + percentualbranco+"%"); System.out.println("Total de votos "+cont); input.close(); } }
package com.example.myapplication; import android.Manifest; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.os.Build; import android.os.Bundle; import android.os.Looper; import android.util.Log; import android.view.View; import android.widget.RelativeLayout; import android.widget.SearchView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.LocationCallback; import com.google.android.gms.location.LocationListener; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationResult; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.android.material.navigation.NavigationView; import com.google.android.material.snackbar.Snackbar; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.AbstractMap; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.TreeMap; import java.util.concurrent.ExecutionException; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import androidx.fragment.app.FragmentActivity; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, SearchView.OnQueryTextListener { RelativeLayout relativeLayout; private GoogleApiClient mGoogleApiClient; private Marker currentUserLocationMarker; private Double lat,lng; private JSONArray jsonArray = null; private static final int request_user_location_code = 99; public static final String TAG = MapsActivity.class.getSimpleName(); GoogleMap mMap; LocationRequest locationRequest; public Location lastLocation; FusedLocationProviderClient mFusedLocationClient; String queryCafe; private TreeMap<String, String> placesMapOfCafes = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); relativeLayout = findViewById(R.id.relativeLayoutSnackBar); mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this); final SearchView searchView = findViewById(R.id.searchView); searchView.setOnQueryTextListener(this); if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { checkUserLocationPermission(); } // Obtain the SupportMapFragment and get notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.mapView); mapFragment.getMapAsync(this); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; if(ContextCompat.checkSelfPermission(this , Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { buildGoogleApiClient(); mMap.setMyLocationEnabled(true); } } protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API).build(); mGoogleApiClient.connect(); } public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; private void checkLocationPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { new AlertDialog.Builder(this) .setTitle("Location Permission Needed") .setMessage("This app needs the Location permission, please accept to use location functionality") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //Prompt the user once explanation has been shown ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION ); } }) .create() .show(); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION ); } } } @Override public void onLocationChanged(Location location) { lastLocation = location; if(currentUserLocationMarker!=null) { currentUserLocationMarker.remove(); } lat = location.getLatitude(); lng = location.getLongitude(); Log.d("default lat", lat.toString()); Log.d("default long is ", lng.toString()); LatLng latLng = new LatLng(location.getLatitude() , location.getLongitude()); MarkerOptions markerOptions = new MarkerOptions(); markerOptions.position(latLng); markerOptions.title("My location!"); markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)); currentUserLocationMarker = mMap.addMarker(markerOptions); mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); mMap.animateCamera(CameraUpdateFactory.zoomBy(14)); if(mGoogleApiClient != null) { LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient , this); } } public boolean checkUserLocationPermission() { if(ContextCompat.checkSelfPermission(this , Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { if(ActivityCompat.shouldShowRequestPermissionRationale(this , Manifest.permission.ACCESS_FINE_LOCATION)) { ActivityCompat.requestPermissions(this , new String[]{Manifest.permission.ACCESS_FINE_LOCATION} , request_user_location_code); } else { ActivityCompat.requestPermissions(this , new String[]{Manifest.permission.ACCESS_FINE_LOCATION} , request_user_location_code); } return false; } else { return true; } } private String getUrl(double lat, double lng, String cafe){ StringBuilder googlePlaceUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?"); googlePlaceUrl.append("location="+lat+","+lng); googlePlaceUrl.append("&radius=10000"); googlePlaceUrl.append("&type="+cafe); googlePlaceUrl.append("&sensor=true"); googlePlaceUrl.append("&key="+"<enter key here>"); return googlePlaceUrl.toString(); } // public void showNearbyCafes(double latitude, double longitude){ // String cafe = "cafe"; // String url = getUrl(latitude, longitude, cafe); // Object[] dataTransfer = new Object[4]; // dataTransfer[0] = mMap; // dataTransfer[1] = url; // dataTransfer[2] = latitude; // dataTransfer[3] = longitude; // // Log.d("data", String.valueOf(dataTransfer)); // NearbyPlacesData nearbyPlacesData = new NearbyPlacesData(); // nearbyPlacesData.execute(dataTransfer); // View view = findViewById(R.id.mapView); // // } public void seeDetailsList(View view){ Log.d("Demo","inside details "); Intent myIntent = new Intent(this, DetailsCafe.class); Log.d("Demo placesMapOfCafe", String.valueOf(placesMapOfCafes)); myIntent.putExtra("nameAndRating",placesMapOfCafes); startActivity(myIntent); } @SuppressLint("LongLogTag") public void searchNearByNew(View view){ Log.d("inside image button","tests"); Log.d("Demo",String.valueOf(lat)); Log.d("Demo ",String.valueOf(lng)); String url = getUrl(lat, lng, "cafe"); Log.d("Demo" , "url = "+url); Object[] dataTransfer = new Object[4]; dataTransfer[0] = mMap; dataTransfer[1] = url; Snackbar snackbar = Snackbar.make(relativeLayout, "NearBy Cafes shown", Snackbar.LENGTH_LONG); snackbar.show(); Log.d("data", String.valueOf(dataTransfer)); GetNearByPlaces getNearByPlaces = new GetNearByPlaces(); try { String s = getNearByPlaces.execute(dataTransfer).get(); //Log.d("Demo nearby in main activity",s); JSONObject allNearbyDataInJSON = new JSONObject(s); jsonArray = allNearbyDataInJSON.getJSONArray("results"); Log.d("Demo all nearby in results ", String.valueOf(jsonArray)); placesMapOfCafes = new TreeMap<String,String>(); for(int i=0;i<jsonArray.length();i++){ JSONObject obj = jsonArray.getJSONObject(i); String rating = obj.optString("rating"); String name = obj.optString("name"); placesMapOfCafes.put(name,rating); } Log.d("Demo before send", String.valueOf(placesMapOfCafes)); } catch (ExecutionException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } @SuppressLint("LongLogTag") public void searchCafe(){ final String cafeName = queryCafe; Geocoder geocoder = new Geocoder(this); List<Address> addressList = null; MarkerOptions mo = new MarkerOptions(); try{ addressList = geocoder.getFromLocationName(cafeName,3); Log.d("addresslist",String.valueOf(addressList)); mMap.clear(); for (Address a : addressList){ Log.d("DemoLog loop called, cafe:= ", String.valueOf(a)); Log.d(" DemoLog Lat is ", String.valueOf(a.getLatitude())); Log.d("DemoLog Long is ", String.valueOf(a.getLongitude())); LatLng latlng = new LatLng(a.getLatitude(), a.getLongitude()); mo.position(latlng); mo.title("Cafe"); mMap.addMarker(mo); //mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 15)); mo.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)); //searchNearBy(a.getLatitude(),a.getLongitude()); } lat = addressList.get(0).getLatitude(); lng = addressList.get(0).getLongitude(); //mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11)); System.out.println("addresses are "+addressList); Log.d("addresses are ", String.valueOf(addressList)); } catch (IOException e) { e.printStackTrace(); } } @Override public boolean onQueryTextSubmit(String s) { queryCafe = s; searchCafe(); //showNearbyCafes(lastLocation.getLatitude(),lastLocation.getLongitude()); return true; } @Override public boolean onQueryTextChange(String s) { return false; } @Override public void onConnected(@Nullable Bundle bundle) { locationRequest = new LocationRequest(); locationRequest.setInterval(1100); locationRequest.setFastestInterval(1100); locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); if(ContextCompat.checkSelfPermission(this , Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient , locationRequest , this ); } } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } }
/* There are a total of n courses you have to take, labeled from 0 to n-1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses? */ class Solution { public boolean canFinish(int numCourses, int[][] prerequisites) { Map<Integer, Set<Integer>> map = new HashMap<> (); for (int[] edge : prerequisites) { Set<Integer> nodes = map.getOrDefault(edge[1], new HashSet<Integer> ()); nodes.add(edge[0]); map.put(edge[1], nodes); } boolean[] visited = new boolean[numCourses]; for (int key : map.keySet()) { boolean[] round = new boolean[numCourses]; if (!dfs(visited, round, map, key)) { return false; } } return true; } private boolean dfs(boolean[] visited, boolean[] round, Map<Integer, Set<Integer>> map, int start) { System.out.println(start); if (round[start]) return false; if (visited[start]) return true; visited[start] = true; round[start] = true; if (map.containsKey(start)) { for (int next : map.get(start)) { if (!dfs(visited, round, map, next)) { return false; } } } round[start] = false; return true; } }
package com.crud.medicalclinic.service; import com.crud.medicalclinic.domain.Patient; import com.crud.medicalclinic.repository.PatientRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class PatientService { @Autowired private PatientRepository patientRepository; public List<Patient> getAll() { return patientRepository.findAll(); } public Optional<Patient> get(long id) { return patientRepository.findById(id); } public Patient save(Patient patient) { return patientRepository.save(patient); } public void deleteById(long id) { patientRepository.deleteById(id); } }
package org.yuan.vita.photo.util; import java.io.File; import org.junit.Test; import org.junit.Assert; public class FTPUtilTest { @Test public void testFile() throws Exception { System.out.println(new File("demo.txt").getCanonicalPath()); // ==> E:\java\vita\demo.txt } @Test public void testUpload() { String filePath = "pom.xml"; String dirPath = "/test"; String fileName = "pom.xml"; boolean exists = false; FTPUtil.upload(filePath, dirPath, fileName); exists = FTPUtil.exists(dirPath, fileName); Assert.assertTrue(exists); FTPUtil.delete(dirPath, fileName); exists = FTPUtil.exists(dirPath, fileName); Assert.assertFalse(exists); FTPUtil.delete(dirPath); exists = FTPUtil.exists(dirPath); Assert.assertFalse(exists); } @Test public void testExists() { boolean exists = false; String dirPath = "test1"; exists = FTPUtil.exists(dirPath); Assert.assertFalse(exists); FTPUtil.create(dirPath); exists = FTPUtil.exists(dirPath); Assert.assertTrue(exists); FTPUtil.delete(dirPath); exists = FTPUtil.exists(dirPath); Assert.assertFalse(exists); } }
package com.java.app.beans.trans; import java.util.Date; public class TransUserDemoQuestionsDO { private Integer id; private TransSurvryInitDO init_id; private TransUserDetailsDO user_id; private Integer iDemomasterId; private String sQuestions; private String sAnswer; private String sOtherSpecify; private String sCreatedBy; private Date dCreatedDate; private String sUpdatedBy; private Date dUpdatedDate; private char cIsLeaderShip; public TransUserDemoQuestionsDO() {} public TransUserDemoQuestionsDO(Integer id) { this.id = id; } /** * @return the id */ public Integer getId() { return id; } /** * @param id the id to set */ public void setId(Integer id) { this.id = id; } /** * @return the sQuestions */ public String getsQuestions() { return sQuestions; } /** * @param sQuestions the sQuestions to set */ public void setsQuestions(String sQuestions) { this.sQuestions = sQuestions; } /** * @return the sAnswer */ public String getsAnswer() { return sAnswer; } /** * @param sAnswer the sAnswer to set */ public void setsAnswer(String sAnswer) { this.sAnswer = sAnswer; } /** * @return the sOtherSpecify */ public String getsOtherSpecify() { return sOtherSpecify; } /** * @param sOtherSpecify the sOtherSpecify to set */ public void setsOtherSpecify(String sOtherSpecify) { this.sOtherSpecify = sOtherSpecify; } /** * @return the init_id */ public TransSurvryInitDO getInit_id() { return init_id; } /** * @param init_id the init_id to set */ public void setInit_id(TransSurvryInitDO init_id) { this.init_id = init_id; } /** * @return the user_id */ public TransUserDetailsDO getUser_id() { return user_id; } /** * @param user_id the user_id to set */ public void setUser_id(TransUserDetailsDO user_id) { this.user_id = user_id; } /** * @return the iDemomasterId */ public Integer getiDemomasterId() { return iDemomasterId; } /** * @param iDemomasterId the iDemomasterId to set */ public void setiDemomasterId(Integer iDemomasterId) { this.iDemomasterId = iDemomasterId; } /** * @return the sCreatedBy */ public String getsCreatedBy() { return sCreatedBy; } /** * @param sCreatedBy the sCreatedBy to set */ public void setsCreatedBy(String sCreatedBy) { this.sCreatedBy = sCreatedBy; } /** * @return the dCreatedDate */ public Date getdCreatedDate() { return dCreatedDate; } /** * @param dCreatedDate the dCreatedDate to set */ public void setdCreatedDate(Date dCreatedDate) { this.dCreatedDate = dCreatedDate; } /** * @return the sUpdatedBy */ public String getsUpdatedBy() { return sUpdatedBy; } /** * @param sUpdatedBy the sUpdatedBy to set */ public void setsUpdatedBy(String sUpdatedBy) { this.sUpdatedBy = sUpdatedBy; } /** * @return the dUpdatedDate */ public Date getdUpdatedDate() { return dUpdatedDate; } /** * @param dUpdatedDate the dUpdatedDate to set */ public void setdUpdatedDate(Date dUpdatedDate) { this.dUpdatedDate = dUpdatedDate; } /** * @return the cIsLeaderShip */ public char getcIsLeaderShip() { return cIsLeaderShip; } /** * @param cIsLeaderShip the cIsLeaderShip to set */ public void setcIsLeaderShip(char cIsLeaderShip) { this.cIsLeaderShip = cIsLeaderShip; } }
package com.hiwes.cores.thread.thread3.Thread0218; /** * 实现set和get交替运行,从而实现生产者/消费者模式。 */ public class MyThread13 extends Thread { private P p; public MyThread13(P p) { super(); this.p = p; } @Override public void run() { while (true) { p.setValue(); } } } class MyThread13_2 extends Thread { private C c; public MyThread13_2(C c) { super(); this.c = c; } @Override public void run() { while (true) { c.getValue(); } } } /** * 生产者p */ class P { private String lock; public P(String lock) { super(); this.lock = lock; } public void setValue() { try { synchronized (lock) { if (!ValueObject2.value.equals("")) { lock.wait(); } String value = System.currentTimeMillis() + "_" + System.nanoTime(); System.out.println("set的值为:" + value); ValueObject2.value = value; lock.notify(); } } catch (InterruptedException e) { e.printStackTrace(); } } } /** * 消费者类 */ class C { private String lock; public C(String lock) { super(); this.lock = lock; } public void getValue() { try { synchronized (lock) { if (ValueObject2.value.equals("")) { lock.wait(); } System.out.println("get 的值是:" + ValueObject2.value); ValueObject2.value = ""; lock.notify(); } } catch (InterruptedException e) { e.printStackTrace(); } } } class ValueObject2 { public static String value = ""; } class Run13 { public static void main(String[] args) { String lock = new String(""); P p = new P(lock); C c = new C(lock); MyThread13 pThread = new MyThread13(p); MyThread13_2 cThread = new MyThread13_2(c); pThread.start(); cThread.start(); } }
package ru.kappers.service.parser; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import ru.kappers.model.CurrencyRate; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.time.LocalDate; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; /** * Парсер курсов валют для сайта ЦБ РФ */ @Slf4j @Service public class CBRFDailyCurrencyRatesParser { private final JsonParser jsonParser = new JsonParser(); @Getter private final URL cbrfUrl; /** Ссылка на JSON курсов валют ЦБ РФ по умолчанию */ public static final String CBRF_DAILY_JSON_DEFAULT_URL = "https://www.cbr-xml-daily.ru/daily_json.js"; @Autowired public CBRFDailyCurrencyRatesParser() throws MalformedURLException { this(new URL(CBRF_DAILY_JSON_DEFAULT_URL)); } public CBRFDailyCurrencyRatesParser(URL cbrfUrl) { log.debug("CBRFDailyCurrencyRatesParser(cbrfUrl: {})...", cbrfUrl); this.cbrfUrl = cbrfUrl; } /** * Парсить курсы валют с сайта ЦБ РФ * @return список курсов валют * @throws RuntimeException если во время парсинга произошла ошибка */ public List<CurrencyRate> parseFromCBRF() { log.debug("parseFromCBRF()..."); return parseFromURL(cbrfUrl); } /** * Парсить курсы валют с сайта * @param url ссылка на сайт * @return список курсов валют * @throws RuntimeException если во время парсинга произошла ошибка */ public List<CurrencyRate> parseFromURL(URL url) { log.debug("parseFromURL(url: {})...", url); final String json = getJSONStringFromURL(url); return parseFromJSON(json); } protected String getJSONStringFromURL(URL url) { log.debug("getJSONStringFromURL(url: {})...", url); StringBuilder sb = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) { String s; while ((s = reader.readLine()) != null) { sb.append(s); } } catch (IOException e) { String msg = "CBR daily JSON reading error"; log.error(msg, e); throw new RuntimeException(msg, e); } return sb.toString(); } /** * Парсить курсы валют из строки JSON-а * @param json строка с JSON * @return список курсов валют */ public List<CurrencyRate> parseFromJSON(String json) { log.debug("parseFromJSON(json: {})...", json); JsonObject object = (JsonObject) jsonParser.parse(json); LocalDate date = ZonedDateTime.parse(object.get("Date").getAsString(), DateTimeFormatter.ISO_ZONED_DATE_TIME) .toLocalDate(); JsonObject valutes = object.get("Valute").getAsJsonObject(); if (valutes.size() == 0) { return Collections.emptyList(); } List<CurrencyRate> currencyRates = new ArrayList<>(valutes.size()); for (Map.Entry<String, JsonElement> entries : valutes.entrySet()) { JsonObject value = entries.getValue().getAsJsonObject(); CurrencyRate rate = CurrencyRate.builder() .numCode(value.get("NumCode").getAsString()) .charCode(value.get("CharCode").getAsString()) .name(value.get("Name").getAsString()) .date(date) .nominal(value.get("Nominal").getAsInt()) .value(value.get("Value").getAsBigDecimal()) .build(); currencyRates.add(rate); } return currencyRates; } }
package com.example.kevin.weatherclothingapp; import android.app.ListFragment; import android.os.Bundle; //import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; /** * Created by Kevin on 10/26/2015. */ public class SimpleWeatherForecastFragment extends ListFragment { ImageView mWeatherIcon; TextView mTemperature; TextView mDate; ArrayList<String> mDays = new ArrayList<>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //TODO this fragment should make a request of the APICreator to the data needed for the weather data. } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.simple_weather_forecast_fragment, container, false); mDays.add("This is test 1."); mDays.add("This is test 2."); mDays.add("This is test 3."); mDays.add("This is test 4."); mDays.add("This is test 5."); mWeatherIcon = (ImageView)v.findViewById(R.id.weather_img); mTemperature = (TextView)v.findViewById(R.id.temp); mDate = (TextView)v.findViewById(R.id.date); ArrayAdapter mDaysAdapter = new ArrayAdapter(inflater.getContext(), android.R.layout.simple_list_item_single_choice, mDays); setListAdapter(mDaysAdapter); return super.onCreateView(inflater, container, savedInstanceState); } }
package com.tencent.mm.plugin.sport.c; public interface c { void bFH(); }
package ru.otus.orm.sql.generator; public class SqlStringBuilder { public static StringBuilder deletekLastChar(StringBuilder sb) { if (sb.length() == 0) return sb; if (sb.lastIndexOf(",") == sb.length()-1) { int lastIdx = sb.lastIndexOf(","); sb.delete(lastIdx, sb.length()); } return sb; } public static StringBuilder clearSymbols(StringBuilder sb) { if (!sb.toString().startsWith("\"") || sb.toString().startsWith("\\")) { deletekLastChar(sb); return sb; } sb.deleteCharAt(0); sb.delete(sb.length()-2, sb.length()); sb.trimToSize(); return sb; } public static StringBuilder objectStringWraper(StringBuilder sb, Object object) { sb.append(stringBuild(object)); sb.append(","); return sb; } public static StringBuilder valuesWraper(StringBuilder sb) { deletekLastChar(sb); int idx = sb.indexOf("?"); if (idx > 0) { sb.insert(idx, "("); sb.append(")"); return sb; } sb.insert(0, "("); sb.append(")"); return sb; } public static StringBuilder stringBuild(Object object) { var sb = new StringBuilder(); sb.append('\''); for(int i = 0; i < object.toString().length(); i++) { char c = object.toString().charAt(i); if (c >= 0x20 && c != '\"' && c != '\\' ) { sb.append(c); } else { switch (c) { case '\\': sb.append('\\'); sb.append(c); break; case '\b': sb.append('\\'); sb.append('b'); break; case '\f': sb.append('\\'); sb.append('f'); break; case '\n': sb.append('\\'); sb.append('n'); break; case '\r': sb.append('\\'); sb.append('r'); break; case '\t': sb.append('\\'); sb.append('t'); break; default: String hex = "000" + Integer.toHexString(c); sb.append("\\u").append(hex.substring(hex.length() - 4)); } } } sb.append('\''); return sb; } public static StringBuilder objectStringBuild(Object object) { var sb = new StringBuilder(); sb.append(object.toString()); sb.append(","); return sb; } }
package core.TestData; public class TestVariables { public static final String COUNTRY = "Argentina"; public static final String USER_NAME = "Alex"; public static final String USER_GENDER = "Male"; public static final String PRODUCT_TAB_NAME = "Products"; public static final String CART_TAB_NAME = "Cart"; }
package demo3; public class Squeak implements QuackBehavior { @Override public void quack() { System.out.println("Rubber duck squeak"); } }
package com.thanhviet.userlistarchvm.db; import android.arch.lifecycle.LiveData; import android.arch.lifecycle.MutableLiveData; import android.arch.persistence.db.SupportSQLiteDatabase; import android.arch.persistence.room.Database; import android.arch.persistence.room.Room; import android.arch.persistence.room.RoomDatabase; import android.content.Context; import android.support.annotation.NonNull; import com.thanhviet.userlistarchvm.AppExecutors; import com.thanhviet.userlistarchvm.db.dao.UserDao; import com.thanhviet.userlistarchvm.db.entity.UserEntity; import java.util.List; /** * Created by FRAMGIA\bui.dinh.viet on 19/07/18. */ @Database(entities = { UserEntity.class }, version = 1) public abstract class UserRoomDB extends RoomDatabase { public abstract UserDao mUserDao(); public static final String DATABASE_NAME = "user-list-archvm-db"; private static UserRoomDB sInstance; private final MutableLiveData<Boolean> mIsDatabaseCreated = new MutableLiveData<>(); public static UserRoomDB getInstance(final Context context, final AppExecutors executors) { if (sInstance == null) { synchronized (UserRoomDB.class) { if (sInstance == null) { sInstance = buildDatabase(context.getApplicationContext(), executors); sInstance.updateDatabaseCreated(context.getApplicationContext()); } } } return sInstance; } private static UserRoomDB buildDatabase(final Context appContext, final AppExecutors executors) { return Room.databaseBuilder(appContext, UserRoomDB.class, DATABASE_NAME) .addCallback(new Callback() { @Override public void onCreate(@NonNull SupportSQLiteDatabase db) { super.onCreate(db); executors.diskIO().execute(new Runnable() { @Override public void run() { UserRoomDB database = UserRoomDB.getInstance(appContext, executors); List<UserEntity> userEntities = DataGenerator.generateUsers(); insertData(database, userEntities); database.setDatabaseCreated(); } }); } }) .build(); } private static void insertData(final UserRoomDB database, final List<UserEntity> userEntities) { database.runInTransaction(new Runnable() { @Override public void run() { database.mUserDao().insertAll(userEntities); } }); } private void updateDatabaseCreated(final Context context) { if (context.getDatabasePath(DATABASE_NAME).exists()) { setDatabaseCreated(); } } private void setDatabaseCreated() { mIsDatabaseCreated.postValue(true); } public LiveData<Boolean> getDatabaseCreated() { return mIsDatabaseCreated; } }
package game; import communication.CommunicationAnswer; import communication.CommunicationHandler; import communication.CommunicationTypes; import domain.*; import main.ConnectionHandler; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class GameRunner implements Runnable { private Game game; private final ConnectionHandler connectionHandler; private final String username; private final ScoreCounter scoreCounter; private final Scanner scanner = new Scanner(System.in); public GameRunner(Game game, ConnectionHandler connectionHandler, String username) { this.game = game; this.connectionHandler = connectionHandler; this.scoreCounter = new ScoreCounter(game); this.username = username; } public GameRunner(Game game, ConnectionHandler connectionHandler, ScoreCounter scoreCounter, String username) { this.game = game; this.username = username; this.connectionHandler = connectionHandler; this.scoreCounter = scoreCounter; } @Override public void run() { runGame(); } private void runGame() { try { while(true) { printGameState(); Player player = getThisPlayer(); assert player != null; if(game.getStage().equals("bet") && game.getTurn().equals(player.getUsername())) { System.out.printf("Fase de apostas! O maior valor apostado foi %f, sua aposta foi %f e você precisa igualar se quiser continuar jogando.\n", game.getCurrentBet(), player.getBet()); System.out.println("Vai apostar quanto? Pra correr digite -1. Lembrando que o valor é somado ao que você já apostou."); double bet; do { bet = scanner.nextDouble(); if(bet != -1 && bet + player.getBet() < game.getCurrentBet()) { System.out.println("Pelo menos precisa completar a aposta atual, se não aguentar corre!"); } if(bet != -1 && bet > player.getBalance()) { System.out.println("Não é permitido apostar o que não tem."); } } while(bet != -1 && bet + player.getBet() < game.getCurrentBet()); CommunicationHandler.of(connectionHandler).sendMessage(CommunicationTypes.RAISE_DECISION, RaiseDecision.networkTransferable(), new RaiseDecision(bet, bet == -1)); } if(game.getStage().equals("draw") && game.getTurn().equals(player.getUsername())) { System.out.println("Fase de puxar cartas! Quer puxar outra carta (p) ou manter (m)?"); String answer = scanner.next(); CommunicationHandler.of(connectionHandler).sendMessage(CommunicationTypes.DRAW_DECISION, DrawDecision.networkTransferable(), new DrawDecision(answer.equals("m"))); } CommunicationAnswer answer = CommunicationHandler.of(connectionHandler).getMessage( Arrays.asList(CommunicationTypes.GAME_INFO, CommunicationTypes.GAME_END), Arrays.asList(Game.networkTransferable(), GameEndInfo.gameEndInfoNetworkTransferable())); if (answer.getType() == CommunicationTypes.GAME_END) { GameEndInfo endInfo = (GameEndInfo) answer.getValue(); String winnersInfo = endInfo.getWinners().size() != 0 ? String.join(",\n", endInfo.getWinners()) : "Casa"; System.out.printf("Fim de jogo! Vencedores:\n %s.\n\n", winnersInfo); goToPlayAgainHandler(endInfo.getWinners()); break; } else { game = (Game) answer.getValue(); } } } catch (IOException exception) { exception.printStackTrace(); } } private void printGameState() { Player player = getThisPlayer(); assert player != null; System.out.printf("Você tem %f de saldo e %f apostados.\n", player.getBalance(), player.getBet()); System.out.println("Suas cartas: "); System.out.println(player.getCards().size() + " Cards."); for (Card card : player.getCards()) { System.out.printf("%s\n", card); } System.out.printf("Sua pontuação: %d\n", player.getValue()); System.out.println(); System.out.println("Seus oponentes: "); for (Player opponent : game.getPlayers()) { System.out.printf("%s com %f de saldo e %f apostados, status %s, primeira carta %s \n", opponent.getUsername(), opponent.getBalance(), opponent.getBet(), opponent.getStatus(), opponent.getCards().get(0)); } System.out.printf("Carta da casa: %s \n", game.getCroupietCard()); System.out.println("Vez de " + game.getTurn()); } private Player getThisPlayer() { for (Player player : game.getPlayers()) { if(player.getUsername().equals(username)) { return player; } } return null; } private void goToPlayAgainHandler(List<String> winners) { Thread playAgainThread = new Thread(new PlayAgainManager(connectionHandler, getThisPlayer(), winners, scoreCounter)); playAgainThread.start(); } }
package com.elepy.handlers; import com.elepy.dao.Crud; import com.elepy.exceptions.ElepyException; import com.elepy.http.HttpContext; import com.elepy.models.ModelContext; import com.fasterxml.jackson.databind.ObjectMapper; public final class DisabledHandler<T> implements ActionHandler<T>, ServiceHandler<T> { @Override public void handleAction(HttpContext context, Crud<T> dao, ModelContext<T> modelContext, ObjectMapper objectMapper) throws Exception { block(); } @Override public void handleCreate(HttpContext context, Crud<T> crud, ModelContext<T> modelContext, ObjectMapper objectMapper) { block(); } @Override public void handleDelete(HttpContext context, Crud<T> crud, ModelContext<T> modelContext, ObjectMapper objectMapper) { block(); } @Override public void handleFindMany(HttpContext context, Crud<T> crud, ModelContext<T> modelContext, ObjectMapper objectMapper) { block(); } @Override public void handleFindOne(HttpContext context, Crud<T> crud, ModelContext<T> modelContext, ObjectMapper objectMapper) { block(); } @Override public void handleUpdatePut(HttpContext context, Crud<T> crud, ModelContext<T> modelContext, ObjectMapper objectMapper) { block(); } @Override public void handleUpdatePatch(HttpContext context, Crud<T> crud, ModelContext<T> modelContext, ObjectMapper objectMapper) throws Exception { block(); } private void block() { throw new ElepyException("Not found", 404); } }
package com.jim.multipos.ui.start_configuration.pos_data; import com.jim.multipos.config.scope.PerFragment; import com.jim.multipos.ui.settings.pos_details.PosDetailsPresenter; import com.jim.multipos.ui.settings.pos_details.PosDetailsPresenterImpl; import dagger.Binds; import dagger.Module; @Module public abstract class PosDataPresenterModule { @Binds @PerFragment abstract PosDataPresenter providePosDataPresenter(PosDataPresenterImpl presenter); }
package data; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.DatabaseErrorHandler; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.widget.Toast; import java.util.ArrayList; import bean.Table; /** * Created by 洒笑天涯 on 2015/11/20. * Function: */ public class TableDataHelper extends SQLiteOpenHelper { private static final int VERSION = 1; public static final String tableName = "table_list"; private static TableDataHelper instance; private static Context context; public TableDataHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } public TableDataHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) { super(context, tableName, null, VERSION); } public TableDataHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) { super(context, name, factory, version, errorHandler); } public TableDataHelper(Context context) { super(context, tableName, null, VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table " + tableName + "(tab_id integer primary key autoincrement,table_name varchar(25),version int)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } /*** * @return 创建数据库, 得到单例的数据库 */ public synchronized static TableDataHelper getInstance(Context context) { TableDataHelper.context = context; if (instance == null) { synchronized (TableDataHelper.class) { instance = new TableDataHelper(context); } } return instance; } /*** * @return 新建了新的表, 插入到输入库中 */ public void insertNewTable(String tableNames, String version, ArrayList<String> pameters, CharacterHelper chHelper) { SQLiteDatabase tableDb = instance.getWritableDatabase(); Cursor cursor = tableDb.rawQuery("select * from table_list", new String[]{}); int count = cursor.getCount() + 1; while (cursor.moveToNext()) { String tableName = cursor.getString(cursor.getColumnIndex("table_name")); if (tableName.equals(tableNames)) { showToast("该名字在数据库中已经存在"); return; } } insert2Characters(pameters, chHelper, count); ContentValues values = new ContentValues(); values.put("tab_id", count); values.put("table_name", tableNames); values.put("version", version); tableDb.insert(tableName, null, values);//往表中插入数据 } /*** * @return 将字段插入到数据库中 */ private void insert2Characters(ArrayList<String> pameters, CharacterHelper chHelper, int count) { SQLiteDatabase chDB = chHelper.getWritableDatabase(); ContentValues mChaValues = new ContentValues(); for (int j = 0; j < pameters.size(); j++) { mChaValues.put("characters", pameters.get(j)); mChaValues.put("trackid", count); chDB.insert(CharacterHelper.tableName, null, mChaValues); } } private void showToast(String toast) { Toast.makeText(context, toast, Toast.LENGTH_SHORT).show(); } /** * @return 查询所有数据 */ public ArrayList<Table> queryAll() { ArrayList<Table> mData = new ArrayList<>(); SQLiteDatabase db = instance.getReadableDatabase(); Cursor cursor = db.rawQuery("select * from " + tableName, new String[]{}); while (cursor.moveToNext()) { String id = cursor.getString(cursor.getColumnIndex("tab_id")); String version = cursor.getString(cursor.getColumnIndex("version")); String tableName = cursor.getString(cursor.getColumnIndex("table_name")); mData.add(new Table(id, tableName, version)); } return mData; } }
/* * LumaQQ - Java QQ Client * * Copyright (C) 2004 luma <stubma@163.com> * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.tsinghua.lumaqq.ui.wizard.search; import java.util.ArrayList; import java.util.List; /** * 管理搜索结果,负责管理分页 * * @author luma */ public class SearchResult { // 分页,每个对象又是一个List,包含了实际的数据 public List<List<? extends Object>> pages; private static List<Object> EMPTY = new ArrayList<Object>(); public SearchResult() { pages = new ArrayList<List<? extends Object>>(); } /** * 得到一页 * * @param index * 页索引,从0开始,0表示第一页 * @return * List */ public List<?> getPage(int index) { if(index < 0 || index >= getPageCount()) return EMPTY; return pages.get(index); } /** * 添加一页 * * @param page * List */ public void addPage(List<? extends Object> page) { pages.add(page); } /** * 所有的数据放到一个List中返回 * * @return * List */ public List<Object> getAll() { List<Object> all = new ArrayList<Object>(); for(List<? extends Object> c : pages) all.addAll(c); return all; } /** * @return * 页数 */ public int getPageCount() { return pages.size(); } /** * 清楚所有数据 */ public void clear() { pages.clear(); } }
package com.paisheng.instagme.widget; import android.content.Context; import android.graphics.drawable.AnimationDrawable; import android.text.TextUtils; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.paisheng.instagme.R; import com.paisheng.lib.widget.reloadview.PageTips; /** * @author: liaoshengjian * @Filename: * @Description: * @Copyright: Copyright (c) 2016 Tuandai Inc. All rights reserved. * @date: 2017/8/8 18:49 */ public class ReloadTipsView extends RelativeLayout { private LinearLayout layLMain; private View mView; private ImageView mSpinnerImageView; private TextView mTvTips, mTvTipsDesc1; private ImageView mImgLogo; public ReloadTipsView(Context context) { super(context); init(context); } public ReloadTipsView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void init(Context context) { mView = LayoutInflater.from(context).inflate(R.layout.view_rtv_load_tips, this, true); layLMain = (LinearLayout) mView.findViewById(R.id.layLMain); mImgLogo = (ImageView) mView.findViewById(R.id.imgLogo); mTvTips = (TextView) mView.findViewById(R.id.tvTips); mTvTipsDesc1 = (TextView) mView.findViewById(R.id.tvTipsDesc1); mSpinnerImageView = (ImageView) mView.findViewById(R.id.spinnerImageView); } private void showTips() { mImgLogo.setVisibility(View.VISIBLE); mTvTips.setVisibility(View.VISIBLE); mTvTipsDesc1.setVisibility(View.VISIBLE); mView.setVisibility(View.VISIBLE); mSpinnerImageView.setVisibility(View.GONE); } public void showFailureTips() { showTips(); mImgLogo.setImageResource(R.drawable.rtv_crash); mTvTips.setText(R.string.rtv_service_tips); } public void showEmptyTips() { showTips(); mImgLogo.setImageResource(R.drawable.rtv_empty_investment_norecord); mTvTips.setText(R.string.rtv_not_data); } public void showEmptyTips(int drawable) { showTips(); if (drawable > 0) { mImgLogo.setImageResource(drawable); } else { mImgLogo.setImageResource(R.drawable.rtv_empty_investment_norecord); } mTvTips.setText(R.string.rtv_not_data); } public void showNoNetworkTips() { showTips(); mImgLogo.setImageResource(R.drawable.rtv_empty_investment_nonetwork); mTvTips.setText(R.string.rtv_not_net); } public void showCustomEmptyTips(PageTips pageTips) { if (pageTips == null || TextUtils.isEmpty(pageTips.getTips())) { showEmptyTips(); } if (pageTips.getIconResid() > 0) { mImgLogo.setVisibility(View.VISIBLE); mImgLogo.setImageResource(pageTips.getIconResid()); } else { mImgLogo.setVisibility(View.GONE); } mTvTips.setVisibility(View.VISIBLE); mTvTips.setText(pageTips.getTips()); mTvTipsDesc1.setVisibility(View.VISIBLE); mView.setVisibility(View.VISIBLE); mSpinnerImageView.setVisibility(View.GONE); } /** * 设置重新加载监听 * * @param listener void * @author longluliu * @date 2014-4-2 下午4:32:58 */ public void setOnReloadDataListener(final LoadTipsListener listener) { if (listener != null && layLMain != null) { layLMain.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { showProgressBar(); listener.clickReloadData(); } }); } } /** * 显示load * void * * @author longluliu * @date 2014-4-2 下午4:33:48 */ public void showProgressBar() { mView.setVisibility(View.VISIBLE); mSpinnerImageView.setVisibility(View.VISIBLE); AnimationDrawable spinner = (AnimationDrawable) mSpinnerImageView.getBackground(); spinner.start(); mTvTips.setVisibility(View.GONE); mTvTipsDesc1.setVisibility(View.GONE); } @Override public void setVisibility(int visibility) { super.setVisibility(visibility); AnimationDrawable spinner = (AnimationDrawable) mSpinnerImageView.getBackground(); spinner.stop(); } @Override public boolean onTouchEvent(MotionEvent event) { return true; } /** * 隐藏 * void * * @author longluliu * @date 2014-4-2 下午4:33:48 */ public void goneView() { mView.setVisibility(View.GONE); } public interface LoadTipsListener { void clickReloadData(); } }
package com.tencent.xweb.sys; import android.graphics.Bitmap; import android.view.View; import android.webkit.WebChromeClient; import android.webkit.WebChromeClient.CustomViewCallback; import android.webkit.WebView; import android.webkit.WebViewClient; import com.tencent.xweb.c.f; import com.tencent.xweb.e; public final class d implements f { WebViewClient vCT = new WebViewClient(); WebChromeClient vCU = new WebChromeClient(); WebView vCV; public d(WebView webView) { this.vCV = webView; } public final void w(String str, Bitmap bitmap) { this.vCT.onPageStarted(this.vCV, str, bitmap); } public final void onShowCustomView(View view, CustomViewCallback customViewCallback) { } public final void onHideCustomView() { } public final boolean a(String str, String str2, com.tencent.xweb.f fVar) { return false; } public final boolean b(String str, String str2, com.tencent.xweb.f fVar) { return false; } public final boolean a(String str, String str2, String str3, e eVar) { return false; } }
package com.example.user.mychat.firebase; import android.content.Context; import android.database.Cursor; import com.example.user.mychat.ChatApplication; import com.example.user.mychat.model.Message; import com.example.user.mychat.database.DBHelper; import com.firebase.client.ChildEventListener; import com.firebase.client.DataSnapshot; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import java.util.HashMap; import java.util.Map; public class FireBaseManager implements ChildEventListener{ private static final String FIREBASE_URL = "https://mysquar-test.firebaseio.com/room1"; private static final String AUTHOR_TAG = "author"; private static final String MESSAGE_TAG = "message"; private Firebase mFireBaseRef; private OnMessageUpdatedListener mListener; private String mAuthorName; private DBHelper mDBHelper; public FireBaseManager(Context context){ Firebase.setAndroidContext(context); mFireBaseRef = new Firebase(FIREBASE_URL); mFireBaseRef.addChildEventListener(this); mAuthorName = ChatApplication.getInstance().getUsername(); mDBHelper = new DBHelper(context); } public String getAuthorName(){ return mAuthorName; } public void setOnMessageUpdatedListener(OnMessageUpdatedListener listener){ mListener = listener; } public Cursor getAllMessage(){ return mDBHelper.getAllChat(); } public void insertText(String value){ Map<String, String> post = new HashMap<String, String>(); post.put(AUTHOR_TAG, mAuthorName); post.put(MESSAGE_TAG, value); mFireBaseRef.push().setValue(post); } @Override public void onChildAdded(DataSnapshot dataSnapshot, String s) { if(dataSnapshot.getValue() instanceof Map) { Map<String, Object> newPost = (Map<String, Object>) dataSnapshot.getValue(); Message message = new Message().update(mDBHelper.getData(dataSnapshot.getKey())); if(message == null) { message = new Message(dataSnapshot.getKey(), (String) newPost.get(AUTHOR_TAG), (String) newPost.get(MESSAGE_TAG)); mDBHelper.insertMessage(message.getId(), message.getAuthor(), message.getMessage()); if (mListener != null) { mListener.onMessageChange(message); } } } } @Override public void onChildChanged(DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(DataSnapshot dataSnapshot) { } @Override public void onChildMoved(DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(FirebaseError firebaseError) { } public interface OnMessageUpdatedListener{ public void onMessageChange(Message message); } }
package zx.soft.restlet_demo; import java.io.IOException; import org.restlet.data.Form; import org.restlet.resource.ClientResource; import org.restlet.resource.ResourceException; /** * Hello world! * */ public class RetrievingWebpageDemo { public static void main(final String[] args) { // //等价于curl http://localhost:8182/\?sentence\=xxx ClientResource resource = new ClientResource("http://localhost:8182/?sentence=我很好"); // Customize the referrer property resource.setReferrerRef("http://www.mysite.org"); // Write the response entity on the console try { //以get方式访问server resource.get().write(System.out); } catch (ResourceException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("\n"); // curl -X POST --data '{"type":"neg","text":"综合消息,近日,湖南湘潭县妇幼保健院一产妇死亡, // 经媒体报道引发关注。"}' --header 'Content-Type:application/json' http://localhost:8182 // resource = new ClientResource("http://192.168.3.23:8182/"); resource = new ClientResource("http://localhost:8182/"); //创建表单 Form form = new Form(); form.add("text", "综合消息,近日,湖南湘潭县妇幼保健院一产妇死亡, 经媒体报道引发关注。"); // form.add("text", "abc"); form.add("type", "neg"); try { //以post方式提交表单 resource.post(form).write(System.out); } catch (ResourceException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("\nHello World in ClientResource"); } }
package com.bowlong.pinyin; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Vector; import com.bowlong.bio2.B2InputStream; import com.bowlong.objpool.StringBufPool; import com.bowlong.util.LRUCache; import com.bowlong.util.NewMap; @SuppressWarnings("unchecked") public class PinYin { static private final PinYin py = new PinYin(); private static NewMap<String, String> p = null; private static LRUCache<String, Object> cache = new LRUCache<String, Object>( 128); private PinYin() { reloadPy(); } public void reloadPy() { try { if (p == null) { InputStream is = getClass().getResourceAsStream("pinyin.bio2"); p = B2InputStream.readMap(is); } } catch (Exception e) { e.printStackTrace(); } } public static final List<String> py(String s) { return getPy(s); } public static final List<String> getPy(String s) { if (s == null) return new Vector<String>(); String _key = "__getPy" + s; if (cache.containsKey(_key)) return ((List<String>) cache.get(_key)); if (p == null) py.reloadPy(); List<String> ret = new ArrayList<String>(); int len = s.length(); for (int n = 0; n < len; n++) { String k = s.substring(n, n + 1); String v = (String) p.get(k); v = v == null ? k : v; ret.add(v); } cache.put(_key, ret); return ret; } public static final List<String> shortPy(String s) { return getShortPy(s); } public static final List<String> getShortPy(String s) { if (s == null) return new Vector<String>(); String _key = "__getShortPy" + s; if (cache.containsKey(_key)) return ((List<String>) cache.get(_key)); List<String> r = getPy(s); List<String> ret = new ArrayList<String>(); for (String v : r) { String v1 = v.substring(0, 1); ret.add(v1); } cache.put(_key, ret); return ret; } public static final String upperPinYin(String s) { if (s == null) return ""; String _key = "__upperPinYin" + s; if (cache.containsKey(_key)) return (String) cache.get(_key); StringBuffer sb = StringBufPool.borrowObject(); try { List<String> r = getPy(s); for (String v : r) { if (v != null && v.length() > 1) { sb.append(v.substring(0, 1).toUpperCase() + v.substring(1, v.length())); } } String ret = sb.toString(); cache.put(_key, ret); return ret; } finally { StringBufPool.returnObject(sb); } } public static final String pinYin(String s) { return getPinYin(s); } public static final String getPinYin(String s) { if (s == null) return ""; String _key = "__getPinYin" + s; if (cache.containsKey(_key)) return (String) cache.get(_key); if (p == null) { py.reloadPy(); } StringBuffer sb = StringBufPool.borrowObject(); try { int len = s.length(); for (int n = 0; n < len; n++) { String k = s.substring(n, n + 1); String v = (String) p.get(k); if (v == null) sb.append(k); else { if (sb.length() > 0 && sb.charAt(sb.length() - 1) != ' ') { sb.append(' '); } sb.append(v); } } String ret = sb.toString(); cache.put(_key, ret); return ret; } finally { StringBufPool.returnObject(sb); } } public static final String upperShortPinYin(String s) { if (s == null) return ""; String _key = "__upperShortPinYin" + s; if (cache.containsKey(_key)) return (String) cache.get(_key); String ret = getShortPinYin(s); if (ret != null && ret.length() > 1) { ret = ret.substring(0, 1).toUpperCase() + ret.substring(1, ret.length()); } cache.put(_key, ret); return ret; } public static final String shortPinYin(String s) { return getShortPinYin(s); } public static final String getShortPinYin(String s) { if (s == null) return ""; String _key = "__getShortPinYin" + s; if (cache.containsKey(_key)) return (String) cache.get(_key); if (p == null) { py.reloadPy(); } StringBuffer sb = StringBufPool.borrowObject(); try { int len = s.length(); for (int n = 0; n < len; n++) { String k = s.substring(n, n + 1); String v = (String) p.get(k); if (v == null) sb.append(k); else { v = v.substring(0, 1); sb.append(v); } } String ret = sb.toString(); cache.put(_key, ret); return ret; } finally { StringBufPool.returnObject(sb); } } /** * 人民币转成大写 * * @param value * @return String */ public static final String rmb(double value) { String _key = "__rmb" + value; if (cache.containsKey(_key)) return (String) cache.get(_key); char[] hunit = { '拾', '佰', '仟' }; // 段内位置表示 char[] vunit = { '万', '亿' }; // 段名表示 char[] digit = { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' }; // 数字表示 long midVal = (long) (value * 100); // 转化成整形 String valStr = String.valueOf(midVal); // 转化成字符串 String head = valStr.substring(0, valStr.length() - 2); // 取整数部分 String rail = valStr.substring(valStr.length() - 2); // 取小数部分 String prefix = ""; // 整数部分转化的结果 String suffix = ""; // 小数部分转化的结果 // 处理小数点后面的数 if (rail.equals("00")) { // 如果小数部分为0 suffix = "整"; } else { suffix = digit[rail.charAt(0) - '0'] + "角" + digit[rail.charAt(1) - '0'] + "分"; // 否则把角分转化出来 } // 处理小数点前面的数 char[] chDig = head.toCharArray(); // 把整数部分转化成字符数组 char zero = '0'; // 标志'0'表示出现过0 byte zeroSerNum = 0; // 连续出现0的次数 for (int i = 0; i < chDig.length; i++) { // 循环处理每个数字 int idx = (chDig.length - i - 1) % 4; // 取段内位置 int vidx = (chDig.length - i - 1) / 4; // 取段位置 if (chDig[i] == '0') { // 如果当前字符是0 zeroSerNum++; // 连续0次数递增 if (zero == '0') { // 标志 zero = digit[0]; } else if (idx == 0 && vidx > 0 && zeroSerNum < 4) { prefix += vunit[vidx - 1]; zero = '0'; } continue; } zeroSerNum = 0; // 连续0次数清零 if (zero != '0') { // 如果标志不为0,则加上,例如万,亿什么的 prefix += zero; zero = '0'; } prefix += digit[chDig[i] - '0']; // 转化该数字表示 if (idx > 0) prefix += hunit[idx - 1]; if (idx == 0 && vidx > 0) { prefix += vunit[vidx - 1]; // 段结束位置应该加上段名如万,亿 } } if (prefix.length() > 0) prefix += '圆'; // 如果整数部分存在,则有圆的字样 String ret = prefix + suffix; cache.put(_key, ret); return ret; // 返回正确表示 } public static void main(String[] args) throws Exception { List<String> z = PinYin.py("中文从类继承的字段"); System.out.println(z); z = PinYin.shortPy("中文从类继承的字段"); System.out.println(z); String s = PinYin.pinYin("中文从类继承的字段"); System.out.println(s); s = PinYin.shortPinYin("中文从类继承的字段"); System.out.println(s); s = PinYin.upperShortPinYin("中文从类继承的字段"); System.out.println(s); s = PinYin.upperPinYin("中文从类继承的字段"); System.out.println(s); } }
package com.lyj.project; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.graphics.Color; import android.os.AsyncTask; import android.os.Bundle; import android.os.CountDownTimer; import android.os.StrictMode; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.ontbee.legacyforks.cn.pedant.SweetAlert.SweetAlertDialog; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.mail.MessagingException; import javax.mail.SendFailedException; public class JoinActivity extends Activity{ EditText join_name_et, join_id_et, join_pwd_et, join_pwd_check_et, join_email_et, join_phone_et; Button btn_join_id_check, btn_join_email_check, btn_join_join, btn_join_return; TextView join_pwd_check_msg, join_email_check_msg; String id, email; int email_check_num = 0; String id_join_check = ""; SweetAlertDialog sweetAlertDialog; private String emailCode; private String finalemail; //LayoutInflater dialog; -> 이렇게 하면 작아짐 왜지,,, View dialogLayout; Dialog emailcheckdialog; //다이얼로그용 EditText dialog_email_check_et; Button dialog_email_check_btn; TextView dialog_email_time_counter; CountDownTimer countDownTimer; final int TOTALCOUNT = 50 * 1000; //나중에 180으로 바꿔라!!!! final int COUNT_DOWN_INTERVAL = 1000; //onTick 메소드 호출할 간격 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_join); StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .permitDiskReads() .permitDiskWrites() .permitNetwork().build()); join_name_et = findViewById(R.id.join_name_et); join_id_et = findViewById(R.id.join_id_et); join_pwd_et = findViewById(R.id.join_pwd_et); join_pwd_check_et = findViewById(R.id.join_pwd_check_et); join_email_et = findViewById(R.id.join_email_et); join_phone_et = findViewById(R.id.join_phone_et); btn_join_id_check = findViewById(R.id.btn_join_id_check); btn_join_email_check = findViewById(R.id.btn_join_email_check); btn_join_join = findViewById(R.id.btn_join_join); btn_join_return = findViewById(R.id.btn_join_return); join_pwd_check_msg = findViewById(R.id.join_pwd_check_msg); join_email_check_msg = findViewById(R.id.join_email_check_msg); //아이디 중복체크 btn_join_id_check.setOnClickListener(id_check); //비밀번호 일치 확인 join_pwd_check_et.setOnKeyListener(pwd_check); //돌아가기 버튼 감지자 등록 btn_join_return.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(JoinActivity.this, LoginMainActivity.class); startActivity(i); finish(); } }); //이메일 체크 btn_join_email_check.setOnClickListener(email_check); //회원가입 버튼 감지자 등록 btn_join_join.setOnClickListener(join); }//onCreate() //아이디 중복 감지 View.OnClickListener id_check = new View.OnClickListener() { @Override public void onClick(View view) { id = join_id_et.getText().toString(); if(id.equals("")){ Toast.makeText(JoinActivity.this,"아이디를 입력하세요",Toast.LENGTH_SHORT).show(); }else { new JoinTask().execute("id=" + id, "type_id_check"); } } };//id_check //비밀번호 일치 감지 View.OnKeyListener pwd_check = new View.OnKeyListener() { @Override public boolean onKey(View view, int i, KeyEvent keyEvent) { if(!(join_pwd_et.getText().toString().equals("")) && !(join_pwd_check_et.getText().toString().equals(join_pwd_et.getText().toString()))) { join_pwd_check_msg.setText("비밀번호가 일치하지 않습니다!"); join_pwd_check_msg.setTextColor(Color.parseColor("#770303")); }else if(!(join_pwd_et.getText().toString().equals("")) && !(join_pwd_check_et.getText().toString().equals("")) && join_pwd_check_et.getText().toString().equals(join_pwd_et.getText().toString())){ join_pwd_check_msg.setText("비밀번호가 일치합니다!"); join_pwd_check_msg.setTextColor(Color.parseColor("#005C31")); } return false; } };//pwd_check //이메일 체크 버튼 View.OnClickListener email_check = new View.OnClickListener() { @Override public void onClick(View view) { email = join_email_et.getText().toString(); Pattern p = Pattern.compile("^[_a-zA-Z0-9-\\.]+@[\\.a-zA-Z0-9-]+\\.[a-zA-Z]+$"); Matcher m = p.matcher(join_email_et.getText().toString()); if (!m.matches()) { sweetAlertDialog = new SweetAlertDialog(JoinActivity.this, SweetAlertDialog.WARNING_TYPE); sweetAlertDialog.setTitleText("이메일 오류"); sweetAlertDialog.setContentText("이메일 형식이 올바르지 않습니다.\n 다시 입력 해 주세요."); sweetAlertDialog.setConfirmText("확인"); sweetAlertDialog.show(); join_email_et.setText(""); /*join_email_check_msg.setText("E-mail 형식이 올바르지 않습니다! 다시 입력해 주세요"); join_email_check_msg.setTextColor(Color.parseColor("#770303"));*/ } else { new JoinTask().execute("email=" + email, "type_email_check"); Log.i("my", "email_check_num1 : " + email_check_num); } } }; //마지막 판별 public void FinalEmail(){ if(email_check_num == 1) { emailCode = createEmailCode(); try { Log.i("my", "인증코드 : " + emailCode); JoinGMailSender joingMailSender = new JoinGMailSender("lyujin0131@gmail.com", "dbwls0131@"); joingMailSender.sendMail("코리아 자가 지킴이 인증코드", "인증코드를 입력해주세요.\n" + emailCode, "lyujin0131@gmail.com", join_email_et.getText().toString()); Log.i("my", "성공"); } catch (SendFailedException e) { Toast.makeText(getApplicationContext(), "이메일 형식이 잘못되었습니다.", Toast.LENGTH_SHORT).show(); } catch (MessagingException e) { Toast.makeText(getApplicationContext(), "인터넷 연결을 확인해주십시오", Toast.LENGTH_SHORT).show(); } catch (Exception e) { e.printStackTrace(); } //dialog = LayoutInflater.from(JoinActivity.this); //dialogLayout = dialog.inflate(R.layout.email_check_dialog, null);//view로 보여줌 emailcheckdialog = new Dialog(JoinActivity.this);//dialog 객체 생성 emailcheckdialog.setContentView(R.layout.email_check_dialog);//dialog에 inflate한 view탑재 emailcheckdialog.show(); countDownTimer(); }else if(email_check_num == 2){ sweetAlertDialog = new SweetAlertDialog(JoinActivity.this, SweetAlertDialog.WARNING_TYPE); sweetAlertDialog.setTitleText("이메일 오류"); sweetAlertDialog.setContentText("이미 가입된 이메일 입니다.\n 다른 이메일을 입력해 주세요."); sweetAlertDialog.setConfirmText("확인"); sweetAlertDialog.show(); join_email_et.setText(""); join_email_check_msg.setText("이미 가입 된 E-mail 입니다."); join_email_check_msg.setTextColor(Color.parseColor("#770303")); } } //이메일 코드 public String createEmailCode(){ //이메일 인증코드 생성 String[] str = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "1", "2", "3", "4", "5", "6", "7", "8", "9"}; String newCode = new String(); for (int x = 0; x < 6; x++){ int random = (int)(Math.random() * str.length); newCode += str[random]; } Log.i("my","이까지 온다 안온다"); return newCode; } //카운트 다운 메서드 public void countDownTimer(){ //줄어드는 시간을 나타내는 TV dialog_email_time_counter = (TextView)emailcheckdialog.findViewById(R.id.dialog_email_time_counter); //사용자 인증 번호 Et dialog_email_check_et = (EditText)emailcheckdialog.findViewById(R.id.dialog_email_check_et); //인증하기 버튼 dialog_email_check_btn = (Button)emailcheckdialog.findViewById(R.id.dialog_email_check_btn); /*dialog_email_check_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.i("plz","여긴오나"); } });*/ countDownTimer = new CountDownTimer(TOTALCOUNT, COUNT_DOWN_INTERVAL) { @Override public void onTick(long l) {//3분에서 1초마다 줄어듦 Log.i("plz", "여기 오긴하니"); long email_check_time_count = l / 1000; Log.i("plz", "time : " + email_check_time_count); if ((email_check_time_count - ((email_check_time_count / 60) * 60)) >= 10) { //초가 10보다 크면 그냥 출력 dialog_email_time_counter.setText((email_check_time_count / 60) + " : " + (email_check_time_count - ((email_check_time_count / 60) * 60))); } else { //초가 10보다 작으면 앞에 '0' 붙여서 같이 출력. ex) 02,03,04... dialog_email_time_counter.setText((email_check_time_count / 60) + " : 0" + (email_check_time_count - ((email_check_time_count / 60) * 60))); } //email_check_time_count는 종료까지 남은 시간 1분 = 60초 되므로, //분을 나타내려면 종료까지 남은 총 시간에 60을 나누면 그 몫이 분 //분을 제외하고 남은 초는, (총 남은 시간 - (분*60) = 남은 초) } @Override public void onFinish() { if(email_check_num == 3) { emailcheckdialog.cancel(); }else { sweetAlertDialog = new SweetAlertDialog(JoinActivity.this, SweetAlertDialog.WARNING_TYPE); sweetAlertDialog.setTitleText("이메일 인증 실패"); sweetAlertDialog.setContentText("인증시간이 초과되었습니다."); sweetAlertDialog.setConfirmText("확인"); sweetAlertDialog.show(); emailcheckdialog.cancel(); join_email_check_msg.setText("E-mail인증을 해주세요"); join_email_check_msg.setTextColor(Color.parseColor("#404040")); } } }.start(); dialog_email_check_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String user_answer = dialog_email_check_et.getText().toString(); if (user_answer.equals(emailCode)){ join_email_check_msg.setText("E-mail 인증 완료"); join_email_check_msg.setTextColor(Color.parseColor("#005C31")); btn_join_email_check.setEnabled(false); join_email_et.setEnabled(false); emailcheckdialog.cancel(); email_check_num = 3; countDownTimer.onFinish(); }else { // Toast.makeText(JoinActivity.this,"실패",Toast.LENGTH_SHORT).show(); sweetAlertDialog = new SweetAlertDialog(JoinActivity.this, SweetAlertDialog.WARNING_TYPE); sweetAlertDialog.setTitleText("인증코드 오류"); sweetAlertDialog.setContentText("인증코드를 확인해주세요"); sweetAlertDialog.setConfirmText("확인"); sweetAlertDialog.show(); dialog_email_check_et.setText(""); join_email_check_msg.setText("인증코드를 확인해 주세요"); join_email_check_msg.setTextColor(Color.parseColor("#770303")); } } }); } //회원가입 버튼 감지 View.OnClickListener join = new View.OnClickListener() { @Override public void onClick(View view) { if(id_join_check.equals("")) { if(join_id_et.getText().toString().equals("")){ //Toast.makeText(JoinActivity.this, "id를 입력하세요", Toast.LENGTH_SHORT).show(); sweetAlertDialog = new SweetAlertDialog(JoinActivity.this, SweetAlertDialog.WARNING_TYPE); sweetAlertDialog.setTitleText("회원가입 실패"); sweetAlertDialog.setContentText("ID를 입력하세요"); sweetAlertDialog.setConfirmText("확인"); sweetAlertDialog.show(); }else { //Toast.makeText(JoinActivity.this, "id중복체크를 하세요", Toast.LENGTH_SHORT).show(); //Toast.makeText(JoinActivity.this, "id를 입력하세요", Toast.LENGTH_SHORT).show(); sweetAlertDialog = new SweetAlertDialog(JoinActivity.this, SweetAlertDialog.WARNING_TYPE); sweetAlertDialog.setTitleText("회원가입 실패"); sweetAlertDialog.setContentText("ID를 중복체크를 해주세요"); sweetAlertDialog.setConfirmText("확인"); sweetAlertDialog.show(); } }else if(id_join_check.equals("already")){ //Toast.makeText(JoinActivity.this, "ID를 입력하세요", Toast.LENGTH_SHORT).show(); sweetAlertDialog = new SweetAlertDialog(JoinActivity.this, SweetAlertDialog.WARNING_TYPE); sweetAlertDialog.setTitleText("회원가입 실패"); sweetAlertDialog.setContentText("ID를 입력하세요"); sweetAlertDialog.setConfirmText("확인"); sweetAlertDialog.show(); }else if(id_join_check.equals("yes")) { String name = join_name_et.getText().toString(); String id = join_id_et.getText().toString(); String pwd = join_pwd_et.getText().toString(); String email = join_email_et.getText().toString(); String phone = join_phone_et.getText().toString(); String result = "name=" + name + "&id=" + id + "&pwd=" + pwd + "&email=" + email + "&phone=" + phone; new JoinTask().execute(result, "type_join"); } } };//join //회원가입,id중복체크 , email중복체크크 용 Async class JoinTask extends AsyncTask<String, Void, String>{ String ip = "192.168.102.18"; String sendMsg, receiveMsg; String serverip = "http://" + ip + ":9090/AndroidJSPProject/list.jsp"; @Override protected String doInBackground(String... strings) { String str = ""; try { URL url = new URL(serverip); //서버연결 HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("POST");//전송방식 OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream()); //서버로 전달할 내용 //type = type_id_check if(strings[1].equals("type_id_check")) { sendMsg = strings[0] + "&type=" + strings[1]; Log.i("my","id : " + strings[0]); Log.i("my","id : " + sendMsg); //서버로 값 전송 osw.write(sendMsg); osw.flush();//얼른가라!! //전송완료 후 서버에서 처리해준 결과값 받기 //getResponseCode() : 200(정상전송) //getResponseCode() : 404, 500등,,,(비정상전송) if (conn.getResponseCode() == conn.HTTP_OK) { InputStreamReader is = new InputStreamReader(conn.getInputStream(), "UTF-8"); BufferedReader reader = new BufferedReader(is); String buffer = "";//한 줄씩 읽어옴 while ((str = reader.readLine()) != null) {//한 줄 씩 읽어서 넘긴다. buffer += str; } //최종적으로 돌려받은 JSON형식의 결과값 receiveMsg = buffer; JSONArray jarray = new JSONObject(receiveMsg).getJSONArray("res"); JSONObject jObject = jarray.getJSONObject(0); String result = jObject.optString("result"); if (result.equals("idok")) { receiveMsg = "idok"; } else { receiveMsg = "idno"; } } }else if(strings[1].equals("type_email_check")){ sendMsg = strings[0] + "&type=" + strings[1]; osw.write(sendMsg); osw.flush(); if (conn.getResponseCode() == conn.HTTP_OK) { InputStreamReader is = new InputStreamReader(conn.getInputStream(), "UTF-8"); BufferedReader reader = new BufferedReader(is); String buffer = ""; while ((str = reader.readLine()) != null) { buffer += str; } receiveMsg = buffer; JSONArray jarray = new JSONObject(receiveMsg).getJSONArray("res"); JSONObject jObject = jarray.getJSONObject(0); String result = jObject.optString("result"); Log.i("my", "result : " + result); if (result.equals("emailok")) { receiveMsg = "emailok"; } else { receiveMsg = "emailno"; } } }else {//type = type_join sendMsg = strings[0] + "&type=" + strings[1]; //서버로 값 전송 osw.write(sendMsg); osw.flush();//얼른가라!! //전송완료 후 서버에서 처리해준 결과값 받기 //getResponseCode() : 200(정상전송) //getResponseCode() : 404, 500등,,,(비정상전송) if (conn.getResponseCode() == conn.HTTP_OK) { InputStreamReader is = new InputStreamReader(conn.getInputStream(), "UTF-8"); BufferedReader reader = new BufferedReader(is); String buffer = "";//한 줄씩 읽어옴 while ((str = reader.readLine()) != null) {//한 줄 씩 읽어서 넘긴다. buffer += str; } //최종적으로 돌려받은 JSON형식의 결과값 receiveMsg = buffer; JSONArray jarray = new JSONObject(receiveMsg).getJSONArray("res"); JSONObject jObject = jarray.getJSONObject(0); String result = jObject.optString("result"); //Log.i("my", "join : " + result); if (result.equals("joinok")) { receiveMsg = "joinok"; } else { receiveMsg = "joinno"; } } } }catch (Exception e) { e.printStackTrace(); } return receiveMsg; } @Override protected void onPostExecute(String s) { Log.i("my","s : "+s); if(s.equals("idok")) { //Toast.makeText(JoinActivity.this, "???id사용 가능!", Toast.LENGTH_SHORT).show(); sweetAlertDialog = new SweetAlertDialog(JoinActivity.this, SweetAlertDialog.SUCCESS_TYPE); sweetAlertDialog.setTitleText("ID중복체크"); sweetAlertDialog.setContentText("사용가능 한 ID 입니다"); sweetAlertDialog.setConfirmText("확인"); sweetAlertDialog.show(); btn_join_id_check.setEnabled(false); join_id_et.setEnabled(false); id_join_check = "yes"; }else if(s.equals("idno")){ //Toast.makeText(JoinActivity.this, "이미 있는 id!!", Toast.LENGTH_SHORT).show(); sweetAlertDialog = new SweetAlertDialog(JoinActivity.this, SweetAlertDialog.WARNING_TYPE); sweetAlertDialog.setTitleText("ID중복체크"); sweetAlertDialog.setContentText("이미 사용중인 ID 입니다"); sweetAlertDialog.setConfirmText("확인"); sweetAlertDialog.show(); join_id_et.setText(""); id_join_check = ""; }else if(s.equals("emailno")){ email_check_num = 2; Log.i("my", "email_check_num2 : " + email_check_num); FinalEmail(); }else if(s.equals("emailok")){ email_check_num = 1; Log.i("my", "email_check_num2 : " + email_check_num); FinalEmail(); }else if(s.equals("joinok")){ //Toast.makeText(JoinActivity.this, "가입성공!!", Toast.LENGTH_SHORT).show(); sweetAlertDialog = new SweetAlertDialog(JoinActivity.this, SweetAlertDialog.SUCCESS_TYPE); sweetAlertDialog.setTitleText("회원가입"); sweetAlertDialog.setContentText("회원가입이 되셨습니다."); sweetAlertDialog.setConfirmText("확인"); sweetAlertDialog.show(); sweetAlertDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() { @Override public void onClick(SweetAlertDialog sweetAlertDialog) { Intent i = new Intent(JoinActivity.this, LoginMainActivity.class); startActivity(i); finish(); } }); }else if(s.equals("joinno")){ //Toast.makeText(JoinActivity.this, "가입실패!!", Toast.LENGTH_SHORT).show(); sweetAlertDialog = new SweetAlertDialog(JoinActivity.this, SweetAlertDialog.WARNING_TYPE); sweetAlertDialog.setTitleText("회원가입"); sweetAlertDialog.setContentText("문제가있다."); sweetAlertDialog.setConfirmText("확인"); sweetAlertDialog.show(); }else{ Log.i("my","실패"); } } } }
import javafx.application.*; import javafx.concurrent.Task; import javafx.stage.*; import javafx.scene.*; import javafx.scene.layout.*; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.scene.media.MediaView; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.scene.control.*; import javafx.scene.control.Alert.AlertType; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.geometry.Insets; import javafx.geometry.Pos; import java.net.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.io.*; import java.util.*; import org.json.simple.JSONObject; import org.json.simple.JSONValue; public class Client extends Application { public static void main(String[] args) throws IOException { launch(args); } Socket messageSocket; PrintWriter out; Scanner in; TextField hostInput,openInput; TextArea received, postInput; Button closeConn; Button post, openConfirm, postConfirm, closeChan, sub, unSub, changeImage, attachFile, saveButton; ToggleButton darkMode; Label hostPrompt, messagePrompt, openPrompt, file; String host, channel, message; boolean conHost, isOpen, isDark; Text pName; File selectedFile = null, profile; HBox hostPane, footerPane, subPane, attaching; VBox miscPane, openPane, postPane, messagePane; GridPane profilePane; Vector<String> subscribedList = new Vector<String>(); public void start(Stage stage) { BorderPane rootPane; Scene scene; //border pane rootPane = new BorderPane(); //rootPane layout hostPane = new HBox(); messagePane = new VBox(); footerPane = new HBox(); miscPane = new VBox(); miscPane.setPadding(new Insets(10, 10, 10, 10)); rootPane.setTop(hostPane); rootPane.setLeft(miscPane); rootPane.setRight(messagePane); rootPane.setBottom(footerPane); //Initially set to false until host accepted messagePane.setVisible(false); miscPane.setVisible(false); isOpen = false; isDark = false; //hostPane set to Top of BorderPane hostPane.setPadding(new Insets(30, 0, 0, 20)); hostPane.setSpacing(10); hostPane.setStyle("-fx-background-color: #1da1f2;"); hostPane.setPrefHeight(100); Image twitter = new Image(Client.class.getResourceAsStream("twitter1.png")); ImageView logo = new ImageView(); logo.setImage(twitter); logo.setCache(true); hostPrompt = new Label("Enter Host Name "); hostPrompt.setFont(new Font("Arial", 20)); hostPrompt.setPadding(new Insets(5, 0, 0, 0)); hostInput = new TextField(); hostInput.setPrefColumnCount(25); closeConn = new Button("Close connection"); closeConn.setOnAction(event->closeDown()); closeConn.setFont(new Font("Arial", 20)); closeConn.setPadding(new Insets(10, 10, 10, 10)); closeConn.setVisible(false); hostPane.getChildren().addAll(logo, hostPrompt, hostInput, closeConn); //Action to accept host hostInput.setOnAction(event->acceptHost()); //message box on right received = new TextArea(); received.setPrefHeight(400); received.setPrefWidth(550); received.setWrapText(true); received.setEditable(false); received.setFont(new Font("Arial", 20)); attaching = new HBox(); Text temp = new Text(); attaching.setSpacing(10); attaching.setPadding(new Insets(5, 5, 5, 5)); attaching.setVisible(false); saveButton = new Button("Save"); attaching.getChildren().addAll(temp, saveButton); messagePane.getChildren().addAll(received, attaching); saveButton.setOnAction(event->saveAttach()); //miscPane set to Left of BorderPane //Open channel pane openPane = new VBox(); openPane.setSpacing(10); openPane.setPadding(new Insets(5, 5, 10, 5)); openPrompt = new Label("Enter Channel Name"); openPrompt.setPadding(new Insets(5, 5, 5, 5)); openPrompt.setFont(new Font("Arial", 20)); openInput = new TextField(); openInput.setPrefColumnCount(25); openConfirm = new Button("Open"); openConfirm.setFont(new Font("Arial", 15)); openConfirm.setPadding(new Insets(10, 10, 10, 10)); openPane.getChildren().addAll(openPrompt, openInput, openConfirm); miscPane.getChildren().add(openPane); //Post message pane postPane = new VBox(); postPane.setSpacing(10); postPane.setPadding(new Insets(5, 5, 20, 5)); postInput = new TextArea(); postInput.setPrefColumnCount(30); postInput.setPromptText("Enter a message..."); postInput.setWrapText(true); postInput.setPrefHeight(120); HBox attachments = new HBox(); attachments.setSpacing(10); attachFile = new Button("Attach Files"); attachFile.setFont(new Font("Arial", 15)); attachFile.setPadding(new Insets(10, 10, 10, 10)); file = new Label("file"); file.setPadding(new Insets(5, 5, 5, 5)); file.setFont(new Font("Arial", 15)); file.setVisible(false); attachments.getChildren().addAll(attachFile, file); postConfirm = new Button("Post"); postConfirm.setFont(new Font("Arial", 15)); postConfirm.setPadding(new Insets(10, 10, 10, 10)); postPane.getChildren().addAll(postInput, attachments, postConfirm); attachFile.setOnAction(event->attachToMess()); postConfirm.setOnAction(event->postMessage()); openConfirm.setOnAction(event->openChannel(stage)); //Subscribe/Unsubscribe to channels pane subPane = new HBox(); subPane.setSpacing(10); subPane.setPadding(new Insets(5, 5, 5, 5)); sub = new Button("Subscribe"); sub.setFont(new Font("Arial", 15)); sub.setPadding(new Insets(10, 20, 10, 20)); unSub = new Button("Unsubscribe"); unSub.setFont(new Font("Arial", 15)); unSub.setPadding(new Insets(10, 10, 10, 10)); subPane.getChildren().addAll(sub, unSub); sub.setOnAction(event->subToPane()); unSub.setOnAction(event->unsubFromPane()); //footer for bottom footerPane.setStyle("-fx-background-color: #303030;"); footerPane.setPrefHeight(60); footerPane.setPadding(new Insets(10, 10, 10, 10)); darkMode = new ToggleButton("Switch to 'Dark Mode'"); darkMode.setFont(new Font("Arial", 15)); darkMode.setPadding(new Insets(10, 10, 10, 10)); darkMode.setOnAction(event->dark(rootPane)); footerPane.getChildren().add(darkMode); scene = new Scene(rootPane, 1200, 800); stage.setScene(scene); stage.setTitle("Client"); stage.show(); } public boolean dark(BorderPane rootPane) { if (isDark == false) { //rootPane background rootPane.setStyle("-fx-background-color: #65696b;"); //message box colours received.setStyle("-fx-control-inner-background: #65696b; -fx-text-fill: #ffffff;"); //hostPane colours hostPane.setStyle("-fx-background-color: #323639;"); hostPrompt.setStyle("-fx-text-fill: #ffffff;"); darkMode.setText("Switch to 'Light Mode'"); //postPane colours file.setStyle("-fx-text-fill: #ffffff;"); isDark = true; } else { //rootPane background rootPane.setStyle("-fx-background-color: #ffffff;"); //message box colours received.setStyle("-fx-control-inner-background: #ffffff; -fx-text-fill: #000000;"); //hostPane colours hostPane.setStyle("-fx-background-color: #1da1f2;"); hostPrompt.setStyle("-fx-text-fill: #000000;"); darkMode.setText("Switch to 'Dark Mode'"); //postPane colours file.setStyle("-fx-text-fill: #ffffff;"); isDark = false; } return isDark; } public boolean acceptHost() { final int ECHO = 12345; host = hostInput.getText(); try { messageSocket = new Socket(host, ECHO); out = new PrintWriter(messageSocket.getOutputStream(), true); in = new Scanner(messageSocket.getInputStream()); hostPrompt.setText("Connected to: " + host); hostInput.setVisible(false); hostInput.setText(""); closeConn.setVisible(true); messagePane.setVisible(true); miscPane.setVisible(true); openInput.requestFocus(); conHost = true; } catch (UnknownHostException e) { conHost = false; Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Connection Error"); alert.setHeaderText(null); alert.setContentText("Invalid host: " + host); alert.showAndWait(); } catch (IOException e) { conHost = false; Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Connection Error"); alert.setHeaderText(null); alert.setContentText("Couldn't get I/O for the connection to host: " + host); alert.showAndWait(); } return conHost; } public boolean openChannel(Stage stage) { String userInput, response; while (!(openInput.getText().isEmpty())) { userInput = "open " + openInput.getText(); out.println(userInput); int n = in.nextInt(); in.nextLine(); response = in.nextLine(); Object object = JSONValue.parse(response); JSONObject json = (JSONObject) object; String error = (String) json.get("_class"); if (error.equals("_ErrorResponse")) { error = (String) json.get("Error"); for (int i = 0; i < n; i++) { received.appendText("*** " + error + " ***\n"); } openInput.setText(""); } else { channel = (String) json.get("identity"); for (int i = 0; i < n; i++) { received.appendText("*** " + channel + " Channel is open ***\n"); } isOpen = true; } openInput.setText(""); } //Profile pane profilePane = new GridPane(); profilePane.setHgap(100); profilePane.setVgap(5); profilePane.setPadding(new Insets(5, 10, 20, 10)); Image pPic = new Image(Client.class.getResourceAsStream("placeholder.png")); ImageView profile = new ImageView(); profile.setImage(pPic); profile.setCache(true); profile.maxWidth(128); profile.maxWidth(128); profile.setFitHeight(128); profile.setFitWidth(128); profile.setPreserveRatio(true); profilePane.add(profile, 0, 0); pName = new Text(channel); pName.setFont(new Font("Arial", 30)); profilePane.add(pName, 0, 1); closeChan = new Button("Close Channel"); closeChan.setFont(new Font("Arial", 15)); closeChan.setPadding(new Insets(10, 10, 10, 10)); profilePane.add(closeChan, 1, 1); closeChan.setOnAction(event->closeChannel()); changeImage = new Button("Edit Profile"); changeImage.setFont(new Font("Arial", 15)); changeImage.setPadding(new Insets(10, 22, 10, 22)); profilePane.add(changeImage, 2, 1); changeImage.setOnAction(event->editProfile(stage, profile)); postInput.requestFocus(); miscPane.getChildren().remove(openPane); miscPane.getChildren().addAll(profilePane, postPane, subPane); return isOpen; } public void closeChannel() { miscPane.getChildren().remove(profilePane); miscPane.getChildren().remove(postPane); miscPane.getChildren().remove(subPane); miscPane.getChildren().add(openPane); isOpen = false; } public void editProfile(Stage stage, ImageView profile) { FileChooser chooser = new FileChooser(); chooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("JPG Files", "*.jpg") ,new FileChooser.ExtensionFilter("PNG Files", "*.png") ,new FileChooser.ExtensionFilter("JPEG Files", "*.jpeg") ); File profilePic = chooser.showOpenDialog(stage); Image image = new Image(profilePic.toURI().toString()); profile.setImage(image); } public void subToPane() { Stage subToStage = new Stage(); BorderPane subToRoot = new BorderPane(); Scene subToScene; VBox subToPane; HBox subSearch; Label title; TextField subInput; subSearch = new HBox(); subToPane = new VBox(); subToRoot.setTop(subSearch); subToRoot.setLeft(subToPane); title = new Label("Subscribe To"); title.setFont(new Font("Arial", 20)); title.setPadding(new Insets(10, 10, 10, 10)); subInput = new TextField(); subInput.setPrefColumnCount(15); subSearch.getChildren().addAll(title, subInput); subInput.setOnAction(event->subTo(subInput, subToStage)); subToScene = new Scene(subToRoot, 500, 50); subToStage.setScene(subToScene); subToStage.setTitle("Subscribe"); subToStage.show(); if (isDark == true) { subToRoot.setStyle("-fx-background-color: #65696b;"); title.setStyle("-fx-text-fill: #ffffff;"); //everything else styled accordingly } } public void subTo(TextField subInput, Stage subToStage) { String userInput, response, channelSub; while (!(subInput.getText().isEmpty())) { userInput = "sub " + subInput.getText(); out.println(userInput); int n = in.nextInt(); in.nextLine(); response = in.nextLine(); Object object = JSONValue.parse(response); JSONObject json = (JSONObject) object; String error = (String) json.get("_class"); if (error.equals("_ErrorResponse")) { error = (String) json.get("Error"); for (int i = 0; i < n; i++) { received.appendText("*** " + error + " ***\n"); } subInput.setText(""); } else { channelSub = (String) json.get("Channel"); for (int i = 0; i < n; i++) { received.appendText("*** Subscribed to " + channelSub + " ***\n"); subscribedList.add(channelSub); } } subInput.setText(""); } subToStage.close(); } public void unsubFromPane() { Stage unsubFromStage = new Stage(); BorderPane unsubFromRoot = new BorderPane(); Scene unsubFromScene; VBox unsubFromPane; HBox unsubSearch; Label title; TextField unsubInput; unsubSearch = new HBox(); unsubFromPane = new VBox(); unsubFromRoot.setTop(unsubSearch); unsubFromRoot.setLeft(unsubFromPane); title = new Label("Unsubscribe From"); title.setFont(new Font("Arial", 20)); title.setPadding(new Insets(10, 10, 10, 10)); unsubInput = new TextField(); unsubInput.setPrefColumnCount(15); unsubSearch.getChildren().addAll(title, unsubInput); unsubInput.setOnAction(event->unsubFrom(unsubInput, unsubFromStage)); unsubFromScene = new Scene(unsubFromRoot, 500, 50); unsubFromStage.setScene(unsubFromScene); unsubFromStage.setTitle("Unsubscribe"); unsubFromStage.show(); if (isDark == true) { unsubFromRoot.setStyle("-fx-background-color: #65696b;"); title.setStyle("-fx-text-fill: #ffffff;"); //everything else styled accordingly } } public void unsubFrom(TextField unsubInput, Stage unsubFromStage) { String userInput, response, channelUnsub; while (!(unsubInput.getText().isEmpty())) { userInput = "unsub " + unsubInput.getText(); out.println(userInput); int n = in.nextInt(); in.nextLine(); response = in.nextLine(); Object object = JSONValue.parse(response); JSONObject json = (JSONObject) object; String error = (String) json.get("_class"); if (error.equals("_ErrorResponse")) { error = (String) json.get("Error"); for (int i = 0; i < n; i++) { received.appendText("*** " + error + " ***\n"); } unsubInput.setText(""); } else { channelUnsub = (String) json.get("Channel"); for (int i = 0; i < n; i++) { received.appendText("*** Unubscribed from " + channelUnsub + " ***\n"); subscribedList.add(channelUnsub); } } unsubInput.setText(""); } unsubFromStage.close(); } public void postMessage() { file.setVisible(false); String userInput, response; while (!(postInput.getText().isEmpty()) || (selectedFile != null)) { userInput = "post " + postInput.getText(); out.println(userInput); int n = in.nextInt(); in.nextLine(); response = in.nextLine(); String messages = in.nextLine(); String[] lines = messages.split(" "); Vector<String> bodys = new Vector<String>(); Vector<String> froms = new Vector<String>(); Vector<String> medias = new Vector<String>(); for (int i = 0; i < lines.length; i++) { Object objectMess = JSONValue.parse(lines[i]); JSONObject jsonMess = (JSONObject) objectMess; bodys.add((String) jsonMess.get("Body")); froms.add((String) jsonMess.get("From")); medias.add((String) jsonMess.get("Media")); try { byte [] newBytes = Base64.getDecoder().decode(medias.get(i)); Path path = Paths.get(""); File newFile = new File(Files.write(path, newBytes).toUri()); typeOfAttachment(newFile); received.appendText(froms.get(i) + ": " + bodys.get(i) + " Attachment: " + newFile.getName() + "\n"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NullPointerException ne) { } finally { received.appendText(froms.get(i) + ": " + bodys.get(i) + "\n"); Object object = JSONValue.parse(response); JSONObject json = (JSONObject) object; String error = (String) json.get("_class"); if (error.equals("_ErrorResponse")) { error = (String) json.get("Error"); received.appendText("*** " + error + " ***\n"); postInput.setText(""); selectedFile = null; } else { if(selectedFile != null) { attaching.setVisible(true); typeOfAttachment(selectedFile); } } postInput.setText(""); selectedFile = null; } } } } public void attachToMess() { Stage attachStage = new Stage(); //setMedia() for message //code it to JSON, use toJSONMessages() //important FileChooser chooser = new FileChooser(); chooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("JPG Files", "*.jpg") ,new FileChooser.ExtensionFilter("PNG Files", "*.png") ,new FileChooser.ExtensionFilter("JPEG Files", "*.jpeg") ,new FileChooser.ExtensionFilter("MP4 Files", "*.mp4") ,new FileChooser.ExtensionFilter("AVI Files", "*.avi") ,new FileChooser.ExtensionFilter("MP3 Files", "*.mp3") ); selectedFile = chooser.showOpenDialog(attachStage); try { // FileInputStream fileInputStreamReader = new FileInputStream(selectedFile); // byte[] bytes = new byte[(int)selectedFile.length()]; // fileInputStreamReader.read(bytes); // String encodedFile = Base64.getEncoder().encodeToString(bytes); // fileInputStreamReader.close(); byte [] bytes = Files.readAllBytes(selectedFile.toPath()); String encodedFile = Base64.getEncoder().encodeToString(bytes); String userInput; while (!(encodedFile.isEmpty())) { userInput = "attach " + encodedFile; out.println(userInput); file.setText(selectedFile.getName()); file.setVisible(true); encodedFile = ""; } } catch (FileNotFoundException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } } public void saveAttach() { Stage attachStage = new Stage(); FileChooser chooser = new FileChooser(); chooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("JPG Files", "*.jpg") ,new FileChooser.ExtensionFilter("PNG Files", "*.png") ,new FileChooser.ExtensionFilter("JPEG Files", "*.jpeg") ,new FileChooser.ExtensionFilter("MP4 Files", "*.mp4") ,new FileChooser.ExtensionFilter("AVI Files", "*.avi") ); chooser.showSaveDialog(attachStage); } public void getMessages() { //if list of clienthandlers have pressed post then messages will refresh for each client //important } public void closeDown() { try { out.println("quit"); hostPrompt.setText("Enter Host Name "); hostInput.requestFocus(); hostInput.setVisible(true); closeConn.setVisible(false); messagePane.setVisible(false); miscPane.setVisible(false); in.close(); out.close(); messageSocket.close(); } catch (IOException e) { System.out.println(e.getMessage()); } } public void typeOfAttachment(File selectedFile) { if ((selectedFile.getName().contains(".png")) || (selectedFile.getName().contains(".jpg")) || (selectedFile.getName().contains(".jpeg"))) { attaching.getChildren().remove(0, 2); Image image = new Image(selectedFile.toURI().toString()); ImageView attachImage = new ImageView(); attachImage.setFitHeight(200); attachImage.setFitWidth(200); attachImage.setPreserveRatio(true); attachImage.setImage(image); attachImage.setCache(true); attachImage.maxWidth(200); attachImage.maxWidth(200); attaching.getChildren().addAll(attachImage, saveButton); } if ((selectedFile.getName().contains(".avi")) || (selectedFile.getName().contains(".mp4"))) { attaching.getChildren().remove(0, 2); Media video = new Media(selectedFile.toURI().toString()); MediaPlayer videoPlayer = new MediaPlayer(video); videoPlayer.setAutoPlay(true); MediaView videoViewer = new MediaView(videoPlayer); videoViewer.setCache(true); videoViewer.maxWidth(200); videoViewer.maxHeight(200); videoViewer.setFitHeight(200); videoViewer.setFitWidth(200); videoViewer.setPreserveRatio(true); attaching.getChildren().addAll(videoViewer, saveButton); } if ((selectedFile.getName().contains(".mp3"))) { attaching.getChildren().remove(0, 2); Media audio = new Media(selectedFile.toURI().toString()); MediaPlayer audioPlayer = new MediaPlayer(audio); audioPlayer.setAutoPlay(true); MediaView audioViewer = new MediaView(audioPlayer); audioViewer.setCache(true); audioViewer.maxWidth(200); audioViewer.maxHeight(200); audioViewer.setFitHeight(200); audioViewer.setFitWidth(200); audioViewer.setPreserveRatio(true); attaching.getChildren().addAll(audioViewer, saveButton); } } }
package demo.web; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class PhidgetController { @Autowired JdbcTemplate jdbcTemplate; @RequestMapping("/spatial") public String listSpatial() { return "spatial/list"; } @RequestMapping("/") public String home() { return "spatial/line"; } @RequestMapping("/spatialGraph") public String lineSpatial() { return "spatial/line"; } }
package hello.agh.edu.bazy.dbApi.gis; import hello.agh.edu.bazy.row.gis.GisPoint; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.sql.SQLException; import java.util.List; /** * Created by mar on 23.01.15. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:/database-blueprint.xml"}) public class gisTest { @Autowired JdbcTemplate gisJdbcTemplate; @Test public void gisConnectionTestAndGetAllObjectCoordinates() throws SQLException { GisDbApi api = new GisDbApi(); try { api.setGisJdbcTemplate(gisJdbcTemplate); List<GisPoint> lamps = api.getAllLamps(); for (GisPoint gisLamp : lamps) { System.out.println(gisLamp.getId() + " " + gisLamp.getX() + ", " + gisLamp.getY()); } } catch (Exception e) { throw e; } } }
package com.tencent.mm.plugin.setting.ui.setting; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; class SettingsLanguageUI$1 implements OnMenuItemClickListener { final /* synthetic */ SettingsLanguageUI mSr; SettingsLanguageUI$1(SettingsLanguageUI settingsLanguageUI) { this.mSr = settingsLanguageUI; } public final boolean onMenuItemClick(MenuItem menuItem) { this.mSr.YC(); this.mSr.finish(); return true; } }
package kr.co.toondra.web.login.service; import java.util.HashMap; import kr.co.toondra.common.collection.PMap; import kr.co.toondra.common.exception.LogicException; import kr.co.toondra.common.util.CommonUtil; import kr.co.toondra.common.util.Hash; import kr.co.toondra.common.util.SessionUtil; import kr.co.toondra.web.login.dao.LoginDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class LoginService { @Autowired LoginDao dao = new LoginDao(); public boolean login(PMap pMap) throws Exception { pMap.put("password", Hash.sha512(pMap.getString("password"))); HashMap<String, Object> userInfo = dao.login(pMap); if(CommonUtil.isNull(userInfo)) { throw new LogicException("Login Failed"); } SessionUtil session = new SessionUtil(pMap.getRequest()); session.setSessionValue("s_manager_seq", userInfo.get("manager_seq")); session.setSessionValue("s_name", userInfo.get("name")); return true; } }
package bookexercises.chapter1.fundamentals.three; import edu.princeton.cs.algs4.StdOut; /** * What does the following code fragment print when N is 50? Give a high-level * description of what it does when presented with a positive integer N. * * Stack<Integer> stack = new Stack<Integer>(); * while (N > 0) * { * stack.push(N % 2); * N = N / 2; * } * for (int d : stack) StdOut.print(d); * StdOut.println(); * * @author atlednolispe * @email atlednolispe@gmail.com * @date 2018/7/14 */ public class Five { /** * binary */ public static void main(String[] args) { Stack<Integer> stack = new Stack<Integer>(); int N = 50; while (N > 0) { stack.push(N % 2); N = N / 2; } for (int d : stack) StdOut.print(d); StdOut.println(); } }
import java.util.ArrayList; public class Policeman { private static int POLICEMEN_COUNT = 0; private static int ACTIVE_POLICEMEN; public int ID = 0; private String name, surname, login; private boolean isActive = false; ArrayList<Policeman> partners = new ArrayList<>(); public Policeman(String name, String surname, String login) { POLICEMEN_COUNT++; this.ID = POLICEMEN_COUNT; this.name = name; this.surname = surname; this.login = login; } public int activatePoliceman() { ACTIVE_POLICEMEN++; this.isActive = true; return ACTIVE_POLICEMEN; } public int deactivatePoliceman() { ACTIVE_POLICEMEN--; this.isActive = false; return ACTIVE_POLICEMEN; } public void addPartner(Policeman p) { this.partners.add(p); p.partners.add(this); } public void removePartner(Policeman p) { this.partners.remove(p); } public void displayInfo() { System.out.print(name + " "+ surname + " " + login + " " + ID + " " + isActive + " "); this.displayPartnerList(); System.out.println(); } public void displayAllActiveInfo() { if (isActive) { System.out.println(name + " " + surname + " " + login + " " + ID ); } } public void displayPartnerList(){ System.out.println(this.partners); } }
/* * Copyright (C) 2015 Miquel Sas * * 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 3 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, see * <http://www.gnu.org/licenses/>. */ package com.qtplaf.platform.statistics.task; import java.util.List; import com.qtplaf.library.database.Persistor; import com.qtplaf.library.database.Record; import com.qtplaf.library.database.Table; import com.qtplaf.library.trading.data.PersistorDataList; import com.qtplaf.platform.database.Fields; import com.qtplaf.platform.statistics.States; /** * Calculate ranges (min-max) values. * * @author Miquel Sas */ public class TaskRanges extends TaskAverages { /** Underlying states statistics. */ private States states; /** States data list. */ private PersistorDataList statesList; /** * Constructor. * * @param states The states statistics. */ public TaskRanges(States states) { super(states.getSession()); this.states = states; this.statesList = states.getDataListStates(); this.statesList.setCacheSize(10000); setNameAndDescription(states, "ranges", "Min-Max ranges of raw values"); } /** * Count the steps. * * @return The number of steps. * @throws Exception If an unrecoverable error occurs during execution. */ @Override public long countSteps() throws Exception { // Notify counting. notifyCounting(); // Number of steps. int count = statesList.size(); // Notify. notifyStepCount(count); return getSteps(); } /** * Returns the result record. * * @param persistor The persistor. * @param name The field name. * @param period The period. * @param minimum Minimum/maximum. * @param value The value. * @param index Source index. * @param time Source time. * @return The record. */ private Record getRecord( Persistor persistor, String name, int period, boolean minimum, double value, int index, long time) { Record record = persistor.getDefaultRecord(); record.setValue(Fields.NAME, name); record.setValue(Fields.PERIOD, period); record.setValue(Fields.MIN_MAX, (minimum ? "min" : "max")); record.setValue(Fields.VALUE, value); record.setValue(Fields.INDEX, index); record.setValue(Fields.TIME, time); return record; } /** * Executes the underlying task processing. * * @throws Exception If an unrecoverable error occurs during execution. */ @Override public void execute() throws Exception { // Count steps. countSteps(); // Result table and persistor. Table table = states.getTableRanges(); Persistor persistor = table.getPersistor(); // Drop and create the table. if (persistor.getDDL().existsTable(table)) { persistor.getDDL().dropTable(table); } persistor.getDDL().buildTable(table); // Periods of ranges: two more slowest averages. int[] periods = new int[] { states.getAverages().get(states.getAverages().size() - 1).getPeriod(), states.getAverages().get(states.getAverages().size() - 2).getPeriod() }; // Field names. List<String> fieldNames = states.getFieldsToNormalize(Fields.Suffix.RAW); // The current index to calculate. int index = 0; // Step and steps. long step = 0; long steps = getSteps(); while (step < steps) { // Check request of cancel. if (checkCancel()) { break; } // Check pause resume. if (checkPause()) { continue; } // Increase step. step++; // Notify step start. notifyStepStart(step, getStepMessage(step, steps, null, null)); // Do calculate if min-max for each name and period. for (String name : fieldNames) { int valueIndex = statesList.getDataInfo().getOutputIndex(name); double value = statesList.get(index).getValue(valueIndex); if (value == 0) { continue; } for (int period : periods) { if (value < 0) { if (statesList.isMinimum(index, valueIndex, period)) { long time = statesList.get(index).getTime(); Record record = getRecord(persistor, name, period, true, value, index, time); persistor.insert(record); } } if (value > 0) { if (statesList.isMaximum(index, valueIndex, period)) { long time = statesList.get(index).getTime(); Record record = getRecord(persistor, name, period, false, value, index, time); persistor.insert(record); } } } } // Skip to next index. index++; // Notify step end. notifyStepEnd(); } } }
package com.config; import com.netflix.client.config.DefaultClientConfigImpl; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class IClientConfig { @Bean public DefaultClientConfigImpl iClientConfig(){ return new DefaultClientConfigImpl(); } }
package com.mrfan.livehelper.network; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import android.content.Context; import android.os.AsyncTask; import android.os.Handler; import android.os.Message; public class DataLoader extends AsyncTask<String, Integer, String> { private Context mContext; private String mType = "GET"; private String mUrl; private Handler mHandler; static public DataLoader get(Context context, String url, Handler hander) { return new DataLoader(context, "GET", url, hander); } static public DataLoader post(Context context, String url, Handler hander) { return new DataLoader(context, "POST", url, hander); } public DataLoader(Context context, String type, String url, Handler hander) { super(); mContext = context; mType = type; mUrl = url; mHandler = hander; } @Override protected String doInBackground(String... params) { String result = "", readLine = null; try { if (mType.equals("GET")) { mUrl = mUrl + "?" + params; } URL url = new URL(mUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(300); connection.setRequestMethod(mType); InputStreamReader isReader = new InputStreamReader(connection.getInputStream()); BufferedReader bufferedReader = new BufferedReader(isReader); while ((readLine = bufferedReader.readLine()) != null) { result += readLine; } isReader.close(); connection.disconnect(); if (mHandler != null) { Message msg = new Message(); msg.what = connection.getResponseCode(); msg.obj = result; mHandler.sendMessage(msg); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } }
/** * */ package com.cnk.travelogix.common.facades.product.provider.impl; import com.cnk.travelogix.common.facades.product.data.flight.AirlineIATAData; import com.cnk.travelogix.common.facades.product.data.flight.FlightData; import com.cnk.travelogix.common.facades.product.provider.CnkFacetValueProvider; /** * @author i313879 * */ public class FlightCompanyValueProvider implements CnkFacetValueProvider<FlightData> { /* * (non-Javadoc) * * @see * com.cnk.travelogix.common.facades.product.facet.provider.CnkFacetValueProvider#getFacetValue(com.cnk.travelogix * .common.facades.product.data.BaseProductData, java.lang.String) */ @Override public Object getFacetValue(final FlightData bean, final String propertyName) { final AirlineIATAData airlineIATA = bean.getAirlineIATA(); if (airlineIATA != null) { return airlineIATA.getAirlineName(); } return null; } }
package com.canfield010.mygame.mapsquare; public class FinalPoint { public final int x; public final int y; public FinalPoint(int x, int y) { this.x = x; this.y = y; } }
package com.example.awoosare_ridebook; import java.util.ArrayList; import java.util.HashMap; // comments for the RideData class // stores the global state for the application, (which is not persistent) // the arrayList is for the recyclerview in ItemListActivity, while the hashMap // is there so that the ride details screen and the Ride Form activity // to look up the ride. I probably could have just picked one, but // it was convenient and felt more natural to use both, and there does not seem to be // a performance hit public class RideData { private static final ArrayList<Ride> ITEMS = new ArrayList<Ride>(); private static final HashMap<String, Ride> ITEM_MAP = new HashMap<String, Ride>(); public static ArrayList<Ride> getITEMS() { return ITEMS; } public static HashMap<String, Ride> getItemMap() { return ITEM_MAP; } public static void addItem(Ride item) { ITEMS.add(item); ITEM_MAP.put(item.getId(), item); } public static void removeItem(Ride item) { ITEMS.remove(item); ITEM_MAP.remove(item.getId()); } }
package com.rsfranco.callcenter; import static org.junit.Assert.assertTrue; import java.util.LinkedList; import java.util.Queue; import com.rsfranco.callcenter.business.Call; import com.rsfranco.callcenter.business.Dispatcher; import com.rsfranco.callcenter.model.Manager; import com.rsfranco.callcenter.model.Operator; import com.rsfranco.callcenter.model.Supervisor; import org.junit.Test; public class AppTest { public static int N = 10, M = 5; @Test public void test1() { //test1: 12 llamadas con 4 operadores,2 supervisores , 1 director Queue<Call> calls = new LinkedList<Call>(); for (int i = 1; i <= 12; i++) { int time = (int) Math.floor(Math.random() * (N - M + 1) + M); calls.add(new Call(i, time)); } Queue<Manager> managers = new LinkedList<Manager>(); for (int i = 1; i <= 1; i++) { managers.add(new Manager(i + "")); } Queue<Supervisor> supervisors = new LinkedList<Supervisor>(); for (int i = 1; i <= 2; i++) { supervisors.add(new Supervisor(i + "")); } Queue<Operator> operators = new LinkedList<Operator>(); for (int i = 1; i <= 4; i++) { operators.add(new Operator(i + "")); } Dispatcher dispatcher = new Dispatcher(managers, supervisors, operators); assertTrue(dispatcher.listener(calls)); } @Test public void test2() { // Test2: 8 llamadas 1 representante por empleado Queue<Call> calls = new LinkedList<Call>(); for (int i = 1; i <= 8; i++) { int time = (int) Math.floor(Math.random() * (N - M + 1) + M); calls.add(new Call(i, time)); } Queue<Manager> managers = new LinkedList<Manager>(); for (int i = 1; i <= 1; i++) { managers.add(new Manager(i + "")); } Queue<Supervisor> supervisors = new LinkedList<Supervisor>(); for (int i = 1; i <= 1; i++) { supervisors.add(new Supervisor(i + "")); } Queue<Operator> operators = new LinkedList<Operator>(); for (int i = 1; i <= 1; i++) { operators.add(new Operator(i + "")); } Dispatcher dispatcher = new Dispatcher(managers, supervisors, operators); assertTrue(dispatcher.listener(calls)); } }
package com.yunhe.basicdata.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.yunhe.basicdata.dao.WarehouseManagementMapper; import com.yunhe.basicdata.entity.WarehouseManagement; import com.yunhe.basicdata.service.IWarehouseManagementService; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.HashMap; import java.util.List; import java.util.Map; /** * <p> * 仓库管理 服务实现类 * </p> * * @author 李恒逵, 唐凯宽 * @since 2019-01-02 */ @Service public class WarehouseManagementServiceImpl extends ServiceImpl<WarehouseManagementMapper, WarehouseManagement> implements IWarehouseManagementService { @Resource private WarehouseManagementMapper warehouseManagementMapper; @Override public Map selectWareList(String data,int pageSize, int pageNum) { Page<WarehouseManagement> page = new Page<WarehouseManagement>(); page.setSize(pageSize); page.setCurrent(pageNum); List<WarehouseManagement> list = warehouseManagementMapper.selectWareList(data,page); Map map = new HashMap(); map.put("pagenum", pageNum); map.put("pageSize", pageSize); map.put("totalPage",page.getPages()); map.put("count",page.getTotal()); map.put("list", list); return map; } @Override public void deleteByid(int id) { warehouseManagementMapper.deleteById(id); } @Override public Integer update(WarehouseManagement warehouseManagemen) { return warehouseManagementMapper.updateById(warehouseManagemen); } @Override public WarehouseManagement selectByid(int id) { return warehouseManagementMapper.selectById(id); } @Override public Map vagueselect1(String data) { Map map = new HashMap(); /* Page<WarehouseManagement> page = new Page<WarehouseManagement>(); page.setSize(pageSize); page.setCurrent(pageNum); map.put("pagenum", pageNum); map.put("pageSize", pageSize); map.put("totalPage",page.getPages()); map.put("count",page.getTotal());*/ //map.put("list", list); List<WarehouseManagement> warehouseManagements = (List<WarehouseManagement>) warehouseManagementMapper.selectList(new QueryWrapper<WarehouseManagement>().like("wm_number", data).or().like("wm_name", data).or().like("wm_person", data).or().like("wm_tel",data).or().like("wm_address",data).or().like("wm_remark",data) ); map.put("list",warehouseManagements); return map; } @Override public Integer addWarehouse(WarehouseManagement warehouseManagement) { return warehouseManagementMapper.insert(warehouseManagement); } @Override public List<WarehouseManagement> selectware() { return warehouseManagementMapper.selectware(); } @Override public List<WarehouseManagement> selectquanWarList() { return warehouseManagementMapper.selectList(null); } }
package com.andy.weexlab.activity; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.ViewGroup; import com.andy.weexlab.R; import com.andy.weexlab.databinding.ActRemoteJsBinding; import com.taobao.weex.IWXRenderListener; import com.taobao.weex.WXSDKInstance; import com.taobao.weex.common.WXRenderStrategy; import java.util.HashMap; import java.util.Map; /** * Created by Andy on 2017/4/14. */ public class RemoteJsActivity extends AppCompatActivity implements IWXRenderListener { private static String TEST_URL = "http://10.0.0.90/foo.js"; private WXSDKInstance mWXSDKInstance; private ActRemoteJsBinding remoteJsBinding; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); remoteJsBinding = DataBindingUtil.setContentView(this, R.layout.act_remote_js); mWXSDKInstance = new WXSDKInstance(this); mWXSDKInstance.registerRenderListener(this); /** * pageName:自定义,一个标示符号。 * url:远程bundle JS的下载地址 * options:初始化时传入WEEX的参数,比如 bundle JS地址 * flag:渲染策略。WXRenderStrategy.APPEND_ASYNC:异步策略先返回外层View,其他View渲染完成后调用onRenderSuccess。WXRenderStrategy.APPEND_ONCE 所有控件渲染完后后一次性返回。 */ Map<String, Object> options = new HashMap<>(); options.put(WXSDKInstance.BUNDLE_URL, TEST_URL); mWXSDKInstance.renderByUrl("WXSample", TEST_URL, null, null, WXRenderStrategy.APPEND_ASYNC); } @Override public void onViewCreated(WXSDKInstance instance, View view) { if (view.getParent() != null) { ((ViewGroup) view.getParent()).removeView(view); } remoteJsBinding.container.addView(view); // setContentView(view); } @Override public void onRenderSuccess(WXSDKInstance instance, int width, int height) { Log.i("RemoteJsActivity", "onRenderSuccess"); } @Override public void onRefreshSuccess(WXSDKInstance instance, int width, int height) { Log.i("RemoteJsActivity", "onRefreshSuccess"); } @Override public void onException(WXSDKInstance instance, String errCode, String msg) { Log.i("RemoteJsActivity", "onException"); Log.e("RemoteJsActivity", "errCode: "+ errCode); Log.e("RemoteJsActivity", "msg: "+ msg); } @Override protected void onStart() { super.onStart(); if (mWXSDKInstance != null) { mWXSDKInstance.onActivityStart(); } } @Override protected void onResume() { super.onResume(); if (mWXSDKInstance != null) { mWXSDKInstance.onActivityResume(); } } @Override protected void onPause() { super.onPause(); if (mWXSDKInstance != null) { mWXSDKInstance.onActivityPause(); } } @Override protected void onStop() { super.onStop(); if (mWXSDKInstance != null) { mWXSDKInstance.onActivityStop(); } } @Override protected void onDestroy() { super.onDestroy(); if (mWXSDKInstance != null) { mWXSDKInstance.onActivityDestroy(); } } }
/* * This software is licensed under the MIT License * https://github.com/GStefanowich/MC-Server-Protection * * Copyright (c) 2019 Gregory Stefanowich * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.theelm.sewingmachine.utilities.text; import net.theelm.sewingmachine.utilities.ColorUtils; import net.minecraft.text.ClickEvent; import net.minecraft.text.HoverEvent; import net.minecraft.text.Style; import net.minecraft.text.TextColor; import net.minecraft.util.Formatting; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import java.util.function.UnaryOperator; /** * Created on Mar 24 2021 at 12:15 PM. * By greg in SewingMachineMod */ public final class StyleApplicator implements UnaryOperator<Style> { private @Nullable TextColor color = null; private @Nullable HoverEvent hover = null; private @Nullable ClickEvent click = null; private final @NotNull List<Formatting> formattings = new ArrayList<>(); public StyleApplicator() {} public StyleApplicator(@Nullable TextColor color) { this.withStyle(color); } public StyleApplicator(@Nullable Formatting color) { this.withStyle(color); } public StyleApplicator(@Nullable String color) { this.withStyle(color); } public <T> StyleApplicator(HoverEvent.Action<T> action, T contents) { this.withHover(action, contents); } public StyleApplicator(ClickEvent.Action action, String value) { this.withClick(action, value); } public StyleApplicator withStyle(@Nullable TextColor color) { this.color = color; return this; } public StyleApplicator withStyle(@Nullable Formatting formatting) { if (formatting != null) { if (formatting == Formatting.RESET) this.clear(); else if (formatting.isColor()) this.color = TextColor.fromFormatting(formatting); else this.formattings.add(formatting); } return this; } public StyleApplicator withStyle(@Nullable String color) { TextColor textColor; if (color != null && (textColor = ColorUtils.getRawTextColor(color)) != null) this.color = textColor; return this; } public <T> StyleApplicator withHover(@NotNull HoverEvent.Action<T> action, @NotNull T contents) { this.hover = new HoverEvent(action, contents); return this; } public StyleApplicator withClick(@NotNull ClickEvent.Action action, @NotNull String value) { this.click = new ClickEvent(action, value); return this; } public boolean isEmpty() { return this.color == null && this.hover == null && this.click == null && this.formattings.isEmpty(); } public void clear() { this.color = null; this.hover = null; this.click = null; this.formattings.clear(); } @Override public @NotNull Style apply(@NotNull Style style) { if (this.color != null) style = style.withColor(this.color); if (this.hover != null) style = style.withHoverEvent(this.hover); if (this.click != null) style = style.withClickEvent(this.click); return style.withFormatting(this.formattings.toArray(new Formatting[0])); } }
package com.tencent.mm.plugin.appbrand.dynamic.d; import android.text.TextUtils; import com.tencent.mm.model.u$b; import com.tencent.mm.plugin.appbrand.collector.c; import com.tencent.mm.plugin.appbrand.dynamic.d.a.a; import com.tencent.mm.plugin.appbrand.dynamic.h.d; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.x; import org.json.JSONObject; public final class b extends a { public b(int i) { super(com.tencent.mm.plugin.appbrand.jsapi.b.b.NAME, i); } protected final void a(com.tencent.mm.u.c.a aVar, JSONObject jSONObject, com.tencent.mm.u.b.b.a<JSONObject> aVar2) { c.aZ(d.j(jSONObject), "before_jsapi_invoke"); u$b Da = aVar.Da(); String string = Da.getString("__page_view_id", null); String string2 = Da.getString("__process_name", ad.getProcessName()); if (com.tencent.mm.plugin.appbrand.dynamic.d.aeQ().su(string) == null) { x.w("MicroMsg.JsApiFunc_DrawCanvas", "get view by viewId(%s) return null.", new Object[]{string}); aVar2.aA(a(false, "got 'null' when get view by the given viewId", null)); return; } long j; synchronized (Da) { long longValue; long currentTimeMillis = System.currentTimeMillis(); CharSequence sF = sF("lastTime"); if (!TextUtils.isEmpty(sF)) { Object obj = Da.dAZ.get(sF); if (obj instanceof Long) { longValue = ((Long) obj).longValue(); j = currentTimeMillis - longValue; } } longValue = 0; j = currentTimeMillis - longValue; } a aVar3 = (a) Da.get(sF("DrawCanvasRunnable"), null); if (aVar3 == null) { aVar3 = new a((byte) 0); Da.p(sF("DrawCanvasRunnable"), aVar3); } aVar3.process = string2; aVar3.fvT = string; aVar3.fvU = jSONObject; aVar3.fvV = this; aVar3.fvW = aVar2; aVar3.fvX = Da; com.tencent.mm.plugin.appbrand.dynamic.b.aeO().removeCallbacks(aVar3); if (j < 16) { x.v("MicroMsg.JsApiFunc_DrawCanvas", "postDelayed(%s)", new Object[]{Long.valueOf(j)}); com.tencent.mm.plugin.appbrand.dynamic.b.aeO().postDelayed(aVar3, j); return; } aVar3.run(); } final String sF(String str) { return this.name + "#" + str; } }
package com.nhatdear.sademo.helpers; import android.content.Context; import android.content.Intent; import android.graphics.Typeface; import android.os.Build; import android.support.design.widget.Snackbar; import android.support.v4.content.ContextCompat; import android.view.View; import android.widget.TextView; import com.nhatdear.sademo.R; import com.nhatdear.sademo.activities.SA_MainActivity; /** * Created by nhatdear on 4/24/17. */ public class SA_Helper { //region STRING HELPER public static final String LAST_USERNAME = "LAST_USERNAME"; public static final String LAST_ACCOUNT = "LAST_ACCOUNT"; public static final String USER_PREF = "USER_SHAREDPREF"; public static final String USERNAME_MUST_NOT_CONTAIN_SPECIAL_CHAR = "Username can only contain letters and numbers"; public static final String EMAIL_IS_NOT_CORRECT_FORMAT = "Ups! That’s not a valid email address."; public static final String PLEASE_CLICK_BACK_AGAIN_TO_EXIT = "Click BACK again to exit"; //endregion //region UI HELPER public static void showSnackbar(View view, String content) { Snackbar snackbar = Snackbar.make(view, content, Snackbar.LENGTH_LONG); View v = snackbar.getView(); v.setBackgroundColor(ContextCompat.getColor(view.getContext(), R.color.snackBarColor)); TextView textView = (TextView) v.findViewById(android.support.design.R.id.snackbar_text); textView.setTypeface(Typeface.createFromAsset(view.getContext().getAssets(), "fonts/OpenSans-Regular.ttf")); textView.setTextSize(12); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER); } textView.setTextColor(ContextCompat.getColor(view.getContext(), R.color.textColorPrimary)); snackbar.show(); } public static boolean softCheckValidString(String str) { return str != null && !str.trim().isEmpty(); } public static void goToMainWithClearFlag(Context context) { Intent intent = new Intent(context, SA_MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); context.startActivity(intent); } }
package com.company; import java.util.Scanner; public class Choose_your_adventure { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); String first=""; String second=""; String third=""; System.out.println("Welcome to MITCHELL's tiny adventure!"); System.out.println(); System.out.println("You're in a creepy house! Would u like to got \"upstairs\" or into the \"kitchen\"?"); first=scanner.nextLine(); if(first.equals("kitchen")){ System.out.println("There is a long countertop with dirty dishes everywhere. Off to one side there is, as you'd expect, a refrigerator. You may open the \"refrigeratoror\" or look inn a \"cabinet\"."); second=scanner.nextLine(); if(second.equals("refrigerator")){ System.out.println("Inside the refrigerator you see food and stuff. It looks pretty nasty. /nWould you like to eat some of the food? \"yes\" or \"no\""); third=scanner.nextLine(); if(third.equals("no")){ System.out.println("You die of starvation... eventually."); } else if(third.equals("yes")){ System.out.println("You survived. Congrats!"); } } else if(second.equals("cabinet")){ System.out.println("There is a coat and a pair of shoes. Which one would you like to get?"); third=scanner.nextLine(); if(third.equals("coat")){ System.out.println("Congrats! U survived."); } else if(third.equals("shoes")){ System.out.println("You die of hypotermia"); } } } else if(first.equals("upstairs")){ System.out.println("Upstairs you see a hallway. At the end of the hallway is the master \"bedroom\". There is also a \"bathroom\" off the hallway. Where would you like to go?"); second=scanner.nextLine(); if(second.equals("bedroom")){ System.out.println("You're in a plush bedroom, with expensive-looking hardwood furniture. The bed is unmade. ın the back of the room, the closet door is ajar. Would you open the door? (\"yes\" or \"no\" "); third=scanner.nextLine(); if(third.equals("no")){ System.out.println("I guess you'll never know what was in there.Thanks for playing."); } else if(third.equals("yes")); System.out.println("Congrats! You escape the house. It' s door that opens to outside."); } else if(second.equals("bathroom")){ System.out.println("You're in a bathroom. There are painkillers and some clean clothes.You can only pick one of them.Which is it?"); if(third.equals("painkiller")){ System.out.println("Sorry you die of consumption of posion."); } else if(third.equals("clean clothes")){ System.out.println("You are now good to go."); } } } } }
package com.isystk.sample.web.front.controller.api.v1.entry.remind; import com.isystk.sample.common.exception.NoDataFoundException; import com.isystk.sample.common.exception.ValidationErrorException; import com.isystk.sample.web.base.controller.api.AbstractRestController; import com.isystk.sample.web.base.controller.api.resource.Resource; import com.isystk.sample.web.base.controller.html.AbstractHtmlController; import com.isystk.sample.web.front.service.EntryRemindService; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.Errors; import org.springframework.validation.FieldError; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import static com.isystk.sample.common.Const.MESSAGE_SUCCESS; import static com.isystk.sample.common.FrontUrl.API_V1_ENTRY_REGIST; import static com.isystk.sample.common.FrontUrl.API_V1_ENTRY_REMIND_CONFIG; /** * 会員パスワード変更 */ @RestController @RequestMapping(path = API_V1_ENTRY_REMIND_CONFIG, produces = MediaType.APPLICATION_JSON_VALUE) public class EntryRemindConfigRestController extends AbstractRestController { @Autowired EntryRemindService entryRemindService; @Autowired PasswordEncoder passwordEncoder; @Autowired EntryRemindConfigRestFormValidator entryRemindConfigRestFormValidator; @ModelAttribute("entryRemindConfigRestForm") public EntryRemindConfigRestForm entryRemindConfigRestForm() { return new EntryRemindConfigRestForm(); } @InitBinder("entryRemindConfigRestForm") public void validatorBinder(WebDataBinder binder) { binder.addValidators(entryRemindConfigRestFormValidator); } @Override public String getFunctionName() { return "API_ENTRY_REMIND_CONFIG"; } /** * パスワード変更画面表示 * * @param onetimeKey * @return */ @GetMapping("{onetimeKey}") public Resource config(@PathVariable String onetimeKey, @ModelAttribute EntryRemindConfigRestForm form, Model model) { Resource resource = resourceFactory.create(); // ワンタイムキーからユーザーIDを取得する var tUserOnetimePass = entryRemindService.getTUserOnetimePass(onetimeKey); if (tUserOnetimePass == null) { throw new NoDataFoundException("指定されたワンタイムキーが見つかりません。[onetimeKey=" + onetimeKey + "]"); } form.setOnetimeKey(onetimeKey); resource.setMessage(getMessage(MESSAGE_SUCCESS)); return resource; } /** * パスワード変更処理 * * @return */ @PostMapping public Resource changePassword(@Validated @ModelAttribute EntryRemindConfigRestForm form, BindingResult br, Errors errors) { Resource resource = resourceFactory.create(); // 入力チェックエラーがある場合は、元の画面にもどる if (br.hasErrors()) { throw new ValidationErrorException(errors); } // ワンタイムキーからユーザーIDを取得する var tUserOnetimePass = entryRemindService.getTUserOnetimePass(form.getOnetimeKey()); if (tUserOnetimePass == null) { throw new NoDataFoundException( "指定されたワンタイムキーが見つかりません。[onetimeKey=" + form.getOnetimeKey() + "]"); } // パスワードをハッシュ化する String password = passwordEncoder.encode(form.getPassword()); // パスワード変更ワンタイムパス登録 entryRemindService.changePassword(form.getOnetimeKey(), password); resource.setMessage(getMessage(MESSAGE_SUCCESS)); return resource; } }
package com.service; import com.alibaba.fastjson.JSON; import com.domain.model.UserModel; import com.google.common.collect.Lists; import com.netty.dao.mapper.UserMapper; import com.netty.dao.pojo.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import java.util.List; /** * @author anthony_xu * @create $ID: UserServiceImpl, v0.1 2018年05月26日 22:07 anthony_xu Exp $ */ @Service public class UserServiceImpl implements UserService { private final static Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class); @Autowired private UserMapper userMapper; @Override public List<UserModel> queryUserList(UserModel param) { return convertDoToModel(userMapper.selectAllUser()); } private List<UserModel> convertDoToModel(List<User> users) { List<UserModel> userModels = Lists.newArrayList(); if (CollectionUtils.isEmpty(users)) { LOGGER.warn("it's empty"); return userModels; } for (User user : users) { UserModel model = new UserModel(user); userModels.add(model); } return userModels; } @Override public List<UserModel> queryUsersDynamic(UserModel param) { User paramDO = new User(); BeanUtils.copyProperties(param, paramDO); LOGGER.warn(String.format("query param %s", JSON.toJSONString(paramDO))); return convertDoToModel(userMapper.selectUsersDynamic(paramDO)); } @Override public int insertUser(UserModel userModel) { if (userModel == null) { return 0; } User userDO = new User(); BeanUtils.copyProperties(userModel, userDO); LOGGER.warn(String.format("insert value %s", JSON.toJSONString(userDO))); return userMapper.insert(userDO); } }
package org.davidsingleton.piui; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.InetAddress; import java.net.URL; import java.net.UnknownHostException; import android.os.AsyncTask; class PiPollerTask extends AsyncTask<Void, Void, InetAddress> { private PiPollerAddressListener listener; private boolean stop; private static final long POLL_DELAY_MS = 2000; private Thread appCheck; PiPollerTask(PiPollerAddressListener listener) { this.listener = listener; } @Override protected void onPostExecute(final InetAddress result) { if (result != null) { if (listener != null) { listener.onPiFoundAtAddress(result); } startAppCheckPolling(result); } } private void startAppCheckPolling(final InetAddress result) { appCheck = new Thread(new Runnable() { @Override public void run() { boolean appFound = false; while (!appFound && !stop) { try { URL url = new URL("http://" + result.getHostAddress() + "/ping"); InputStream is = (InputStream) url.getContent(); String resp = (new BufferedReader(new InputStreamReader(is))) .readLine(); if (resp.equals("pong")) { appFound = true; listener.onAppFound(); } } catch (IOException e) { // pass } try { Thread.sleep(POLL_DELAY_MS); } catch (InterruptedException e) { } } } }); appCheck.start(); } @Override protected InetAddress doInBackground(Void... params) { InetAddress addr = null; while (addr == null && !stop) { try { addr = InetAddress.getByName("piui"); } catch (UnknownHostException e) { try { Thread.sleep(POLL_DELAY_MS); } catch (InterruptedException e1) { // no matter, continue. } } } return addr; } public void stop() { stop = true; if (appCheck != null) { try { appCheck.join(); } catch (InterruptedException e) { } } } }
package com.tencent.mm.plugin.account.bind.ui; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import com.tencent.mm.kernel.g; import com.tencent.mm.modelsimple.ab; import com.tencent.mm.plugin.account.bind.ui.f.5; class f$5$1 implements OnCancelListener { final /* synthetic */ ab eJf; final /* synthetic */ 5 eJg; f$5$1(5 5, ab abVar) { this.eJg = 5; this.eJf = abVar; } public final void onCancel(DialogInterface dialogInterface) { this.eJg.eJe.onDetach(); g.DF().c(this.eJf); } }
package com.taximagicroshambo.roshambo; import android.app.Activity; import android.app.ListFragment; import android.app.LoaderManager; import android.content.CursorLoader; import android.content.Loader; import android.database.Cursor; import android.os.Bundle; import android.view.View; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import com.taximagicroshambo.roshambo.services.RoshamboContentProvider; /** * Fragment displays the results history */ public class RoshamboHistoryFragmentFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> { private OnFragmentInteractionListener mListener; SimpleCursorAdapter mAdapter; static final String[] RESULTS_PROJECTION = new String[]{ RoshamboContentProvider.Columns._ID, RoshamboContentProvider.Columns.DATE_COLUMN, RoshamboContentProvider.Columns.RESULTS_COLUMN}; // TODO: Rename and change types of parameters public static RoshamboHistoryFragmentFragment newInstance(String param1, String param2) { RoshamboHistoryFragmentFragment fragment = new RoshamboHistoryFragmentFragment(); return fragment; } /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public RoshamboHistoryFragmentFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); setEmptyText(getString(R.string.empty_text)); mAdapter = new SimpleCursorAdapter( getActivity(), android.R.layout.simple_list_item_2, null, new String[]{ RoshamboContentProvider.Columns.DATE_COLUMN, RoshamboContentProvider.Columns.RESULTS_COLUMN}, new int[]{ android.R.id.text1, android.R.id.text2}, 0); setListAdapter(mAdapter); setListShown(false); getLoaderManager().initLoader(0, null, this); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); if (null != mListener) { } } @Override public Loader onCreateLoader(int id, Bundle args) { return new CursorLoader( getActivity(), RoshamboContentProvider.Columns.CONTENT_URI, RESULTS_PROJECTION, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { mAdapter.swapCursor(data); if(isResumed()){ setListShown(true); } else { setListShownNoAnimation(true); } } @Override public void onLoaderReset(Loader<Cursor> loader) { mAdapter.swapCursor(null); } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name public void onFragmentInteraction(String id); } }
package com.example.demo.core.components.cooler; public class CabinetFan implements Cooler{ @Override public int consumedPower() { return 8; } }
package model.object; import java.awt.Color; import acm.graphics.GRect; import model.Helper; /** * Class which represents a brick in the game. * */ public class Brick extends RectangularObject { // ***** FIELDS ***** public final static byte MAXSTATE = 3; public byte state; /** * Constructor. * @param x The x of the brick * @param y The y of the brick * @param w The width of the brick * @param h The height of the brick */ public Brick(double x, double y, double w, double h) { super(x, y, w, h); state = (byte)acm.util.RandomGenerator.getInstance().nextInt(1, MAXSTATE); } // ***** MAIN METHODS ***** /** * Collision method, reduces state of brick (slowly breaking). * @param d Ignored. */ @Override public void onCollision(DeflectDirection d) { state--; } /** * Turns this model into a displayable GObject. * @param cvsWidth The width of the canvas * @param cvsHeight The height of the canvas */ @Override public GRect toGObject(double cvsWidth, double cvsHeight) { GRect brick = super.toGObject(cvsWidth, cvsHeight); brick.setFilled(true); brick.setColor(new Color(255, (int)Helper.map(state, 0, MAXSTATE, 0, 220), 0)); return brick; } }
package com.hawk.application.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.hawk.application.model.Dictionary; import com.hawk.application.repository.springdatajpa.DictionaryRepository; @Service public class DictionaryServiceImpl implements DictionaryService { @Autowired private DictionaryRepository dictionaryRepository; @Override public List<Dictionary> getProvinces() { return dictionaryRepository.findProvinces(); } @Override public List<Dictionary> getCitys(Dictionary province) { return dictionaryRepository.findCitys(province.getId()); } @Override public List<Dictionary> getAllCitys() { return dictionaryRepository.findAllCitys(); } }
package com.timmy.framework.netFw.http; import com.timmy.framework.netFw.http.listener.IHttpListener; import com.timmy.framework.netFw.http.listener.IHttpService; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.HttpResponseException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpParams; import java.io.IOException; /** * Created by timmy1 on 17/4/4. * 发起网络请求 * 得到网络响应的数据 */ public class JsonHttpService implements IHttpService { private String url; private byte[] requestData; private IHttpListener httpListener; private HttpClient httpClient = new DefaultHttpClient(); private HttpResponseHandler httpResponseHandler = new HttpResponseHandler(); private HttpUriRequest httpPost; private HttpGet httpGet; @Override public void setUrl(String url) { this.url = url; } @Override public void setRequestData(byte[] requestData) { this.requestData = requestData; } @Override public void setHttpListener(IHttpListener httpListener) { this.httpListener = httpListener; } @Override public void execute() { //使用HttpClient发起网络请求 //发送post请求 // httpPost = new HttpPost(url); httpGet = new HttpGet(url); //设置请求参数--httppost方法调用不了setentity方法 // ByteArrayEntity byteArrayEntity = new ByteArrayEntity(requestData); // httpPost.setEntity() try { // HttpResponse httpResponse = httpClient.execute(httpPost); httpClient.execute(httpGet, httpResponseHandler); } catch (IOException e) { e.printStackTrace(); httpListener.onFail(1); } } /** * 网络请求后返回的实现类 */ private class HttpResponseHandler extends BasicResponseHandler { @Override public String handleResponse(HttpResponse response) throws ClientProtocolException { int code = response.getStatusLine().getStatusCode(); if (code == 200) { httpListener.onSuccess(response.getEntity()); } else { httpListener.onFail(code); } return null; } } }
package Kodluyoruz_HomeWork_AbdAlrahimZakaria.Week1_Homework; import java.util.Scanner; public class MarketCashier { public static void main(String[] args) { double pears = 2.14; double apples = 3.67; double tomatoes = 1.11; double banana = 0.95; double eggplant = 5.00; double sum=0; Scanner scanner = new Scanner(System.in); System.out.println("How many KG of pears do you want? "); sum += scanner.nextInt()*pears; System.out.println("How many KG of apples do you want? "); sum += scanner.nextInt()*apples; System.out.println("How many KG of tomatoes do you want? "); sum += scanner.nextInt()*tomatoes; System.out.println("How many KG of banana do you want? "); sum += scanner.nextInt()*banana; System.out.println("How many KG of eggplant do you want? "); sum += scanner.nextInt()*eggplant; System.out.println(sum); } }