text
stringlengths 10
2.72M
|
|---|
package ru.netology.web;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
//import io.github.bonigarcia.seljup.SeleniumJupiter;
import org.openqa.selenium.chrome.ChromeOptions;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.openqa.selenium.By.cssSelector;
//@ExtendWith(SeleniumJupiter.class)
public class CardOrderTest {
private WebDriver driver;
@BeforeAll
static void setUpAll() {
WebDriverManager.chromedriver().setup();
}
@BeforeEach
void setUp() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-dev-shm-usage");
options.addArguments("--no-sandbox");
options.addArguments("--headless");
driver = new ChromeDriver(options);
driver.get("http://localhost:9999/");
}
@AfterEach
void tearDown() {
driver.quit();
driver = null;
}
@Test
void shouldSendForm() {
driver.findElement(cssSelector("[data-test-id=name] input")).sendKeys("Иванов Иван");
driver.findElement(cssSelector("[data-test-id='phone'] input")).sendKeys("+79999999999");
driver.findElement(cssSelector(".checkbox__box")).click();
driver.findElement(cssSelector("button")).click();
String message = driver.findElement(cssSelector("[data-test-id=order-success]")).getText();
assertEquals("Ваша заявка успешно отправлена! Наш менеджер свяжется с вами в ближайшее время.", message.strip());
}
@Test
void shouldSendEmptyForm() {
driver.findElement(cssSelector("button")).click();
String message = driver.findElement(cssSelector("[class='input__sub']")).getText();
assertEquals("Поле обязательно для заполнения", message.strip());
}
@Test
void shouldSendFormWithoutPhone() {
driver.findElement(cssSelector("[data-test-id=name] input")).sendKeys("Сергеев Сергей");
driver.findElement(cssSelector(".checkbox__box")).click();
driver.findElement(cssSelector("button")).click();
String message = driver.findElement(cssSelector(".input_invalid .input__sub")).getText();
assertEquals("Поле обязательно для заполнения", message.strip());
}
@Test
void shouldSendFormWithoutName() {
driver.findElement(cssSelector("[data-test-id='phone'] input")).sendKeys("+79999999111");
driver.findElement(cssSelector(".checkbox__box")).click();
driver.findElement(cssSelector("button")).click();
String message = driver.findElement(cssSelector(".input_invalid .input__sub")).getText();
assertEquals("Поле обязательно для заполнения", message.strip());
}
@Test
void shouldSendFormWithoutAgreement() {
driver.findElement(cssSelector("[data-test-id=name] input")).sendKeys("Сергеев Сергей");
driver.findElement(cssSelector("[data-test-id='phone'] input")).sendKeys("+79999999111");
driver.findElement(cssSelector("button")).click();
assertTrue(driver.findElement(cssSelector(".input_invalid > .checkbox__box")).isEnabled());
}
@Test
void shouldSendFormWithIncorrectName() {
driver.findElement(cssSelector("[data-test-id=name] input")).sendKeys("Ivanov Иван");
driver.findElement(cssSelector("[data-test-id='phone'] input")).sendKeys("+79999999999");
driver.findElement(cssSelector(".checkbox__box")).click();
driver.findElement(cssSelector("button")).click();
String message = driver.findElement(cssSelector(".input_invalid .input__sub")).getText();
assertEquals("Имя и Фамилия указаные неверно. Допустимы только русские буквы, пробелы и дефисы.", message.strip());
}
@Test
void shouldSendFormWithIncorrectPhone() {
driver.findElement(cssSelector("[data-test-id=name] input")).sendKeys("Смирнов Иван");
driver.findElement(cssSelector("[data-test-id='phone'] input")).sendKeys("+799999111");
driver.findElement(cssSelector(".checkbox__box")).click();
driver.findElement(cssSelector("button")).click();
String message = driver.findElement(cssSelector(".input_invalid .input__sub")).getText();
assertEquals("Телефон указан неверно. Должно быть 11 цифр, например, +79012345678.", message.strip());
}
}
|
// Andrew Smith
// 12/4/15
//Google Programming Challenge 3 - Access Codes
import java.util.ArrayList;
//---------------------------------------------------------------------------------------------------------
// This program was created for the Google FOOBAR Coding Recruitment Challenge
//
// The application takes a given set of "Access Codes" (made of only lowercase letters) and finds the
// number of distinct access codes as defined by:
//
// Any string that is not repeated both forwards and backwards. "foo" is distinct in the list
// ["foo", "bar], but not in the list ["foo", "oof"].
//
// and returns the total number of distinct codes.
//---------------------------------------------------------------------------------------------------------
public class Answer {
public static int answer(String[] accessCodes) {
ArrayList<String> distinctKeys = new ArrayList<String>();
for (String accessKey: accessCodes) {
if (distinctKeys.contains(accessKey))
continue; //There is an identical string in the saved keys
else if (distinctKeys.contains(new StringBuilder(accessKey).reverse().toString()))
continue; //There is a reversed string in the saved keys
else
distinctKeys.add(accessKey); //The given accessKey is distinct
}
return distinctKeys.size();
}
}
|
/**
* project name:cdds
* file name:TestServiceImpl
* package name:com.cdkj.schedule.schedule.service.impl
* date:2018/9/5 17:03
* author:ywshow
* Copyright (c) CD Technology Co.,Ltd. All rights reserved.
*/
package com.cdkj.schedule.schedule.service.impl;
import com.cdkj.common.base.service.impl.BaseServiceImpl;
import com.cdkj.model.schedule.pojo.Schedule;
import com.cdkj.schedule.schedule.service.api.TestService;
import com.cdkj.util.JsonUtils;
import org.springframework.stereotype.Service;
/**
* description: //TODO <br>
* date: 2018/9/5 17:03
*
* @author ywshow
* @version 1.0
* @since JDK 1.8
*/
@Service
public class TestServiceImpl extends BaseServiceImpl<Schedule,String> implements TestService {
@Override
public void test() {
logger.error(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
}
@Override
public int save(Schedule schedule) {
logger.error("000000000000000000000000000000000000000000"+ JsonUtils.res(schedule));
return 0;
}
@Override
public void info() {
logger.error("KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK");
}
}
|
package pl.rpolak.temperatureconverter.util;
/**
*
* @author Rafal.Polak
*/
public class ConstantsForEquations {
public static final int CONSTANT_1 = 32;
public static final double CONSTANT_2 = 1.8;
public static final double CONSTANT_3 = 273.15;
public static final double CONSTANT_4 = 0.8;
public static final double CONSTANT_5 = 459.67;
public static final double CONSTANT_6 = 2.25;
public static final double CONSTANT_7 = 1.25;
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package calculadoraig;
/**
*
* @author alumno
*/
public class calculadora extends javax.swing.JFrame {
private String memoria1;
private String memoria2;
private String signo;
/**
* Creates new form calculadora
*/
public calculadora() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
pantalla = new javax.swing.JTextField();
cuatro = new javax.swing.JButton();
uno = new javax.swing.JButton();
siete = new javax.swing.JButton();
ocho = new javax.swing.JButton();
cinco = new javax.swing.JButton();
dos = new javax.swing.JButton();
nueve = new javax.swing.JButton();
seis = new javax.swing.JButton();
tres = new javax.swing.JButton();
C = new javax.swing.JButton();
division = new javax.swing.JButton();
multiplicar = new javax.swing.JButton();
CE = new javax.swing.JButton();
resta = new javax.swing.JButton();
suma = new javax.swing.JButton();
unoX = new javax.swing.JButton();
igual = new javax.swing.JButton();
punto = new javax.swing.JButton();
cero = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
pantalla.setBackground(new java.awt.Color(0, 0, 204));
pantalla.setForeground(new java.awt.Color(255, 255, 255));
pantalla.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
cuatro.setBackground(new java.awt.Color(0, 0, 204));
cuatro.setForeground(new java.awt.Color(255, 255, 255));
cuatro.setText("4");
cuatro.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cuatroActionPerformed(evt);
}
});
uno.setBackground(new java.awt.Color(0, 0, 204));
uno.setForeground(new java.awt.Color(255, 255, 255));
uno.setText("1");
uno.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
unoActionPerformed(evt);
}
});
siete.setBackground(new java.awt.Color(0, 0, 204));
siete.setForeground(new java.awt.Color(255, 255, 255));
siete.setText("7");
siete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sieteActionPerformed(evt);
}
});
ocho.setBackground(new java.awt.Color(0, 0, 204));
ocho.setForeground(new java.awt.Color(255, 255, 255));
ocho.setText("8");
ocho.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ochoActionPerformed(evt);
}
});
cinco.setBackground(new java.awt.Color(0, 0, 204));
cinco.setForeground(new java.awt.Color(255, 255, 255));
cinco.setText("5");
cinco.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cincoActionPerformed(evt);
}
});
dos.setBackground(new java.awt.Color(0, 0, 204));
dos.setForeground(new java.awt.Color(255, 255, 255));
dos.setText("2");
dos.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dosActionPerformed(evt);
}
});
nueve.setBackground(new java.awt.Color(0, 0, 204));
nueve.setForeground(new java.awt.Color(255, 255, 255));
nueve.setText("9");
nueve.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nueveActionPerformed(evt);
}
});
seis.setBackground(new java.awt.Color(0, 0, 204));
seis.setForeground(new java.awt.Color(255, 255, 255));
seis.setText("6");
seis.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
seisActionPerformed(evt);
}
});
tres.setBackground(new java.awt.Color(0, 0, 204));
tres.setForeground(new java.awt.Color(255, 255, 255));
tres.setText("3");
tres.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tresActionPerformed(evt);
}
});
C.setBackground(new java.awt.Color(0, 0, 204));
C.setForeground(new java.awt.Color(255, 255, 255));
C.setText("C");
C.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CActionPerformed(evt);
}
});
division.setBackground(new java.awt.Color(0, 0, 204));
division.setForeground(new java.awt.Color(255, 255, 255));
division.setText("/");
division.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
divisionActionPerformed(evt);
}
});
multiplicar.setBackground(new java.awt.Color(0, 0, 204));
multiplicar.setForeground(new java.awt.Color(255, 255, 255));
multiplicar.setText("X");
multiplicar.setActionCommand("x");
multiplicar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
multiplicarActionPerformed(evt);
}
});
CE.setBackground(new java.awt.Color(0, 0, 204));
CE.setForeground(new java.awt.Color(255, 255, 255));
CE.setText("CE");
CE.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CEActionPerformed(evt);
}
});
resta.setBackground(new java.awt.Color(0, 0, 204));
resta.setForeground(new java.awt.Color(255, 255, 255));
resta.setText("-");
resta.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
restaActionPerformed(evt);
}
});
suma.setBackground(new java.awt.Color(0, 0, 204));
suma.setForeground(new java.awt.Color(255, 255, 255));
suma.setText("+");
suma.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
sumaActionPerformed(evt);
}
});
unoX.setBackground(new java.awt.Color(0, 0, 204));
unoX.setForeground(new java.awt.Color(255, 255, 255));
unoX.setText("1/X");
unoX.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
unoXActionPerformed(evt);
}
});
igual.setBackground(new java.awt.Color(0, 0, 204));
igual.setForeground(new java.awt.Color(255, 255, 255));
igual.setText("=");
igual.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
igualActionPerformed(evt);
}
});
punto.setBackground(new java.awt.Color(0, 0, 204));
punto.setForeground(new java.awt.Color(255, 255, 255));
punto.setText(".");
punto.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
puntoActionPerformed(evt);
}
});
cero.setBackground(new java.awt.Color(0, 0, 204));
cero.setForeground(new java.awt.Color(255, 255, 255));
cero.setText("0");
cero.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
ceroActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(32, 32, 32)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pantalla)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cuatro, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(uno, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(siete, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cinco, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(dos, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ocho, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(seis, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tres, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(nueve, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(division, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(multiplicar, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(C, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(cero, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(punto, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(igual, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(resta, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(suma, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(CE, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(unoX))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(pantalla, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(siete, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cuatro, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(uno, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(ocho, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cinco, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(dos, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(nueve, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(seis, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tres, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(C, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(division, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(multiplicar, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(CE, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(resta, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(suma, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(unoX, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(igual, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(punto, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cero, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
pantalla.getAccessibleContext().setAccessibleName("");
pack();
}// </editor-fold>//GEN-END:initComponents
private void cuatroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cuatroActionPerformed
// TODO add your handling code here:
pantalla.setText(pantalla.getText()+"4");
}//GEN-LAST:event_cuatroActionPerformed
private void cincoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cincoActionPerformed
// TODO add your handling code here:
pantalla.setText(pantalla.getText()+"5");
}//GEN-LAST:event_cincoActionPerformed
private void seisActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_seisActionPerformed
// TODO add your handling code here:
pantalla.setText(pantalla.getText()+"6");
}//GEN-LAST:event_seisActionPerformed
private void divisionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_divisionActionPerformed
// TODO add your handling code here:
String cadena = pantalla.getText();
if (cadena.length()>0){
memoria1=cadena;
signo="/";
pantalla.setText("");
}
}//GEN-LAST:event_divisionActionPerformed
private void restaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_restaActionPerformed
// TODO add your handling code here:
String cadena = pantalla.getText();
if (cadena.length()>0){
memoria1=cadena;
signo="-";
pantalla.setText("");
}
}//GEN-LAST:event_restaActionPerformed
private void igualActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_igualActionPerformed
// TODO add your handling code here:
Double num = 0.0;
memoria2 = pantalla.getText();
if(memoria2.length()>0){
switch (signo){
case "+":
num = Double.parseDouble(memoria1)+Double.parseDouble(memoria2);
break;
case "-":
num = Double.parseDouble(memoria1)-Double.parseDouble(memoria2);
break;
case "*":
num = Double.parseDouble(memoria1)*Double.parseDouble(memoria2);
break;
case "/":
num = Double.parseDouble(memoria1)/Double.parseDouble(memoria2);
break;
default:
break;
}
pantalla.setText(num.toString());
}
}//GEN-LAST:event_igualActionPerformed
private void unoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_unoActionPerformed
// TODO add your handling code here:
pantalla.setText(pantalla.getText()+"1");
}//GEN-LAST:event_unoActionPerformed
private void dosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dosActionPerformed
// TODO add your handling code here:
pantalla.setText(pantalla.getText()+"2");
}//GEN-LAST:event_dosActionPerformed
private void tresActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tresActionPerformed
// TODO add your handling code here:
pantalla.setText(pantalla.getText()+"3");
}//GEN-LAST:event_tresActionPerformed
private void sieteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sieteActionPerformed
// TODO add your handling code here:
pantalla.setText(pantalla.getText()+"7");
}//GEN-LAST:event_sieteActionPerformed
private void ochoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ochoActionPerformed
// TODO add your handling code here:
pantalla.setText(pantalla.getText()+"8");
}//GEN-LAST:event_ochoActionPerformed
private void nueveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nueveActionPerformed
// TODO add your handling code here:
pantalla.setText(pantalla.getText()+"9");
}//GEN-LAST:event_nueveActionPerformed
private void ceroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ceroActionPerformed
// TODO add your handling code here:
pantalla.setText(pantalla.getText()+"0");
}//GEN-LAST:event_ceroActionPerformed
private void puntoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_puntoActionPerformed
// TODO add your handling code here:
String cadena;
cadena=pantalla.getText();
//Comprueba si la cadena esta vacia
if(cadena.length()==0){
pantalla.setText("0.");
}else{
//Si no hay ningún punto
if (cadena.indexOf(".")==-1)
pantalla.setText(cadena+".");
}
}//GEN-LAST:event_puntoActionPerformed
private void CActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CActionPerformed
// TODO add your handling code here:
String cadena=pantalla.getText();
if (cadena.length()>0){
cadena = cadena.substring(0, cadena.length()-1);
}
pantalla.setText(cadena);
}//GEN-LAST:event_CActionPerformed
private void CEActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CEActionPerformed
// TODO add your handling code here:
pantalla.setText("");
}//GEN-LAST:event_CEActionPerformed
private void unoXActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_unoXActionPerformed
// TODO add your handling code here:
String cadena = pantalla.getText();
Double num;
if(cadena.length()>0){
num = 1 / (Double.parseDouble(cadena));
pantalla.setText(num.toString());
}
}//GEN-LAST:event_unoXActionPerformed
private void multiplicarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_multiplicarActionPerformed
// TODO add your handling code here:
String cadena = pantalla.getText();
if (cadena.length()>0){
memoria1=cadena;
signo="*";
pantalla.setText("");
}
}//GEN-LAST:event_multiplicarActionPerformed
private void sumaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sumaActionPerformed
// TODO add your handling code here:
String cadena = pantalla.getText();
if (cadena.length()>0){
memoria1=cadena;
signo="+";
pantalla.setText("");
}
}//GEN-LAST:event_sumaActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(calculadora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(calculadora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(calculadora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(calculadora.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new calculadora().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton C;
private javax.swing.JButton CE;
private javax.swing.JButton cero;
private javax.swing.JButton cinco;
private javax.swing.JButton cuatro;
private javax.swing.JButton division;
private javax.swing.JButton dos;
private javax.swing.JButton igual;
private javax.swing.JButton multiplicar;
private javax.swing.JButton nueve;
private javax.swing.JButton ocho;
private javax.swing.JTextField pantalla;
private javax.swing.JButton punto;
private javax.swing.JButton resta;
private javax.swing.JButton seis;
private javax.swing.JButton siete;
private javax.swing.JButton suma;
private javax.swing.JButton tres;
private javax.swing.JButton uno;
private javax.swing.JButton unoX;
// End of variables declaration//GEN-END:variables
}
|
package edu.inheritance.savelyev.denis;
import edu.jenks.dist.inheritance.*;
public class BarcodeItem extends Item implements Barcoded{
public BarcodeItem(boolean bulk, double weight, double price) {
super(bulk);
super.setBulk(bulk);
super.setWeight(weight);
setWeight(weight);
setPrice(price);
}
public double getPrice() {
return 0;
}
public double getTax(double arg0) {
return 0;
}
public double getWeight() {
return 0;
}
public boolean initBuyable(ItemHandler arg0) {
return false;
}
public boolean isBulk() {
return false;
}
public void setBulk(boolean arg0) {
}
public void setWeight(double arg0) {
}
public void setPrice(double arg0) {
}
}
|
package br.chico.recyclerview;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import br.chico.recyclerview.model.Person;
public class PersonAdapter extends RecyclerView.Adapter<PersonAdapter.ViewHolderPerson> {
private List<Person> dataSet;
public PersonAdapter(List<Person> dataSet) {
this.dataSet = dataSet;
}
@Override
public PersonAdapter.ViewHolderPerson onCreateViewHolder(ViewGroup viewGroup, int i) {
LayoutInflater layoutInflater = LayoutInflater.from(viewGroup.getContext());
View view = layoutInflater.inflate(R.layout.list_line, viewGroup, false);
ViewHolderPerson holderPerson = new ViewHolderPerson(view);
return holderPerson;
}
@Override
public void onBindViewHolder(ViewHolderPerson viewHolderPerson, int i) {
if (dataSet != null && dataSet.size() > 0) {
Person person = dataSet.get(i);
viewHolderPerson.textName.setText(person.getName());
viewHolderPerson.textAge.setText(String.valueOf(person.getAge()));
}
}
@Override
public int getItemCount() {
return dataSet.size();
}
public class ViewHolderPerson extends RecyclerView.ViewHolder {
public TextView textName;
public TextView textAge;
public ViewHolderPerson(View itemView) {
super(itemView);
textName = itemView.findViewById(R.id.textName);
textAge = itemView.findViewById(R.id.textAge);
}
}
}
|
import java.util.Date;
public class FileDetails {
private String m_Name;
private String m_Sh1;
private FileType m_FileType;
private String m_WhoUpdatedLast;
private Date m_LastUpdated;
@Override
public String toString() {
return
m_Name + "," +
m_Sh1 + "," +
m_FileType + ","
+ m_WhoUpdatedLast + "," +
m_LastUpdated + "\n";
}
}
|
public class AndOp {
public static void main(String[] args) {
try {
// Terminate program if user does not provide 2 arguments
if (args.length != 2) {
System.out.println("You must enter two decimal numbers. Try again.");
return;
}
// Get command-line values
double firstDouble = Double.parseDouble(args[0]);
double secondDouble = Double.parseDouble(args[1]);
// Default result to false
String result = "false";
// Determine if both numbers meet the requirements of being between 0 and 1
if (firstDouble < 1 && firstDouble > 0 && secondDouble < 1 && secondDouble > 0) {
result = "true";
}
System.out.println(result);
} catch (NumberFormatException exception) {
System.out.println("You must enter two decimal numbers. Try again.");
return;
}
}
}
|
package com.example.breno.pokemobile;
import android.content.Intent;
import android.database.SQLException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.breno.pokemobile.db.JogadorDAO;
import com.example.breno.pokemobile.db.TreinadorDAO;
import com.example.breno.pokemobile.modelo.Jogador;
import com.example.breno.pokemobile.modelo.Treinador;
public class CadastroActivity extends AppCompatActivity {
private Jogador jogador;
private Treinador treinador;
private Integer imagemAtual = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cadastro);
ImageView treinadorIV = (ImageView) findViewById(R.id.treinadorCriar);
treinadorIV.setImageResource(Treinador.getImagemTreinador(imagemAtual));
}
public void anterior(View v) {
ImageView treinadorIV = (ImageView) findViewById(R.id.treinadorCriar);
if(imagemAtual == 0) {
imagemAtual = 12;
}
treinadorIV.setImageResource(Treinador.getImagemTreinador(--imagemAtual));
}
public void proximo(View v) {
ImageView treinadorIV = (ImageView) findViewById(R.id.treinadorCriar);
if(imagemAtual == 11) {
imagemAtual = -1;
}
treinadorIV.setImageResource(Treinador.getImagemTreinador(++imagemAtual));
}
public void cadastrar(View v) {
EditText nome = (EditText) findViewById(R.id.nomeCriarEdit);
EditText usuario = (EditText) findViewById(R.id.usuarioCriarEdit);
EditText senha = (EditText) findViewById(R.id.senhaCriarEdit);
if(nome.getText().toString().equals("") || usuario.getText().toString().equals("") || senha.getText().toString().equals("")) {
Toast.makeText(this, "Preencha todos os campos.", Toast.LENGTH_SHORT).show();
} else {
jogador = new Jogador(usuario.getText().toString(), senha.getText().toString());
treinador = new Treinador(nome.getText().toString(), 1000, imagemAtual, null);
JogadorDAO jogadorDAO = new JogadorDAO(this);
try {
Long idJogador = jogadorDAO.inserir(jogador);
treinador.setIdJogador(idJogador);
TreinadorDAO treinadorDAO = new TreinadorDAO(this);
Long idTreinador = treinadorDAO.inserir(treinador);
treinador.setIdTreinador(idTreinador);
Toast.makeText(this, "Jogador criado com sucesso!", Toast.LENGTH_SHORT).show();
//Encaminhar para o menu principal
// Intent intent = new Intent(CadastroActivity.this, MenuPrincipalActivity.class);
// intent.putExtra("treinador", treinador);
// startActivity(intent);
Intent selecionaPokemon = new Intent(CadastroActivity.this, SelecionaPokemonActivity.class);
selecionaPokemon.putExtra("treinador", treinador);
startActivity(selecionaPokemon);
} catch (SQLException ex) {
Toast.makeText(this, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
}
|
package org.maple.design_pattern.creational.singleton;
/**
* @author mapleins
* @Date 2019-03-15 10:23
* @Desc 懒汉式
**/
public class LazySingleton {
//类初始化时,不初始化这个对象(延时加载,真正用的时候再创建)。
private static LazySingleton instance;
private LazySingleton(){ //私有化构造器
}
//方法同步,调用效率低!
public static synchronized LazySingleton getInstance(){
if(instance==null){
instance = new LazySingleton();
}
return instance;
}
}
|
package net.feliperocha.gameofthree.unit;
import net.feliperocha.gameofthree.domain.*;
import net.feliperocha.gameofthree.listener.dto.MoveDTO;
import org.junit.jupiter.api.*;
import java.util.List;
import java.util.Optional;
import static java.util.Comparator.comparing;
import static net.feliperocha.gameofthree.domain.GameStatus.*;
import static net.feliperocha.gameofthree.domain.MoveCommand.*;
import static net.feliperocha.gameofthree.domain.PlayerStatus.PLAYING;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class GameUnitTest {
private final static Integer DIVISOR = 3;
private final static Integer WINNING_NUMBER = 1;
private final static Integer INITIAL_NUMBER = 56;
private final static Player FIRST_PLAYER = new Player("First", true);
private final static Player SECOND_PLAYER = new Player("Second", false);;
private Game GAME;
@BeforeAll
void create_test_game() {
GAME = new Game();
GAME.setInitialNumber(INITIAL_NUMBER);
GAME.getPlayers().addAll(List.of(FIRST_PLAYER, SECOND_PLAYER));
}
@Test
void execute_moves_until_game_end() {
//given
FIRST_PLAYER.setStatus(PLAYING);
SECOND_PLAYER.setStatus(PLAYING);
//when
GAME.executeMove(new MoveDTO(GAME.getId(), SECOND_PLAYER.getId(), ADD), DIVISOR, WINNING_NUMBER);
GAME.executeMove(new MoveDTO(GAME.getId(), FIRST_PLAYER.getId(), SUBTRACT), DIVISOR, WINNING_NUMBER);
GAME.executeMove(new MoveDTO(GAME.getId(), SECOND_PLAYER.getId(), MAINTAIN), DIVISOR, WINNING_NUMBER);
GAME.executeMove(new MoveDTO(GAME.getId(), FIRST_PLAYER.getId(), ADD), DIVISOR, WINNING_NUMBER);
//then
assertTrue(GAME.getPlayers().stream().allMatch(p -> p.getStatus().equals(PlayerStatus.FINISHED)));
assertEquals(GAME.getStatus(), FINISHED);
assertEquals(GAME.getMoves().stream().max(comparing(Move::getCreatedAt)).get().getCurrentNumber(), WINNING_NUMBER);
assertEquals(GAME.getWinnerPlayer(), Optional.of(FIRST_PLAYER));
}
@Test
void start_game() {
GAME.startGame();
assertEquals(GAME.getStatus(), RUNNING);
assertTrue(GAME.getPlayers().stream().allMatch(p -> p.getStatus().equals(PLAYING)));
}
@Test
void get_first_player() {
assertEquals(GAME.getFirstPlayer(), FIRST_PLAYER);
}
@Test
void get_last_player() {
assertEquals(GAME.getLastPlayer(), SECOND_PLAYER);
}
@Test
void get_next_player() {
//when
FIRST_PLAYER.setStatus(PLAYING);
SECOND_PLAYER.setStatus(PLAYING);
//then
assertEquals(GAME.getNextPlayer(FIRST_PLAYER), SECOND_PLAYER);
assertEquals(GAME.getNextPlayer(SECOND_PLAYER), FIRST_PLAYER);
}
@Test
void disconnect_game() {
GAME.disconnectGame();
assertEquals(GAME.getStatus(), DISCONNECTED);
}
@Test
void get_winner_player() {
assertEquals(GAME.getWinnerPlayer(), Optional.empty());
GAME.setWinnerPlayerId(Optional.of(FIRST_PLAYER.getId()));
assertEquals(GAME.getWinnerPlayer(), Optional.of(FIRST_PLAYER));
}
}
|
package com.uchain.networkmanager.peermanager;
import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.Cancellable;
import akka.actor.Props;
import akka.io.Tcp;
import akka.io.Tcp.CommandFailed;
import akka.io.Tcp.ConnectionClosed;
import akka.io.Tcp.Received;
import akka.io.TcpMessage;
import akka.util.ByteString;
import akka.util.ByteStringBuilder;
import akka.util.CompactByteString;
import com.uchain.core.ChainInfo;
import com.uchain.main.Settings;
import com.uchain.networkmanager.NetworkUtil.*;
import com.uchain.networkmanager.message.MessagePack;
import com.uchain.networkmanager.message.MessageType;
import com.uchain.util.NetworkTimeProvider;
import com.uchain.util.Object2Array;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.concurrent.duration.Duration;
import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;
import java.nio.ByteOrder;
public class PeerConnectionManager extends AbstractActor {
Logger log = LoggerFactory.getLogger(PeerConnectionManager.class);
private Settings settings;
private ActorRef peerHandlerActor;
private ActorRef connection;
private ConnectionType direction;
private InetSocketAddress remote;
private ActorRef networkManager;
private Cancellable handshakeTimeoutCancellableOpt;
private boolean handshakeSent = false;
private boolean handshakeGot = false;
private Handshake receivedHandshake;
private ChainInfo chainInfo;
private ActorRef nodeRef;
private NetworkTimeProvider timeProvider;
private ByteString chunksBuffer;
public PeerConnectionManager(Settings settings, ActorRef peerHandlerActor, ActorRef nodeRef,
ChainInfo chainInfo, ActorRef connection,
ConnectionType direction, InetSocketAddress remote, NetworkTimeProvider timeProvider) {
this.settings = settings;
this.peerHandlerActor = peerHandlerActor;
this.connection = connection;
this.direction = direction;
this.remote = remote;
this.chainInfo = chainInfo;
this.nodeRef = nodeRef;
this.timeProvider = timeProvider;
this.chunksBuffer = CompactByteString.empty();
networkManager = getContext().parent();
// getContext().watch(peerHandlerActor);
getContext().watch(connection);
// getContext().watch(networkManager);
}
public static Props props(Settings settings, ActorRef peerHandlerActor, ActorRef nodeRef,
ChainInfo chainInfo, ActorRef connection,
ConnectionType direction, InetSocketAddress remote, NetworkTimeProvider timeProvider) {
return Props.create(PeerConnectionManager.class, settings, peerHandlerActor, nodeRef, chainInfo, connection, direction, remote,
timeProvider);
}
@Override
public void preStart() {
DoConnecting doConnecting = new DoConnecting();
doConnecting.setDirection(direction);
doConnecting.setRemote(remote);
peerHandlerActor.tell(doConnecting, getSelf());
handshakeTimeoutCancellableOpt = getContext().system().scheduler().scheduleOnce(
Duration.create(Long.parseLong(settings.getHandshakeTimeout()), TimeUnit.SECONDS), new Runnable() {
public void run() {
getSelf().tell(new HandshakeTimeout(), getSelf());
}
}, getContext().system().dispatcher());
connection.tell(TcpMessage.register(getSelf(), false, true), getSelf());
connection.tell(TcpMessage.resumeReading(), getSelf());
}
@Override
public Receive createReceive() {
return receiveBuilder()
.match(DoConnecting.class, msg -> {
log.info(msg.getRemote() + ":" + msg.getDirection());
})
//processErrors
.match(CommandFailed.class, msg -> {
if (msg.cmd() instanceof Tcp.Command) {
log.info("执行命令失败 : " + msg.cmd() + " remote : " + remote);
connection.tell(TcpMessage.resumeReading(), getSelf());
} else if (msg.cmd() instanceof Tcp.Write) {
log.warn("写入失败 :$w " + remote);
connection.tell(TcpMessage.close(), getSelf());
connection.tell(TcpMessage.resumeReading(), getSelf());
connection.tell(TcpMessage.resumeWriting(), getSelf());
}
})
.match(ConnectionClosed.class, msg -> {
Disconnected disconnected = new Disconnected(remote);
peerHandlerActor.tell(disconnected, getSelf());
log.info("链接关闭 : " + remote + ": " + msg.getErrorCause());
getContext().stop(getSelf());
})
.match(CloseConnection.class, msg -> {
log.info("强制中止通信: " + remote);
connection.tell(TcpMessage.close(), getSelf());
})
.match(StartInteraction.class, msg -> {
Handshake handshake = new Handshake(settings.getAgentName(), settings.getAppVersion(),
settings.getNodeName(),chainInfo.getId(),System.currentTimeMillis());
connection.tell(TcpMessage.register(connection), getSelf());
connection.tell(TcpMessage.write(ByteString.fromArray(Object2Array.objectToByteArray(handshake))),
getSelf());
log.info("发送握手到:" + remote);
handshakeSent = true;
if (handshakeGot && handshakeSent)
getSelf().tell(new HandshakeDone(), getSelf());
})
.match(Received.class, msg -> {
try {
receivedHandshake = (Handshake) Object2Array.byteArrayToObject((((Received) msg).data()).toArray());
handleHandshake(receivedHandshake);
} catch (Exception e) {
log.info("解析握手时的错误");
e.printStackTrace();
getSelf().tell(new CloseConnection(), getSelf());
}
})
.match(HandshakeTimeout.class, msg -> {
log.info("与远程" + remote + "握手超时, 将删除连接");
getSelf().tell(new CloseConnection(), getSelf());
})
.match(HandshakeDone.class, msg -> {
if (receivedHandshake == null)
return;
ConnectedPeer peer = new ConnectedPeer(remote, getSelf(), direction, receivedHandshake);
Handshaked handshaked = new Handshaked(peer);
peerHandlerActor.tell(handshaked, getSelf());
handshakeTimeoutCancellableOpt.cancel();
connection.tell(TcpMessage.resumeReading(), getSelf());
getContext().become(workingCycle(connection));
}).build();
}
private void sendMessagePack(MessagePack msg, final ActorRef connection) {
ByteStringBuilder builder = ByteString.createBuilder();
builder.putInt(msg.getData().length + 1, ByteOrder.BIG_ENDIAN);
builder.putByte((byte) MessageType.getMessageTypeByType(msg.getMessageType()));
builder.putBytes(msg.getData());
connection.tell(TcpMessage.write(builder.result()), getSelf());
}
private void processChunksBuffer() {
if (chunksBuffer.length() > 5) {
int payloadLen = chunksBuffer.iterator().getInt(ByteOrder.BIG_ENDIAN);
log.debug("payloadLen=" + payloadLen + " chunksBuffer.length=" + chunksBuffer.length());
if (chunksBuffer.length() >= payloadLen + 4) {
chunksBuffer = chunksBuffer.drop(4);
nodeRef.tell(MessagePack.fromBytes(chunksBuffer, null), ActorRef.noSender());
chunksBuffer = chunksBuffer.drop(payloadLen);
processChunksBuffer();
} else
log.info("not enough data, payloadLen=" + payloadLen + " chunksBuffer.length=" + chunksBuffer.length());
}
}
private Receive workingCycle(final ActorRef connection) {
return receiveBuilder().match(MessagePack.class, msg -> {
// log.info("发送的消息类型:" + msg.getMessageType());
connection.tell(TcpMessage.register(connection), getSelf()); // what for ???
sendMessagePack(msg, connection);
}).match(Received.class, msg -> {
// log.info("接收的消息:" + msg);
chunksBuffer = chunksBuffer.concat(msg.data());
processChunksBuffer();
connection.tell(TcpMessage.resumeReading(), getSelf());
}).build();
}
@Override
public void postStop() {
Disconnected disconnected = new Disconnected(remote);
peerHandlerActor.tell(disconnected, getSelf());
log.info("Peer handler to " + remote + "销毁");
}
public boolean handleHandshake(Handshake handshakeMsg){
if (!chainInfo.getId().equals(handshakeMsg.getChainId())) {
log.error("Peer on a different chain. Closing connection");
context().self().tell(new CloseConnection(),getSelf());
return false;
} else {
long myTime = System.currentTimeMillis();
long timeGap = Math.abs(handshakeMsg.getTime() - myTime);
log.info("peer timeGap = "+timeGap);
if (timeGap > Long.parseLong(settings.getPeerMaxTimeGap())) {
log.error("peer timeGap too large "+timeGap+" Closing connection");
context().self().tell(new CloseConnection(),getSelf());
return false;
}else{
log.info("获得握手:" + remote);
connection.tell(TcpMessage.resumeReading(), getSelf());
networkManager.tell(new GetHandlerToPeerConnectionManager(), getSelf()); // 握手成功后,向PeerConnectionManager发送远程handler
if (receivedHandshake != null)
handshakeGot = true;
if (handshakeGot && handshakeSent)
getSelf().tell(new HandshakeDone(), getSelf());
return true;
}
}
}
}
|
package org.crazyit.app;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class SecondFragment extends Fragment
{
@Override
public View onCreateView(LayoutInflater inflater
, ViewGroup container, Bundle data)
{
TextView tv = new TextView(getActivity());
tv.setGravity(Gravity.CENTER_HORIZONTAL);
tv.setText("第二个Fragment");
tv.setTextSize(40);
return tv;
}
}
|
package com.itheima.service.impl;
import com.itheima.domain.Patient;
import com.itheima.mapper.PatientMapper;
import com.itheima.service.PatientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service("patientService")
public class PatientServiceImpl implements PatientService {
@Autowired
private PatientMapper patientMapper;
@Override
public void save(Patient patient) {
patientMapper.save(patient);
}
@Override
public List<Patient> listAll() {
return patientMapper.listAll();
}
@Override
public List<Patient> listByName(String name) {
return patientMapper.listLikeName("%" + name + "%");
}
}
|
package egovframework.adm.book.controller;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import egovframework.adm.book.service.CpBookAdminService;
import egovframework.adm.cfg.amm.service.AdminMenuManageService;
import egovframework.com.cmm.EgovMessageSource;
import egovframework.com.cmm.service.EgovFileMngUtil;
import egovframework.com.cmm.service.EgovProperties;
@Controller
public class CpBookAdminController {
/** log */
protected static final Log log = LogFactory.getLog(CpBookAdminController.class);
/** EgovMessageSource */
@Resource(name = "egovMessageSource")
EgovMessageSource egovMessageSource;
/** portalActionMainService */
@Resource(name = "cpBookAdminService")
CpBookAdminService cpBookAdminService;
/**
* 연수생관리 > 교재/배송조회 리스트
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/adm/book/selectCpBookList.do")
public String selectCpBookList(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
List list = cpBookAdminService.selectList(commandMap);
List cpList = cpBookAdminService.selectCPList(commandMap);
List subjList = cpBookAdminService.selectSubj(commandMap);
model.addAttribute("list", list);
model.addAttribute("cpList", cpList);
model.addAttribute("subjList", subjList);
model.addAllAttributes(commandMap);
return "adm/book/selectCpBookList";
}
/**
* 엑셀 다운
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/adm/book/selectCpBookExcelDown.do")
public ModelAndView excelDownload(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
List<?> list = cpBookAdminService.selectList(commandMap);
model.addAttribute("list", list);
Map<String, Object> map = new HashMap<String, Object>();
map.put("list", list);
return new ModelAndView("selectCpBookExcelView", "cpBookMap", map);
}
/**
* 배송상태 변경
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/adm/book/updateCpBookStatus.do")
public String updateCpBookStatus(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
String resultMsg = "";
boolean isOk = cpBookAdminService.updateCpbookStatus(commandMap);
if(isOk){
resultMsg = egovMessageSource.getMessage("success.common.save");
}else{
resultMsg = egovMessageSource.getMessage("fail.common.save");
}
model.addAttribute("resultMsg", resultMsg);
model.addAllAttributes(commandMap);
return "forward:/adm/book/selectCpBookList.do";
}
/**
* 정보 삭제
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/adm/book/deleteCpBook.do")
public String deleteCpBook(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
String resultMsg = "";
boolean isOk = cpBookAdminService.deleteCpBook(commandMap);
if(isOk){
resultMsg = egovMessageSource.getMessage("success.common.delete");
}else{
resultMsg = egovMessageSource.getMessage("fail.common.delete");
}
model.addAttribute("resultMsg", resultMsg);
model.addAllAttributes(commandMap);
return "forward:/adm/book/selectCpBookList.do";
}
/**
* 엑셀 업로드 팝업
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/adm/book/cpBookExcelUploadPop.do")
public String cpBookExcelUploadPop(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
Map infoMap = cpBookAdminService.selectSubjInfo(commandMap);
model.addAttribute("infoMap", infoMap);
model.addAllAttributes(commandMap);
return "adm/book/cpBookExcelUploadPop";
}
/**
* 택배사 코드 엑셀 다운
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/adm/book/excelDownForComp.do")
public String selectDeliveryCompExcelList(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
List list = cpBookAdminService.selectDeliveryCompExcelList(commandMap);
model.addAttribute("list", list);
model.addAllAttributes(commandMap);
return "adm/book/selectDeliveryCompExcelList";
}
/**
* 엑셀 업로드
* @param request
* @param response
* @param commandMap
* @param model
* @return
* @throws Exception
*/
@RequestMapping(value="/adm/book/insertExcelFileToDB.do")
public String insertExcelFileToDB(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{
//업로드 처리를 한다.
List<Object> fileList = this.uploadFiles(request, commandMap);
String result = cpBookAdminService.excelDownBookDelivery(commandMap, fileList);
model.addAttribute("result", result);
model.addAllAttributes(commandMap);
return "adm/book/cpBookExcelUploadPop_P";
}
/**
* 업로드된 파일을 등록한다.
*
* @param contentPath 컨텐츠 경로
* @param contentCode 컨텐츠 코드
* @return Directory 생성 여부
* @throws Exception
*/
public List<Object> uploadFiles(HttpServletRequest request, Map<String, Object> commandMap) throws Exception {
//기본 업로드 폴더
String defaultDP = EgovProperties.getProperty("Globals.defaultDP");
log.info("- 기본 업로드 폴더 : " + defaultDP);
List<Object> list = new ArrayList<Object>();
//저장경로 : dp\\bulletin
//파일업로드를 실행한다.
MultipartHttpServletRequest mptRequest = (MultipartHttpServletRequest)request;
java.util.Iterator<?> fileIter = mptRequest.getFileNames();
while (fileIter.hasNext()) {
MultipartFile mFile = mptRequest.getFile((String)fileIter.next());
if (mFile.getSize() > 0) {
Object fileHm = new HashMap();
fileHm = EgovFileMngUtil.uploadContentFile(mFile, defaultDP + File.separator + "bulletin");
list.add(fileHm);
}
}
return list;
}
}
|
package com.example.g0294.tutorial.adapterview;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.g0294.tutorial.R;
public class SpinnerActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner_layout);
//設定string array
String[] mItems = getResources().getStringArray(R.array.languages);
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
Spinner spinner2 = (Spinner) findViewById(R.id.spinner2);
spinner1.setOnItemSelectedListener(new myOnItemSelectedListener());
// 建立Adapter并且載入array,android.R.layout.simple_spinner_item內建的資源檔
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, mItems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
/**simple_spinner_item和simple_spinner_dropdown_item。一個應用於下拉一個應用於Spinner本身。*/
spinner2.setAdapter(adapter);
spinner2.setOnItemSelectedListener(new myOnItemSelectedListener());
}
//監聽當有Item選擇
class myOnItemSelectedListener implements AdapterView.OnItemSelectedListener {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String[] languages = getResources().getStringArray(R.array.languages);
Toast.makeText(SpinnerActivity.this, "選擇的是:" + languages[position], Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
}
|
import processing.core.*;
import processing.data.*;
import processing.event.*;
import processing.opengl.*;
import processing.serial.*;
import java.awt.Robot;
import java.awt.AWTException;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.File;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
public class ProcessingBit extends PApplet {
Serial myPort; // Create object from Serial class
Robot robot;
String valString = "Null";
String oldValString = "aaa";
int oldParsedVal = 0;
int val;
int parsedVal = 0;
int parsedPotVal = 0;
int oldParsedPotVal = 0;
boolean firstRun = true;
boolean veryFirstRun = true;
public void setup()
{
size(200,200);
String COM3 = Serial.list()[0];
println(COM3);
myPort = new Serial(this, COM3, 57600);
try
{
robot = new Robot();
}
catch (AWTException e)
{
println("Robot class not supported by your system!");
exit();
}
}
public void draw()
{
if (myPort.available() > 0) { // If data is available,
valString = myPort.readString(); //read it and store it in val
if(veryFirstRun) { println("Ready to recieve input"); veryFirstRun = false; }
}
//Recieve serial string from COM3 and compare it to open Kappa.png
if(valString.contains("q")){
valString = " "; //Clear the string
println("Button 1 pressed");
open("D:/Users/Christian/Desktop/kappa.png");
}
//Recieve serial string from COM3 and compare it to launch Borger.dk
if(valString.contains("w")) {
valString = " "; //Clear the string
println("Button 2 pressed");
link("https://www.borger.dk/Sider/default.aspx");
}
//Checks if the serial communication starts with R - our protocol for Rotary Rotation
String newValString = valString.trim();
if(newValString.length() > 1){
char c = newValString.charAt(0);
if (c >= 'R') {
StringBuilder sb = new StringBuilder(newValString);
sb.deleteCharAt(0);
String tempString = sb.toString(); //Remove R from the string
if(tempString.length() <= 3){
parsedVal = Integer.parseInt(tempString);
if(parsedVal == 1) {
println("Going up");
robot.mouseWheel(-1);
valString = "";
} else if (parsedVal == 255){
println("Going down");
robot.mouseWheel(1);
valString = "";
}
}
}
}
//Checks if the serial communication starts with P - our protocol for the Slide Potentiometer
String newPotString = valString.trim();
if(newPotString.length() > 1){
char c = newPotString.charAt(0);
if (c >= 'P') {
StringBuilder sb = new StringBuilder(newPotString);
sb.deleteCharAt(0);
String tempString = sb.toString(); //Remove R from the string
if(tempString.length() <= 4){
parsedPotVal = Integer.parseInt(tempString);
if(firstRun) {
oldParsedPotVal = parsedPotVal;
firstRun = false;
}
if (oldParsedPotVal + 4 < parsedPotVal) {
oldParsedPotVal = parsedPotVal;
println("Zooming in");
valString = "";
}
if (parsedPotVal + 4 < oldParsedPotVal) {
oldParsedPotVal = parsedPotVal;
println("Zooming out");
valString = "";
}
}
}
}
}
static public void main(String[] passedArgs) {
String[] appletArgs = new String[] { "ProcessingBit" };
if (passedArgs != null) {
PApplet.main(concat(appletArgs, passedArgs));
} else {
PApplet.main(appletArgs);
}
}
}
|
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Timestamp;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/Login")
public class Login extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String u_name = request.getParameter("Username");
String u_pass = request.getParameter("pass");
Timestamp DateTime = new java.sql.Timestamp(new java.util.Date().getTime());
Connect L = new Connect();
int x = L.check(u_name, u_pass);
String User_role = L.User_role;
System.out.println("connect"+User_role);
if (x == 1) {
HttpSession session = request.getSession();
if (User_role.equals("Admin")) {
response.sendRedirect("Home.jsp");
session.setAttribute("u_name", u_name);
} else if (User_role.equals("Teacher")) {
response.sendRedirect("Home1.jsp");
session.setAttribute("u_name", u_name);
} else {
response.sendRedirect("Home2.jsp");
session.setAttribute("u_name", u_name);
}
String url="jdbc:mysql://localhost:3306/user" ;
String username="root";
String password="root";
try {
String session_id=session.getId();
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(url,username,password);
String sql="INSERT INTO login_history(Session_id,User_name,Login_Time) VALUES (?,?,?)";
PreparedStatement st=con.prepareStatement(sql);
st.setString(1, session_id);
st.setString(2, u_name);
st.setTimestamp(3, DateTime);
st.executeUpdate();
}
catch (Exception e) {
e.printStackTrace();
}
}
else {
response.sendRedirect("Login.jsp");
}
}
}
|
public class Solution{
//if given array doesn't contain duplicate, worst case O(logn) time, if it may contain duplicate, worst case O(n) time.
//iterative solution
public static int search(int[] array,int target){
if(array==null||array.length==0){return -1;}
int low = 0;
int high = array.length-1;
while(low<=high){
int mid = low + (high-low)/2;
if(array[mid]==target){return mid;}
if(array[mid]>array[low]){
if(target>=array[low]&&target<array[mid]){
high = mid - 1;
}else{
low = mid + 1;
}
}else if(array[mid]<array[low]){
if(target>array[mid]&&target<=array[high]){
low = mid + 1;
}else{
high = mid - 1;
}
}else{ //when array[mid] == array[low], we are not sure which half target may locate. So we can simply remove array[low] from search range because array[low] == array[mid] != target
low++;
}
}
return -1;//given target not found
}
//recursive solution
public static int search2(int[] array,int target){
return binSearch(array,target,0,array.length-1);
}
private static int binSearch(int[] array,int target,int low,int high){
if(low>high){
return -1;
}
int mid = low + (high-low)/2;
if(array[mid]==target){return mid;}
if(array[mid]>array[low]){
if(target>=array[low]&&target<array[mid]){
return binSearch(array,target,low,mid-1);
}else{
return binSearch(array,target,mid+1,high);
}
}else if(array[mid]<array[low]){
if(target>array[mid]&&target<array[low]){
return binSearch(array,target,mid+1,high);
}else{
return binSearch(array,target,low,mid-1);
}
}else{
if(array[mid]!=array[high]){
return binSearch(array,target,mid+1,high);
}else{
int result = binSearch(array,target,low,mid-1);
if(result==-1){
return binSearch(array,target,mid+1,high);
}else{
return result;
}
}
}
}
}
|
package com.hoon.project.reactivewithmongodb.repository.secondary;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
/**
* Created by babybong on 09/01/2019.
*/
public interface SecondaryRepository extends ReactiveMongoRepository<SecondaryModel, String> {
}
|
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.messaging.converter;
import java.util.Collections;
import org.junit.jupiter.api.Test;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageHeaderAccessor;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for
* {@link org.springframework.messaging.converter.SimpleMessageConverter}.
*
* @author Rossen Stoyanchev
*/
public class SimpleMessageConverterTests {
private final SimpleMessageConverter converter = new SimpleMessageConverter();
@Test
public void toMessageWithPayloadAndHeaders() {
MessageHeaders headers = new MessageHeaders(Collections.<String, Object>singletonMap("foo", "bar"));
Message<?> message = this.converter.toMessage("payload", headers);
assertThat(message.getPayload()).isEqualTo("payload");
assertThat(message.getHeaders().get("foo")).isEqualTo("bar");
}
@Test
public void toMessageWithPayloadAndMutableHeaders() {
MessageHeaderAccessor accessor = new MessageHeaderAccessor();
accessor.setHeader("foo", "bar");
accessor.setLeaveMutable(true);
MessageHeaders headers = accessor.getMessageHeaders();
Message<?> message = this.converter.toMessage("payload", headers);
assertThat(message.getPayload()).isEqualTo("payload");
assertThat(message.getHeaders()).isSameAs(headers);
assertThat(message.getHeaders().get("foo")).isEqualTo("bar");
}
}
|
package model;
import java.sql.Date;
import java.sql.Timestamp;
public class Message_DTO {
private int msg_no;
private String msg_title;
private String msg_content;
private Timestamp msg_date;
private int msg_state;
private int msg_sender;
private int msg_receiver;
private String rcv_sname;
private String sen_sname;
private String member;
public String getMember() {
return member;
}
public void setMember(String member) {
this.member = member;
}
public String getRcv_sname() {
return rcv_sname;
}
public void setRcv_sname(String rcv_sname) {
this.rcv_sname = rcv_sname;
}
public String getSen_sname() {
return sen_sname;
}
public void setSen_sname(String sen_sname) {
this.sen_sname = sen_sname;
}
public int getMsg_no() {
return msg_no;
}
public void setMsg_no(int msg_no) {
this.msg_no = msg_no;
}
public String getMsg_title() {
return msg_title;
}
public void setMsg_title(String msg_title) {
this.msg_title = msg_title;
}
public String getMsg_content() {
return msg_content;
}
public void setMsg_content(String msg_content) {
this.msg_content = msg_content;
}
public Timestamp getMsg_date() {
return msg_date;
}
public void setMsg_date(Timestamp msg_date) {
this.msg_date = msg_date;
}
public int getMsg_state() {
return msg_state;
}
public void setMsg_state(int msg_state) {
this.msg_state = msg_state;
}
public int getMsg_sender() {
return msg_sender;
}
public void setMsg_sender(int msg_sender) {
this.msg_sender = msg_sender;
}
public int getMsg_receiver() {
return msg_receiver;
}
public void setMsg_receiver(int msg_receiver) {
this.msg_receiver = msg_receiver;
}
public Message_DTO() {
}
}
|
package com.saechimdaeki.chap02;
import org.springframework.data.repository.query.ReactiveQueryByExampleExecutor;
public interface ItemByExampleRepository extends ReactiveQueryByExampleExecutor<Item> {
}
|
package mapx.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* Spring辅助工具类,主要用于在任何地方获取Spring管理的Bean对象
* @author Ready
* @date 2012-08-18
*/
public class SpringUtil implements ApplicationContextAware {
// Spring应用上下文环境
private static ApplicationContext applicationContext;
/**
* 实现ApplicationContextAware接口的回调方法,设置上下文环境
* @param applicationContext
*/
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringUtil.applicationContext = applicationContext;
}
/**
* 获取ApplicationContext对象
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 获取Spring管理的Bean对象
* @param name spring管理的bean的名称
* @return Object 返回Spring管理的bean实例,如果指定实例不存在将抛出异常
* @throws BeansException
*/
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.innovaciones.reporte.serviceRest;
import com.innovaciones.reporte.model.AsignacionReparacion;
import com.innovaciones.reporte.service.AsignacionReparacionService;
import com.innovaciones.reporte.service.NotificacionService;
import com.innovaciones.reporte.util.Utilities;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/asignacionReparacionService")
public class AsignacionReparacionServiceRest extends Utilities {
@Autowired
private AsignacionReparacionService asignacionReparacionService;
@Autowired
private NotificacionService notificacionService;
@RequestMapping(value = "/getNotificacionesByEstadoReporteByIdUsuario/{id}", method = RequestMethod.GET, produces = "application/json")
@CrossOrigin(origins = "*", maxAge = 3600)
public ResponseEntity<List<AsignacionReparacion>> getNotificacionesByEstadoReporteByIdUsuario(@PathVariable("id") Integer id) {
List<AsignacionReparacion> lista = asignacionReparacionService.getIdUsuarioAtencionByEstado(id, "ASIGNADO");
System.out.println("TAMANIO " + lista.size());
return new ResponseEntity<List<AsignacionReparacion>>(lista, headers(), HttpStatus.OK);
}
@RequestMapping(value = "/ejecutar/{id}", method = RequestMethod.GET, produces = "application/json")
@CrossOrigin(origins = "*", maxAge = 3600)
public ResponseEntity<AsignacionReparacion> AsignacionReparacion(@PathVariable("id") Integer id) {
AsignacionReparacion as = asignacionReparacionService.getAsignacionReparacionById(id);
// System.out.println("ENTIDAD == " + reparacion);
// enviarNotificacion(reparacion);
if (asignacionReparacionService.enviarNotificacion(as)) {
System.out.println("ENVIADOP ");
} else {
System.out.println("ERROR EN LA NOTIFICACIOSN ");
}
return new ResponseEntity<AsignacionReparacion>(as, headers(), HttpStatus.OK);
}
}
|
package it.sparks.postdb.entity;
import javax.persistence.*;
import java.io.Serializable;
import java.util.List;
@Entity
@Table(name = "image")
@NamedQueries({
@NamedQuery(name = "Image.findAll", query = "SELECT i FROM Image i")
})
public class Image implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "idImage", nullable = false)
private Integer idImage;
@ManyToOne
@JoinColumn(name = "idPost")
private Post post;
@Column(name = "mimeType")
private String mimeType;
@Column(name = "originalNameFile")
private String originalNameFile;
@Column(name = "imageBinary")
private byte[] imageBinary;
@OneToMany(mappedBy = "image")
private List<Tag> tags;
public Integer getIdImage() {
return idImage;
}
public void setIdImage(Integer idImage) {
this.idImage = idImage;
}
public Post getPost() {
return post;
}
public void setPost(Post post) {
this.post = post;
}
public String getMimeType() {
return mimeType;
}
public void setMimeType(String mimeType) {
this.mimeType = mimeType;
}
public String getOriginalNameFile() {
return originalNameFile;
}
public void setOriginalNameFile(String originalNameFile) {
this.originalNameFile = originalNameFile;
}
public byte[] getImageBinary() {
return imageBinary;
}
public void setImageBinary(byte[] imageBinary) {
this.imageBinary = imageBinary;
}
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
}
|
package com.example.david.hackathon;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class CreateGoal extends AppCompatActivity {
private EditText title;
private EditText description;
private Button submit;
private String sTitle;
private String sDescription;
private SharedPreferences settings;
private SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_goal);
title = (EditText) findViewById(R.id.title);
description = (EditText) findViewById(R.id.description);
submit = (Button) findViewById(R.id.submit);
settings = getSharedPreferences(Login.SHAREDPREFS, 0);
editor = settings.edit();
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sTitle = title.getText().toString();
sDescription = description.getText().toString();
sendPostRequest(sTitle,sDescription);
int numGoals = settings.getInt("numGoals",0);
String[] titles = new String[numGoals];
String[] descriptions = new String[numGoals];
for(int i = 0; i < numGoals-1; i++){
titles[i] = settings.getString("title_"+i,"");
descriptions[i] = settings.getString("description_"+i,"");
}
for(int i = 0; i < numGoals-1; i++){
editor.putString("title_"+i,titles[i]);
editor.putString("description_"+i,descriptions[i]);
}
editor.putString("title_"+numGoals,sTitle);
editor.putString("description_"+numGoals,sDescription);
editor.putBoolean("goalAdded",true);
editor.putInt("numGoals",numGoals+1);
editor.commit();
Intent i = new Intent(getBaseContext(),MainActivity.class);
startActivity(i);
}
});
}
private void sendPostRequest(final String title, final String description){
RequestQueue queue = Volley.newRequestQueue(this);
String username = settings.getString("username","not_found");
String url ="http://"+Login.serverURL+"/user/goals?u="+username;
StringRequest sRequest = new StringRequest
(Request.Method.POST, url,new Response.Listener<String>() {
@Override
public void onResponse(String response) {
String account = response;
Log.v("HEYy", response);
editor.putString("post_goal_response",account);
editor.commit();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
String account = error.toString();
editor.putString("post_goal_response",account);
editor.commit();
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("title", title);
params.put("description", description);
return params;
}
};
queue.add(sRequest);
}
}
|
package com.app.mymvvmsample.view.activities;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import com.app.mymvvmsample.R;
import com.app.mymvvmsample.model.UserCategoryModel;
import com.app.mymvvmsample.view.adapters.UserCategoriesAdapter;
import com.app.mymvvmsample.viewmodel.CategoriesViewModel;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends BaseActivity implements View.OnClickListener {
@BindView(R.id.iv_backbtn)
ImageView iv_backbtn;
@BindView(R.id.rv_usercategorieslist)
RecyclerView rv_usercategorieslist;
@BindView(R.id.iv_add)
ImageView iv_add;
private CategoriesViewModel categoriesViewModel;
private ArrayList<UserCategoryModel> userCategoryModelArrayList=new ArrayList<>();
private UserCategoriesAdapter categoriesAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
ButterKnife.bind(this);
init();
}
private void init()
{
iv_backbtn.setOnClickListener(this);
iv_add.setOnClickListener(this);
rv_usercategorieslist.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
categoriesAdapter=new UserCategoriesAdapter(this,userCategoryModelArrayList);
rv_usercategorieslist.setAdapter(categoriesAdapter);
categoriesViewModel= ViewModelProviders.of(this).get(CategoriesViewModel.class);
categoriesViewModel.getUsercategoryList().observe(this, new Observer<List<UserCategoryModel>>() {
@Override
public void onChanged(@Nullable List<UserCategoryModel> userCategoryModels) {
Log.e("Onchanged","onchanged");
userCategoryModelArrayList.addAll(userCategoryModels);
categoriesAdapter.notifyDataSetChanged();
}
});
if(isInternetConnected())
categoriesViewModel.getUserCategories();
else
showInternetToast();
}
@Override
public void onClick(View view) {
switch (view.getId())
{
case R.id.iv_backbtn:
finish();
break;
case R.id.iv_add:
Intent intent=new Intent(MainActivity.this,HashtagsActivity.class);
startActivity(intent);
break;
}
}
}
|
package com.jushu.video.controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jushu.video.api.Pages;
import com.jushu.video.api.ParamFilter;
import com.jushu.video.api.Response;
import com.jushu.video.common.IpUtil;
import com.jushu.video.entity.GmOperation;
import com.jushu.video.service.IGmOperationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* <p>
* 前端控制器
* </p>
*
* @author chen
* @since 2020-01-09
*/
@Controller
@RequestMapping("/video/gm-operation")
public class GmOperationController {
@Autowired
private IGmOperationService iGmOperationService;
@GetMapping("/list")
public String list(){
return "webLogList";
}
@PostMapping("/list")
@ResponseBody
public Response list(@RequestBody ParamFilter queryFilter, HttpServletRequest request, HttpSession session) {
//new 一个mybatis plus分页对象
Page<GmOperation> page = new Page<>();
//pages为自己封装的分页工具类,对应页面
Pages pages = queryFilter.getPage();
//如果pages不为空,则为page放入当前页、每页显示条数
if(pages != null) {
page.setCurrent(pages.getPageNo());
page.setSize(pages.getPageSize());
} else {
//如果pages为空则默认当前页为第一页,每页显示10条
page.setCurrent(1);
page.setSize(10);
}
//获取当前方法名
String method = Thread.currentThread().getStackTrace()[1].getMethodName();
//操作事件
String operation = "查询管理员操作列表";
//当前用户登录IP
String loginIp = IpUtil.getIpAddr(request);
//操作是否成功
int isSuccess = 0;
//备注:查询成功
String remark = "查询成功";
boolean flag = iGmOperationService.saveOperation(method, loginIp, operation, isSuccess, remark, session);
if(flag) {
Page<GmOperation> operationList = iGmOperationService.operationPageList(page, queryFilter);
//得到总记录数,页面上自动计算页数
pages.setResultCount((int) operationList.getTotal());
//返回数据至页面
return new Response(operationList.getRecords(), pages);
} else {
return new Response("数据出现问题,请联系管理员!");
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bookstore.DAL;
import bookstore.Entity.CTPX;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
/**
*
* @author HieuNguyen
*/
public class CTPXDAL extends SqlDataConnection{
private final String INSERT = "insert into tb_CTPX(maCTPX,maPhieuXuat,maSach,soLuong,thanhTien) values(?,?,?,?,?)";
private final String UPDATE = "UPDATE [dbo].[tb_CTPX] SET [maSach] = ? ,[soLuong] = ?,thanhTien = ? WHERE [maCTPX] = ?";
private final String DELETE_ALL = "DELETE FROM [dbo].[tb_CTPX] WHERE maPhieuXuat = ?";
private final String DELETE = "DELETE FROM [dbo].[tb_CTPX] WHERE maCTPX = ?";
public ArrayList<CTPX> getAll(String TOP, String WHERE, String ORDER) {
String GET_ALL = "select * from tb_CTPX";
ArrayList<CTPX> arr = new ArrayList<>();
if (TOP.length() != 0 || WHERE.length() != 0 || ORDER.length() != 0) {
GET_ALL = "SELECT ";
if (TOP.length() != 0) {
GET_ALL += "TOP " + TOP;
}
GET_ALL += "* FROM tb_CTPX ";
if (WHERE.length() != 0) {
GET_ALL += "WHERE " + WHERE;
}
if (ORDER.length() != 0) {
GET_ALL += "ORDER BY " + ORDER;
}
}
// System.out.println(GET_ALL);
try {
openConnection();
PreparedStatement ps = con.prepareStatement(GET_ALL);
ResultSet rs = ps.executeQuery();
if (rs != null) {
while (rs.next()) {
CTPX item = new CTPX();
item.setMaCTPX(rs.getString("maCTPX"));
item.setMaPhieuXuat(rs.getString("maPhieuXuat"));
item.setMaSach(rs.getString("maSach"));
item.setSoLuong(rs.getInt("soLuong"));
item.setThanhTien(rs.getInt("thanhTien"));
arr.add(item);
}
}
closeConnection();
} catch (Exception e) {
e.printStackTrace();
}
return arr;
}
public boolean insertData(CTPX data) {
boolean check = false;
try {
openConnection();
PreparedStatement ps = con.prepareStatement(INSERT);
ps.setString(1, data.getMaCTPX());
ps.setString(2, data.getMaPhieuXuat());
ps.setString(3, data.getMaSach());
ps.setInt(4, data.getSoLuong());
ps.setInt(5, data.getThanhTien());
int rs = ps.executeUpdate();
if (rs > 0) {
check = true;
}
closeConnection();
} catch (Exception e) {
e.printStackTrace();
}
return check;
}
public boolean updateData(CTPX data) {
boolean check = false;
try {
openConnection();
PreparedStatement ps = con.prepareCall(UPDATE);
// ps.setString(1, data.getMaPhieuXuat());
ps.setString(1, data.getMaSach());
ps.setInt(2, data.getSoLuong());
ps.setInt(3, data.getThanhTien());
ps.setString(4, data.getMaCTPX());
int rs = ps.executeUpdate();
if (rs > 0) {
check = true;
}
closeConnection();
} catch (Exception e) {
e.printStackTrace();
}
return check;
}
public boolean deleteData_PX(String id) {
boolean check = false;
try {
openConnection();
PreparedStatement ps = con.prepareCall(DELETE_ALL);
ps.setString(1, id);
int rs = ps.executeUpdate();
if (rs > 0) {
check = true;
}
closeConnection();
} catch (Exception e) {
e.printStackTrace();
}
return check;
}
public boolean deleteData_CTPX(String id) {
boolean check = false;
try {
openConnection();
PreparedStatement ps = con.prepareCall(DELETE);
ps.setString(1, id);
int rs = ps.executeUpdate();
if (rs > 0) {
check = true;
}
closeConnection();
} catch (Exception e) {
e.printStackTrace();
}
return check;
}
}
|
package com.spreadtrum.android.eng;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.util.Log;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
public class DebugParam extends PreferenceActivity {
private String mATline;
private int mAssertMdoe;
private boolean[] mBandCheckList = new boolean[]{false, false, false, false};
private Preference mBandSelectPreference;
private int[] mBandShowList = new int[]{1, 2, 4, 8};
private engfetch mEf;
private boolean mHaveFinish = true;
private int mSocketID;
private Handler mThread;
private Handler mUiThread;
private ByteArrayOutputStream outputBuffer;
private DataOutputStream outputBufferStream;
class AsyncnonizeHandler extends Handler {
public AsyncnonizeHandler(Looper looper) {
super(looper);
}
public void handleMessage(Message msg) {
Builder builder;
int i;
switch (msg.what) {
case 0:
builder = new Builder(DebugParam.this);
int value = DebugParam.this.getSelectedBand();
if (value != -1) {
int param = BandSelectDecoder.getInstance().getBandsFromCmdParam(value);
for (i = 0; i < DebugParam.this.mBandShowList.length; i++) {
if ((DebugParam.this.mBandShowList[i] & param) != 0) {
DebugParam.this.mBandCheckList[i] = true;
}
}
builder.setMultiChoiceItems(R.array.band_select_choices, DebugParam.this.mBandCheckList, new OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
DebugParam.this.mBandCheckList[which] = isChecked;
}
});
builder.setPositiveButton("OK ", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
DebugParam.this.mThread.obtainMessage(1).sendToTarget();
}
});
DebugParam.this.showDialog(builder, String.valueOf(msg.obj));
break;
}
Toast.makeText(DebugParam.this, "Error", 0).show();
break;
case 1:
int selectBands = 0;
for (i = 0; i < DebugParam.this.mBandCheckList.length; i++) {
if (DebugParam.this.mBandCheckList[i]) {
selectBands |= DebugParam.this.mBandShowList[i];
}
}
int cmdFromBands = BandSelectDecoder.getInstance().getCmdParamFromBands(selectBands);
if (cmdFromBands != -1) {
final int select = selectBands;
if (DebugParam.this.setSelectedBand(cmdFromBands)) {
DebugParam.this.mUiThread.post(new Runnable() {
public void run() {
DebugParam.this.mBandSelectPreference.setSummary(DebugParam.this.getBandSelectSummary(BandSelectDecoder.getInstance().getCmdParamFromBands(select)));
}
});
break;
}
}
Toast.makeText(DebugParam.this, R.string.set_bands_error, 0).show();
Log.e("DebugParam", "Error, cmdFromBands = -1");
return;
break;
case 2:
builder = new Builder(DebugParam.this);
int mode = DebugParam.this.getAssertMode();
if (mode != -1) {
DebugParam.this.mAssertMdoe = mode;
builder.setSingleChoiceItems(R.array.assert_mode, DebugParam.this.mAssertMdoe, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
DebugParam.this.mAssertMdoe = which;
}
});
builder.setPositiveButton("OK ", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Message msg = DebugParam.this.mThread.obtainMessage(3);
msg.arg1 = DebugParam.this.mAssertMdoe;
msg.sendToTarget();
}
});
DebugParam.this.showDialog(builder, String.valueOf(msg.obj));
break;
}
Toast.makeText(DebugParam.this, "Error", 0).show();
break;
case 4:
DebugParam.this.setManualAssert();
break;
case 5:
final String summary = DebugParam.this.getBandSelectSummary(DebugParam.this.getSelectedBand());
DebugParam.this.mUiThread.post(new Runnable() {
public void run() {
DebugParam.this.mBandSelectPreference.setSummary(summary);
}
});
break;
}
super.handleMessage(msg);
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.mEf = new engfetch();
this.mSocketID = this.mEf.engopen();
addPreferencesFromResource(R.layout.debugparam);
this.mBandSelectPreference = findPreference("key_bandselect");
this.mUiThread = new Handler();
HandlerThread t = new HandlerThread("debugparam");
t.start();
this.mThread = new AsyncnonizeHandler(t.getLooper());
this.mThread.obtainMessage(6).sendToTarget();
this.mThread.obtainMessage(5).sendToTarget();
}
protected void onStart() {
this.mHaveFinish = false;
super.onStart();
}
protected void onStop() {
this.mHaveFinish = true;
super.onStop();
}
private void showDialog(final Builder builder, final String title) {
this.mUiThread.post(new Runnable() {
public void run() {
if (!DebugParam.this.mHaveFinish) {
builder.setTitle(title);
builder.create().show();
}
}
});
}
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
String key = preference.getKey();
Message obtainMessage;
if ("key_bandselect".equals(key)) {
obtainMessage = this.mThread.obtainMessage(0);
obtainMessage.obj = preference.getTitle();
obtainMessage.sendToTarget();
} else if ("key_assertmode".equals(key)) {
obtainMessage = this.mThread.obtainMessage(2);
obtainMessage.obj = preference.getTitle();
obtainMessage.sendToTarget();
} else if ("key_manualassert".equals(key)) {
obtainMessage = this.mThread.obtainMessage(4);
obtainMessage.obj = preference.getTitle();
obtainMessage.sendToTarget();
} else if ("key_forbidplmn".equals(key)) {
startActivity(new Intent(this, TextInfo.class).putExtra("text_info", 1));
} else if ("key_plmnselect".equals(key)) {
startActivity(new Intent(this, TextInfo.class).putExtra("text_info", 2));
}
return true;
}
private boolean setSelectedBand(int bands) {
this.outputBuffer = new ByteArrayOutputStream();
this.outputBufferStream = new DataOutputStream(this.outputBuffer);
this.mATline = 2 + "," + 1 + "," + bands;
try {
this.outputBufferStream.writeBytes(this.mATline);
this.mEf.engwrite(this.mSocketID, this.outputBuffer.toByteArray(), this.outputBuffer.toByteArray().length);
byte[] inputBytes = new byte[128];
if (new String(inputBytes, 0, this.mEf.engread(this.mSocketID, inputBytes, 128), Charset.defaultCharset()).indexOf("ERROR") == -1) {
return true;
}
Toast.makeText(this, R.string.set_bands_error, 1).show();
return false;
} catch (IOException e) {
Log.e("DebugParam", "writeBytes() error!");
return true;
}
}
private int getSelectedBand() {
this.outputBuffer = new ByteArrayOutputStream();
this.outputBufferStream = new DataOutputStream(this.outputBuffer);
this.mATline = 3 + "," + 0;
try {
this.outputBufferStream.writeBytes(this.mATline);
this.mEf.engwrite(this.mSocketID, this.outputBuffer.toByteArray(), this.outputBuffer.toByteArray().length);
byte[] inputBytes = new byte[128];
String mATResponse = new String(inputBytes, 0, this.mEf.engread(this.mSocketID, inputBytes, 128), Charset.defaultCharset());
Log.d("DebugParam", "getSelectedBand result : " + mATResponse);
int value = -1;
try {
return Integer.parseInt(mATResponse);
} catch (Exception e) {
Log.e("DebugParam", "Format String " + mATResponse + " to Integer Error!");
return value;
}
} catch (IOException e2) {
Log.e("DebugParam", "writeBytes() error!");
return -1;
}
}
private int getAssertMode() {
this.outputBuffer = new ByteArrayOutputStream();
this.outputBufferStream = new DataOutputStream(this.outputBuffer);
this.mATline = 108 + "," + 0;
try {
this.outputBufferStream.writeBytes(this.mATline);
int size = this.mEf.engwrite(this.mSocketID, this.outputBuffer.toByteArray(), this.outputBuffer.toByteArray().length);
byte[] inputBytes = new byte[128];
String mATResponse = new String(inputBytes, 0, this.mEf.engread(this.mSocketID, inputBytes, 128), Charset.defaultCharset());
Log.d("DebugParam", "getAssertMode result : " + mATResponse);
if (mATResponse.indexOf("+SDRMOD: 1") != -1) {
return 1;
}
if (mATResponse.indexOf("+SDRMOD: 0") == -1) {
return -1;
}
return 0;
} catch (IOException e) {
Log.e("DebugParam", "writeBytes() error!");
return -1;
}
}
private void setManualAssert() {
this.outputBuffer = new ByteArrayOutputStream();
this.outputBufferStream = new DataOutputStream(this.outputBuffer);
this.mATline = 110 + "," + 0;
try {
this.outputBufferStream.writeBytes(this.mATline);
} catch (IOException e) {
Log.e("DebugParam", "writeBytes() error!");
}
int datasize = this.outputBuffer.toByteArray().length;
int iRet = this.mEf.engwrite(this.mSocketID, this.outputBuffer.toByteArray(), datasize);
Log.d("DebugParam", "setManualAssert engwrite size: " + iRet);
if (datasize == iRet) {
Toast.makeText(this, "Success", 0).show();
} else {
Toast.makeText(this, "Error", 0).show();
}
}
private String getBandSelectSummary(int band) {
String bandString = null;
if (band == -1) {
return "";
}
int param = BandSelectDecoder.getInstance().getBandsFromCmdParam(band);
for (int i = 0; i < this.mBandShowList.length; i++) {
if ((this.mBandShowList[i] & param) != 0) {
if (bandString == null) {
bandString = getResources().getStringArray(R.array.band_select_choices)[i];
} else {
bandString = bandString + "|" + getResources().getStringArray(R.array.band_select_choices)[i];
}
}
}
return bandString;
}
}
|
/*
* Ara - Capture Species and Specimen Data
*
* Copyright © 2009 INBio (Instituto Nacional de Biodiversidad).
* Heredia, Costa Rica.
*
* 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 org.inbio.ara.persistence.identification;
import java.util.Calendar;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.inbio.ara.persistence.GenericEntity;
import org.inbio.ara.persistence.LogGenericEntity;
/**
*
* @author asanabria
*/
@Entity
@Table(name = "identifier")
public class Identifier extends LogGenericEntity{
private static final long serialVersionUID = 1L;
@EmbeddedId
protected IdentifierPK identifierPK;
@Basic(optional = false)
@Column(name = "identifier_sequence")
private Long identifierSequence;
@JoinColumns({
@JoinColumn(name = "specimen_id", referencedColumnName = "specimen_id" , updatable=false, insertable=false),
@JoinColumn(name = "identification_sequence", referencedColumnName = "identification_sequence", updatable=false, insertable=false),
@JoinColumn(name = "initial_timestamp", referencedColumnName = "initial_timestamp", updatable=false, insertable=false)
})
@ManyToOne( cascade={CascadeType.ALL}, fetch = FetchType.EAGER)
private Identification identification;
public Identifier() {
}
public Identifier(IdentifierPK identifierPK) {
this.identifierPK = identifierPK;
}
public Identifier(IdentifierPK identifierPK, Long identifierSequence,
String createdBy, Calendar creationDate,
Calendar lastModificationDate, String lastModificationBy) {
this.identifierPK = identifierPK;
this.identifierSequence = identifierSequence;
this.setCreatedBy(createdBy);
this.setCreationDate(creationDate);
this.setLastModificationDate(lastModificationDate);
this.setLastModificationBy(lastModificationBy);
}
public IdentifierPK getIdentifierPK() {
return identifierPK;
}
public void setIdentifierPK(IdentifierPK identifierPK) {
this.identifierPK = identifierPK;
}
public Long getIdentifierSequence() {
return identifierSequence;
}
public void setIdentifierSequence(Long identifierSequence) {
this.identifierSequence = identifierSequence;
}
public Identification getIdentification() {
return identification;
}
public void setIdentification(Identification identification) {
this.identification = identification;
}
@Override
public int hashCode() {
int hash = 0;
hash += (identifierPK != null ? identifierPK.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Identifier)) {
return false;
}
Identifier other = (Identifier) object;
if ((this.identifierPK == null && other.identifierPK != null) || (this.identifierPK != null && !this.identifierPK.equals(other.identifierPK))) {
return false;
}
return true;
}
@Override
public String toString() {
return "org.inbio.ara.persistence.taxonomy.Identifier[identifierPK=" + identifierPK + "]";
}
}
|
package com.sinodynamic.hkgta.dao.crm;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.springframework.stereotype.Repository;
import com.sinodynamic.hkgta.dao.GenericDao;
import com.sinodynamic.hkgta.dto.crm.CorporateMemberDto;
import com.sinodynamic.hkgta.dto.crm.CorporateProfileDto;
import com.sinodynamic.hkgta.entity.crm.CorporateProfile;
import com.sinodynamic.hkgta.util.constant.Constant;
import com.sinodynamic.hkgta.util.pagination.ListPage;
import com.sinodynamic.hkgta.util.pagination.ListPage.OrderType;
@Repository
public class CorporateProfileDaoImpl extends GenericDao<CorporateProfile>
implements CorporateProfileDao {
private Logger logger = Logger.getLogger(CorporateProfileDaoImpl.class);
public Serializable saveCorporateProf(CorporateProfile corporateProfile) {
return save(corporateProfile);
}
public boolean updateCorporateProf(CorporateProfile corporateProfile) throws HibernateException{
return update(corporateProfile);
}
public CorporateProfile getByCorporateId(Long corporateId) {
String hqlstr = "from CorporateProfile where corporateId = ?";
List<Serializable> listParam = new ArrayList<Serializable>();
listParam.add(corporateId);
return (CorporateProfile) getUniqueByHql(hqlstr, listParam);
}
/**
* Method to check if the typed br_No exists or not for register
* @param brNo The business register number
* @return false if exists, true if not exists
*/
public boolean checkAvailableBRNo(String brNo) {
String hqlstr = " from CorporateProfile where brNo = ? ";
List<Serializable> listParam = new ArrayList<Serializable>();
listParam.add(brNo);
CorporateProfile corpProf = (CorporateProfile) getUniqueByHql(hqlstr,listParam);
if (corpProf != null)
return false;
return true;
}
/**
* Method to check if the typed company name exists or not for register
* @param companyName: The company name
* @return false if exists, true if not exists
*/
public boolean checkAvailableCompanyName(String companyName) {
String hqlstr = " from CorporateProfile c where c.companyName = ? ";
List<Serializable> listParam = new ArrayList<Serializable>();
listParam.add(companyName);
CorporateProfile corpProf = (CorporateProfile) getUniqueByHql(hqlstr,listParam);
if (corpProf != null)
return false;
return true;
}
/**
* Method to check if the typed company name exists or not for update
* (The current corporateId is ignored)
* @param comanyName
* @param corporateId
* @return false if exists, true if not exists
*/
public boolean checkAvailableCompanyName(String companyName, Long corporateId){
String hqlstr = " from CorporateProfile c where c.companyName = ? ";
List<Serializable> listParam = new ArrayList<Serializable>();
listParam.add(companyName);
CorporateProfile corpProf = (CorporateProfile) getUniqueByHql(hqlstr,listParam);
if(corpProf!=null){//This brNo exists
if(corpProf.getCorporateId().equals(corporateId)){
return true;
}
return false;
}
return true;
}
/**
* Method to check if the typed br_No exists or not for update
* (The current corporateId is ignored)
* @param brNo
* @param corporateId
* @return false if exists, true if not exists
*/
public boolean checkAvailableBrNo(String brNo, Long corporateId){
String hqlstr = " from CorporateProfile where brNo = ? ";
List<Serializable> listParam = new ArrayList<Serializable>();
listParam.add(brNo);
CorporateProfile corpProf = (CorporateProfile) getUniqueByHql(hqlstr,listParam);
if(corpProf!=null){//This brNo exists
if(corpProf.getCorporateId().equals(corporateId)){
return true;
}
return false;
}
return true;
}
public ListPage<CorporateProfile> getCorpoateProfileListOld(
ListPage<CorporateProfile> page, CorporateProfileDto dto,String status) {
StringBuilder hql = new StringBuilder(" select\n" +
" corporate_profile.corporate_id as corporateId,\n" +
" corporate_profile.company_name as companyName,\n" +
" service_plan.plan_name as planName,\n" +
" service_plan.plan_no as servicePlanNo,\n" +
" corporate_profile.create_date as createDate,\n" +
" um.nickname as followByStaff,\n" +
" corporate_acc.status as status,\n" +
" corporate_acc.contract_ref_no as contractRefNo\n," +
" corporate_acc.acc_no as accNo\n" +
" from\n" +
" corporate_profile corporate_profile,\n" +
" service_plan service_plan ,\n" +
" corporate_service_subscribe corporates2_,\n" +
" (select csa.corporate_id as corporate_id,max(csa.acc_no) as acc_no from corporate_service_acc csa GROUP BY csa.corporate_id) corporate_alias, \n" +
" corporate_service_acc corporate_acc\n" +
" left join user_master um on um.user_id = corporate_acc.follow_by_staff \n"+
" where\n" +
" corporate_profile.corporate_id=corporate_acc.corporate_id \n" +
" and corporate_acc.acc_no=corporates2_.acc_no \n" +
" and service_plan.plan_no=corporates2_.service_plan_no\n" +
" and corporate_acc.acc_no = corporate_alias.acc_no ");
String countHql=null;
List<Serializable> param = new ArrayList<Serializable>();
if(Constant.General_Status_ACT.equalsIgnoreCase(status)||Constant.General_Status_NACT.equalsIgnoreCase(status)||Constant.General_Status_EXP.equalsIgnoreCase(status)){
hql.append("and corporate_acc.status = ? ");
param.add(status);
if(!StringUtils.isBlank(page.getCondition())){
String condition = " and "+page.getCondition();
hql.append(condition);
}
countHql = " SELECT count(corporate_profile.corporate_id) " +hql.substring(hql.indexOf("from"));
return listBySqlDto(page, countHql, hql.toString(), param, dto);
}
if(!StringUtils.isBlank(page.getCondition())){
String condition = " and "+page.getCondition();
hql.append(condition);
}
countHql = " SELECT count(corporate_profile.corporate_id) " +hql.substring(hql.indexOf("from"));
return listBySqlDto(page, countHql, hql.toString(), null, dto);
}
public ListPage<CorporateProfile> getCorpoateProfileList(ListPage<CorporateProfile> page) {
String sql = new String("SELECT\n" +
" corporateProfile.corporate_id AS corporateId,\n" +
" corporateProfile.company_name AS companyName,\n" +
" CONCAT_WS(' ',corporateProfile.contact_person_firstname,contact_person_lastname) AS followByStaff,\n" +
" (\n" +
" SELECT\n" +
" count(1)\n" +
" FROM\n" +
" corporate_member corporateMember,\n" +
" customer_service_acc customerServiceAcc\n" +
" WHERE\n" +
" corporateMember.corporate_id = corporateProfile.corporate_id\n" +
" AND corporateMember.customer_id = customerServiceAcc.customer_id\n" +
" AND date_format(now(), '%Y-%m-%d') BETWEEN customerServiceAcc.effective_date\n" +
" AND customerServiceAcc.expiry_date\n" +
" AND customerServiceAcc.status = 'ACT'\n" +
" AND corporateMember.status = 'ACT'\n" +
" AND customerServiceAcc.acc_cat = 'COP'\n" +
" ) AS noOfActiveMember,\n" +
" acc.total_credit_limit AS creditLimit\n" +
"FROM\n" +
" corporate_profile corporateProfile,\n" +
" corporate_service_acc acc\n" +
"WHERE\n" +
" acc.corporate_id = corporateProfile.corporate_id\n" +
"AND acc.acc_no = (\n" +
" SELECT\n" +
" max(accInternal.acc_no)\n" +
" FROM\n" +
" corporate_service_acc accInternal\n" +
" WHERE\n" +
" accInternal.corporate_id = corporateProfile.corporate_id\n" +
")");
if(!StringUtils.isBlank(page.getCondition())){
sql = "SELECT * FROM ( "+sql + ") result\n";
String condition = " WHERE "+page.getCondition();
sql = sql + (condition);
}
String countHql = " SELECT count(1) FROM ( " +sql + " ) countSql ";
return listBySqlDto(page, countHql, sql, null, new CorporateProfileDto());
}
public ListPage<CorporateProfile> getMemberList(
ListPage<CorporateProfile> page,String byAccount,String status,Long filterByCustomerId) {
List<Serializable> listParam = new ArrayList<Serializable>();
String sql = new String("SELECT\n" +
" corp.*, \n" +
" ccp.corporate_id AS corporateId,\n" +
" IFNULL(mlr.num_value, 'N/A') AS creditLimit,\n" +
" ccp.company_name AS companyName,\n" +
" CASE corp.memberType\n" +
" WHEN 'CPM' THEN\n" +
" (\n" +
" SELECT\n" +
" plan.plan_name\n" +
" FROM\n" +
" customer_service_acc inter,\n" +
" customer_service_subscribe sub,\n" +
" service_plan plan\n" +
" WHERE\n" +
" sub.acc_no = inter.acc_no\n" +
" AND plan.plan_no = sub.service_plan_no\n" +
" AND inter.customer_id = corp.customerId\n" +
" AND date_format(?, '%Y-%m-%d') >= inter.effective_date\n" +
" ORDER BY\n" +
" inter.expiry_date DESC\n" +
" LIMIT 0,\n" +
" 1\n" +
" )\n" +
" WHEN 'CDM' THEN\n" +
" (\n" +
" SELECT\n" +
" plan.plan_name\n" +
" FROM\n" +
" customer_service_acc inter,\n" +
" customer_service_subscribe sub,\n" +
" service_plan plan\n" +
" WHERE\n" +
" sub.acc_no = inter.acc_no\n" +
" AND plan.plan_no = sub.service_plan_no\n" +
" AND inter.customer_id = corp.superiorMemberId\n" +
" AND date_format(?, '%Y-%m-%d') >= inter.effective_date\n" +
" ORDER BY\n" +
" inter.expiry_date DESC\n" +
" LIMIT 0,\n" +
" 1\n" +
" )\n" +
" ELSE NULL\n" +
" END AS planName,\n" +
" CASE corp.memberType\n" +
" WHEN 'CPM' THEN\n" +
" (\n" +
" SELECT CONCAT_WS(' ',staffProfileCreateBy.given_name,staffProfileCreateBy.surname) FROM staff_profile staffProfileCreateBy WHERE staffProfileCreateBy.user_id = ce.sales_follow_by\n" +
" )\n" +
" WHEN 'CDM' THEN 'N/A'\n" +
" ELSE NULL\n" +
" END AS officer,\n" +
" \n" +
" CASE corp.memberType\n" +
" WHEN 'CPM' THEN\n" +
" (\n" +
" SELECT\n" +
" inter.effective_date as effectiveDate\n" +
" FROM\n" +
" customer_service_acc inter\n" +
" WHERE\n" +
" inter.customer_id = corp.customerId\n" +
" AND date_format(?, '%Y-%m-%d') >= inter.effective_date\n" +
" ORDER BY\n" +
" inter.expiry_date DESC\n" +
" limit 0,1\n" +
" )\n" +
" WHEN 'CDM' THEN \n" +
" (\n" +
" SELECT\n" +
" inter.effective_date as effectiveDate\n" +
" FROM\n" +
" customer_service_acc inter\n" +
" WHERE\n" +
" inter.customer_id = corp.superiorMemberId\n" +
" AND date_format(?, '%Y-%m-%d') >= inter.effective_date\n" +
" ORDER BY\n" +
" inter.expiry_date DESC\n" +
" limit 0,1\n" +
" )\n" +
" ELSE NULL\n" +
" END AS activationDate\n" +
"FROM\n" +
" (\n" +
" SELECT\n" +
" m.academy_no AS academyNo,\n" +
" m.member_type AS memberType,\n" +
" m.superior_member_id AS superiorMemberId,\n" +
" CONCAT(\n" +
" cp.salutation,\n" +
" ' ',\n" +
" cp.given_name,\n" +
" ' ',\n" +
" cp.surname\n" +
" ) AS memberName,\n" +
" m.status AS status,\n" +
" (case m.status when 'ACT' then 'Active' when 'NACT' then 'Inactive' end) as statusValue," +
" cp.customer_id AS customerId\n" +
" FROM\n" +
" member m,\n" +
" customer_profile cp\n" +
" WHERE\n" +
" cp.customer_id = m.customer_id\n" +
" ) corp\n" +
"LEFT JOIN member_limit_rule mlr ON mlr.customer_id = corp.customerId AND mlr.limit_type = 'CR' AND date_format( ? , '%Y-%m-%d') BETWEEN mlr.effective_date AND mlr.expiry_date\n" +
"LEFT JOIN customer_enrollment ce ON ce.customer_id = corp.customerId \n" +
"LEFT JOIN corporate_member cm ON corp.customerId = cm.customer_id OR corp.superiorMemberId = cm.customer_id\n" +
"LEFT JOIN corporate_profile ccp ON cm.corporate_id = ccp.corporate_id\n" +
"WHERE\n" +
"((corp.memberType = 'CPM'\n" +
" AND \n" +
" (ce.status = 'ANC' OR ce.status = 'CMP'))\n" +
"OR (corp.memberType = 'CDM'))\n");
Date currentDate = new Date();
listParam.add(currentDate);
listParam.add(currentDate);
listParam.add(currentDate);
listParam.add(currentDate);
listParam.add(currentDate);
if (!byAccount.equalsIgnoreCase("ALL")) {
sql = sql + " and ccp.corporate_id = ? ";
listParam.add(Long.parseLong(byAccount));
}
if(filterByCustomerId!=null){
sql = sql + " and corp.customerId = ? ";
listParam.add(filterByCustomerId);
}
String countSql = null;
if(Constant.General_Status_ACT.equalsIgnoreCase(status)||Constant.General_Status_NACT.equalsIgnoreCase(status)){
sql = sql + " and corp.`status` = ? ";
listParam.add(status);
}
if(!StringUtils.isBlank(page.getCondition())){
sql = "SELECT * FROM ( "+sql + ") resultAdvanceSearch\n";
String condition = " WHERE "+page.getCondition();
sql = sql + (condition);
}
List<ListPage<CorporateProfile>.OrderBy> orderCondition = page.getOrderByList();
StringBuilder orderBy = new StringBuilder("");
for(ListPage<CorporateProfile>.OrderBy sortByTemp:orderCondition ){
if(!StringUtils.isEmpty(sortByTemp.getProperty())){
if(!StringUtils.isEmpty(orderBy.toString())){
orderBy.append(",");
}else{
orderBy.append(" ORDER BY ");
}
if(OrderType.ASCENDING.equals(sortByTemp.getType())){
orderBy.append(sortByTemp.getProperty()).append(" asc ");
}else{
orderBy.append(sortByTemp.getProperty()).append(" desc ");
}
}
}
sql = sql + orderBy;
countSql = " SELECT count(1) from (" +sql+ ") countSql";
if(logger.isDebugEnabled())
{
logger.debug("sql : " + sql);
}
return listBySqlDto(page, countSql, sql, listParam, new CorporateMemberDto());
}
@Override
public List<CorporateProfile> getCorporateAccountDropList() {
String hql = " select cp.companyName as companyName, cp.corporateId as corporateId, cp.status as status from CorporateProfile cp order by cp.companyName asc";
// return getByHql(hql);
return getDtoByHql(hql, null, CorporateProfile.class);
}
public CorporateProfileDto getCorporateContactByCorporateIdAndContactType(Long corporateId,String contactType){
String sql = null;
List<Serializable> param = new ArrayList<Serializable>();
param.add(corporateId);
//Contact Type:INCHARGE, ADMINISTRATION, FINANCE
if("ADMINISTRATION".equalsIgnoreCase(contactType)||"FINANCE".equalsIgnoreCase(contactType)){
sql = "SELECT\n" +
" corpAdd.contact_email AS contactEmail,\n" +
" CONCAT_WS(\n" +
" ' ',\n" +
" corpAdd.contact_person_firstname,\n" +
" corpAdd.contact_person_lastname\n" +
" ) AS contactPersonFullName\n" +
"FROM\n" +
" corporate_addition_contact corpAdd\n" +
"WHERE\n" +
" corpAdd.corporate_id = ?\n" +
"AND corpAdd.contact_type = ?";
param.add(contactType);
}else{
sql = "SELECT\n" +
" corp.contact_email AS contactEmail,\n" +
" CONCAT_WS(\n" +
" ' ',\n" +
" corp.contact_person_firstname,\n" +
" corp.contact_person_lastname\n" +
" ) AS contactPersonFullName\n" +
"FROM\n" +
" corporate_profile corp\n" +
"WHERE\n" +
" corp.corporate_id = ?";
}
List<CorporateProfileDto> result = getDtoBySql(sql, param, CorporateProfileDto.class);
if(result!=null&&result.size()>0){
return result.get(0);
}else{
return null;
}
}
}
|
package com.hui;
/**
* @author hui
* @16:59 2019/8/25
*/
public class HelloTest3 {
}
|
package com.legaoyi.client.messagebody.decoder;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Component;
import com.legaoyi.client.down.messagebody.Tjsatl_2017_8103_MessageBody;
import com.legaoyi.protocol.exception.IllegalMessageException;
import com.legaoyi.protocol.message.MessageBody;
import com.legaoyi.protocol.message.decoder.MessageBodyDecoder;
import com.legaoyi.protocol.util.ByteUtils;
/**
*
* @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a>
* @version 1.0.0
* @since 2018-08-07
*/
@Component(MessageBodyDecoder.MESSAGE_BODY_DECODER_BEAN_PREFIX + "8103_tjsatl" + MessageBodyDecoder.MESSAGE_BODY_DECODER_BEAN_SUFFIX)
public class Tjsatl_2017_8103_MessageBodyDecoder implements MessageBodyDecoder {
@Override
public MessageBody decode(byte[] messageBody) throws IllegalMessageException {
Tjsatl_2017_8103_MessageBody body = new Tjsatl_2017_8103_MessageBody();
try {
int offset = 0;
int count = ByteUtils.byte2int(messageBody[offset++]);
Map<String, String> paramList = new HashMap<String, String>();
for (int i = 0; i < count; i++) {
byte[] arr = new byte[4];
System.arraycopy(messageBody, offset, arr, 0, arr.length);
String id = ByteUtils.bytes2hex(arr);
offset += arr.length;
int length = ByteUtils.byte2int(messageBody[offset++]);
arr = new byte[length];
System.arraycopy(messageBody, offset, arr, 0, arr.length);
offset += arr.length;
paramList.put(id, ByteUtils.bytes2hex(arr));
}
body.setParamList(paramList);
} catch (Exception e) {
throw new IllegalMessageException(e);
}
return body;
}
}
|
package com.love.step.service.impl;
import com.love.step.dto.AuthDTO;
import com.love.step.dto.UserDTO;
import com.love.step.mapper.AuthMapper;
import com.love.step.mapper.UserMapper;
import com.love.step.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Autowired
private AuthMapper authMapper;
@Override
public List<UserDTO> getUserList() {
return userMapper.getUserList();
}
@Override
public UserDTO getUserInfoByOpenid(String openid) {
return userMapper.getUserByOpenId(openid);
}
@Override
public Map<String,Object> addUserInfo(UserDTO userDTO) {
Map<String,Object> resultMap = null;
if(null != userDTO && !StringUtils.isEmpty(userDTO.getOpenid())){
UserDTO openIdUser = userMapper.getUserByOpenId(userDTO.getOpenid());
if(null != openIdUser){
resultMap = new HashMap<>();
resultMap.put("isAuth",openIdUser.getIsAuth());
resultMap.put("isRun",openIdUser.getIsRun());
resultMap.put("isAuthUser",openIdUser.getIsAuthUser());
return resultMap;
}
if(userMapper.insertUserInfo(userDTO) >= 1){
resultMap = new HashMap<>();
resultMap.put("isAuth",0);
resultMap.put("isRun",0);
resultMap.put("isAuthUser",0);
return resultMap;
}
}
return resultMap;
}
@Override
public boolean updateUserInfo(UserDTO userDTO) {
return userMapper.updateUserInfo(userDTO) > 0;
}
@Override
@Transactional
public boolean addAuth(String openid,String name,String mobile) {
UserDTO userDTO = userMapper.getUserByOpenId(openid);
if(null != userDTO){
if(userDTO.getIsAuthUser() == 0) {
AuthDTO authDTO = new AuthDTO();
authDTO.setMobile(mobile);
authDTO.setName(name);
authDTO.setUserId(userDTO.getId());
authDTO.setUserOpenid(openid);
if (authMapper.addAuth(authDTO) < 0) {
return false;
}
userDTO.setIsAuthUser(1);
if(userMapper.updateUserInfo(userDTO) < 0){
return false;
}
}
}
return true;
}
}
|
package org.digdata.swustoj.util;
import java.io.IOException;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import org.apache.log4j.Logger;
/**
*
* @author wwhhf
* @since 2016年6月12日
* @comment 发送邮件客户端
*/
public class MailUtil {
private static final String PROPTY_FILENAME = "mail.properties";
private static Logger logger = Logger.getLogger(MailUtil.class);
/**
*
* @author wwhhf
* @since 2016年6月12日
* @comment 发送邮件
* @param address
* @param subject
* @param mail
* @throws MessagingException
* @throws IOException
*/
public static boolean sendMail(final String address, final String subject,
final String content) {
new Thread(new Runnable() {
@Override
public void run() {
// 配置发送邮件的环境属性
try {
final Properties props = PropertiesUtil
.getProperties(PROPTY_FILENAME);
// 初始化发送邮件环境
MimeMessage message = init(props);
// 设置收件人
InternetAddress to = new InternetAddress(address);
message.setRecipient(RecipientType.TO, to);
// 设置抄送
InternetAddress cc = new InternetAddress(address);
message.setRecipient(RecipientType.CC, cc);
// 设置邮件标题
message.setSubject(subject);
// 设置邮件的内容体
message.setContent(content, "text/html;charset=UTF-8");
// 发送邮件
Transport.send(message);
} catch (IOException | MessagingException e) {
logger.error(e.getStackTrace());
}
}
}).start();
return true;
}
/**
*
* @author wwhhf
* @since 2016年6月14日
* @comment 群发邮件
* @param address
* @param subject
* @param content
* @throws Exception
*/
public static void sendMail(final String address[], final String subject,
final String content) throws Exception {
if (address.length <= 20) {
new Thread(new Runnable() {
@Override
public void run() {
// 配置发送邮件的环境属性
try {
final Properties props = PropertiesUtil
.getProperties(PROPTY_FILENAME);
// 初始化发送邮件环境
MimeMessage message = init(props);
InternetAddress to[] = new InternetAddress[address.length];
for (int i = 0, len = address.length; i < len; i++) {
to[i] = new InternetAddress(address[i]);
}
// 设置收件人
message.setRecipients(RecipientType.TO, to);
// 设置抄送
message.setRecipients(RecipientType.CC, to);
// 设置邮件标题
message.setSubject(subject);
// 设置邮件的内容体
message.setContent(content, "text/html;charset=UTF-8");
// 发送邮件
Transport.send(message);
} catch (IOException | MessagingException e) {
logger.error(e.getStackTrace());
}
}
}).start();
} else {
throw new Exception("address length is too long");
}
}
/**
* @author wwhhf
* @since 2016年6月12日
* @comment 初始化发送邮件环境
* @param props
* @return
* @throws AddressException
* @throws MessagingException
*/
private static MimeMessage init(final Properties props)
throws AddressException, MessagingException {
// 构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用环境属性和授权信息,创建邮件会话
Session mailSession = Session.getInstance(props, authenticator);
// 创建邮件消息
MimeMessage message = new MimeMessage(mailSession);
// 设置发件人
InternetAddress form = new InternetAddress(
props.getProperty("mail.user"));
message.setFrom(form);
return message;
}
}
|
package com.pwq.utils;
/**
* @Author:WenqiangPu
* @Description
* @Date:Created in 10:29 2017/9/28
* @Modified By:
*/
public class NumUtils {
/**
* @Author: WenqiangPu
* @Description: 将字符串型整数转化为int。
* @param str
* @return:
* @Date: 10:35 2017/9/28
*/
public static int parseInt(String str){
if(StringUtils.isEmpty(str)){
return 0;
}
boolean isNum = str.matches("[0-9]+");
if(isNum){
return Integer.parseInt(str);
}
return 0;
}
/**
* @Author: WenqiangPu
* @Description: 将字符串浮点型转化为浮点型
* @param str
* @return:
* @Date: 15:25 2017/9/28
*/
public static double parseDouble(String str){
if(StringUtils.isEmpty(str)){
return 0;
}
boolean isNum = str.matches("^[-\\+]?[0-9]+\\.?[0-9]*$");
if(isNum){
return Double.parseDouble(str);
}
return 0;
}
/**
* @Author: WenqiangPu
* @Description: 将字符串金额(单位元)转化为int类型以分为单位
* @param money
* @return:
* @Date: 15:34 2017/9/28
*/
public static int parseMoney(String money){
return (int)(NumUtils.parseDouble(money) * 100);
}
public static Double parseMoney2(String money){
return NumUtils.parseDouble(money) * 100;
}
}
|
package com.lab2;
import java.util.Scanner;
class SinhVien{
String hoTen;
double diem;
String hocLuc;
}
public class Lab2Bai6 {
public static class BaiTap6{
public static void main(String[] args) {
int n;
System.out.println("Nhập vào số sinh viên: ");
Scanner scanner = new Scanner(System.in);
n = Integer.parseInt(scanner.nextLine());
//Khoi tao mang
SinhVien[] sv = new SinhVien[n];
for (int i = 0; i<n; i++ ) {
System.out.println("Nhập vào sinh viên thứ: " + i);
sv[i] = new SinhVien();
System.out.println("Nhập họ tên: ");
sv[i].hoTen = scanner.nextLine();
System.out.println("Nhập điểm: ");
sv[i].diem = Double.parseDouble(scanner.nextLine());
if(sv[i].diem<5) {
sv[i].hocLuc = "Yếu";
} else if(5<=sv[i].diem && sv[i].diem<6.5) {
sv[i].hocLuc = "Trung Bình";
}
else if(6.5<=sv[i].diem && sv[i].diem<7.5) {
sv[i].hocLuc = "Khá";
}
else if(7.5<=sv[i].diem && sv[i].diem<9) {
sv[i].hocLuc = "Giỏi";
} else {
sv[i].hocLuc = "Xuất sắc";
}
}
System.out.println("Danh sách sinh viên vừa nhập: ");
for (int i = 0; i<sv.length; i++) {
System.out.println("Thứ tự số học sinh số" + i);
System.out.println("Họ và tên: " + sv[i].hoTen + "\n Điểm: "+ sv[i].diem + "\n Học lực: " + sv[i].hocLuc);
}
}
}
}
|
package com.citibank.ods.modules.client.ipdocprvt.functionality;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import org.apache.struts.action.ActionForm;
import com.citibank.ods.Globals;
import com.citibank.ods.Globals.FuncionalityFormatKeys;
import com.citibank.ods.common.functionality.ODSHistoryDetailFnc;
import com.citibank.ods.common.functionality.valueobject.BaseFncVO;
import com.citibank.ods.entity.pl.BaseTplDocTransferEntity;
import com.citibank.ods.entity.pl.BaseTplIpDocCallbackEntity;
import com.citibank.ods.entity.pl.BaseTplIpDocPrvtEntity;
import com.citibank.ods.entity.pl.TplDocTransferHistEntity;
import com.citibank.ods.entity.pl.TplIpDocCallbackHistEntity;
import com.citibank.ods.entity.pl.valueobject.TplIpDocPrvtHistEntityVO;
import com.citibank.ods.modules.client.ipdocprvt.form.BaseIpDocPrvtDetailForm;
import com.citibank.ods.modules.client.ipdocprvt.form.IpDocPrvtHistoryDetailForm;
import com.citibank.ods.modules.client.ipdocprvt.functionality.valueobject.BaseIpDocPrvtDetailFncVO;
import com.citibank.ods.modules.client.ipdocprvt.functionality.valueobject.IpDocPrvtHistoryDetailFncVO;
import com.citibank.ods.persistence.pl.dao.BaseTplIpDocPrvtDAO;
import com.citibank.ods.persistence.pl.dao.TplDocTransferHistDAO;
import com.citibank.ods.persistence.pl.dao.TplIpDocCallbackHistDAO;
import com.citibank.ods.persistence.pl.dao.TplIpDocPrvtHistDAO;
import com.citibank.ods.persistence.pl.dao.factory.ODSDAOFactory;
//
//©2002-2007 Accenture. All rights reserved.
//
/**
* [Class description]
*
* @see package com.citibank.ods.modules.client.ipdocprvt.functionality;
* @version 1.0
* @author gerson.a.rodrigues,Apr 12, 2007
*
* <PRE>
*
* <U>Updated by: </U> <U>Description: </U>
*
* </PRE>
*/
public class IpDocPrvtHistoryDetailFnc extends BaseIpDocPrvtDetailFnc implements
ODSHistoryDetailFnc
{
/*
* (non-Javadoc)
*
* @see com.citibank.ods.modules.client.ipdocprvt.functionality.BaseIpDocPrvtDetailFnc#getDAO()
*/
protected BaseTplIpDocPrvtDAO getDAO()
{
ODSDAOFactory odsDAOFactory = ODSDAOFactory.getInstance();
TplIpDocPrvtHistDAO tplIpDocPrvtHistDAO = odsDAOFactory.getTplIpDocPrvtHistDAO();
return tplIpDocPrvtHistDAO;
}
/*
* (non-Javadoc)
*
* @see com.citibank.ods.common.functionality.BaseFnc#createFncVO()
*/
public BaseFncVO createFncVO()
{
return new IpDocPrvtHistoryDetailFncVO();
}
/*
* (non-Javadoc)
*
* @see com.citibank.ods.common.functionality.ODSHistoryDetailFnc#loadForConsult(com.citibank.ods.common.functionality.valueobject.BaseFncVO)
*/
public void loadForConsult( BaseFncVO fncVO_ )
{
this.load( fncVO_ );
super.loadCustFullNameText( ( BaseIpDocPrvtDetailFncVO ) fncVO_ );
}
/**
*
*/
public void load( BaseFncVO fncVO_ )
{
super.load( fncVO_ );
IpDocPrvtHistoryDetailFncVO ipDocPrvtHistoryDetailFncVO = ( IpDocPrvtHistoryDetailFncVO ) fncVO_;
TplIpDocCallbackHistDAO ipDocCallbackHistDAO = ODSDAOFactory.getInstance().getTplIpDocCallbackHistDAO();
TplDocTransferHistDAO docTransferHistDAO = ODSDAOFactory.getInstance().getTplDocTransferHistDAO();
ipDocPrvtHistoryDetailFncVO.getBaseTplIpDocPrvtEntity().setBaseIpDocCallbackEntities(
ipDocCallbackHistDAO.findByPK(
ipDocPrvtHistoryDetailFncVO.getBaseTplDocTransferEntity().getData().getIpDocCode(),
ipDocPrvtHistoryDetailFncVO.getBaseTplDocTransferEntity().getData().getCustNbr() ) );
ipDocPrvtHistoryDetailFncVO.getBaseTplIpDocPrvtEntity().setBaseDocTransferEntities(
docTransferHistDAO.findByPK(
ipDocPrvtHistoryDetailFncVO.getBaseTplDocTransferEntity().getData().getIpDocCode(),
ipDocPrvtHistoryDetailFncVO.getBaseTplDocTransferEntity().getData().getCustNbr() ) );
}
public void updateFormFromFncVO( ActionForm form_, BaseFncVO fncVO_ )
{
super.updateFormFromFncVO( form_, fncVO_ );
BaseIpDocPrvtDetailFncVO baseIpDocPrvtDetailFncVO = ( BaseIpDocPrvtDetailFncVO ) fncVO_;
BaseIpDocPrvtDetailForm baseIpDocPrvtDetailForm = ( BaseIpDocPrvtDetailForm ) form_;
// Atualização do grid de Dados de Transferência
ArrayList domainsDocTransferCodeList = new ArrayList();
ArrayList domainsAgnBankCodeList = new ArrayList();
ArrayList domainsBrchCodeList = new ArrayList();
ArrayList domainsCurAcctCodeList = new ArrayList();
ArrayList domainsOwnDestAcctIndList = new ArrayList();
ArrayList domainsTxnTypeCodeList = new ArrayList();
BaseTplIpDocPrvtEntity baseTplIpDocPrvtEntity = baseIpDocPrvtDetailFncVO.getBaseTplIpDocPrvtEntity();
BaseTplDocTransferEntity baseTplDocTransferEntity = baseIpDocPrvtDetailFncVO.getBaseTplDocTransferEntity();
ArrayList ipDocTransferEntities = baseTplIpDocPrvtEntity.getBaseDocTransferEntities();
Iterator ipDocTransferEntitiesIt = ipDocTransferEntities.iterator();
while ( ipDocTransferEntitiesIt.hasNext() )
{
baseTplDocTransferEntity = ( TplDocTransferHistEntity ) ipDocTransferEntitiesIt.next();
if ( baseTplDocTransferEntity.getData().getAgnBankCode() != null )
{
domainsAgnBankCodeList.add( baseTplDocTransferEntity.getData().getAgnBankCode() );
}
else
{
domainsAgnBankCodeList.add( "" );
}
if ( baseTplDocTransferEntity.getData().getBrchCode() != null )
{
domainsBrchCodeList.add( baseTplDocTransferEntity.getData().getBrchCode() );
}
else
{
domainsBrchCodeList.add( "" );
}
if ( baseTplDocTransferEntity.getData().getCurAcctNbr() != null )
{
domainsCurAcctCodeList.add( baseTplDocTransferEntity.getData().getCurAcctNbr() );
}
else
{
domainsCurAcctCodeList.add( "" );
}
if ( baseTplDocTransferEntity.getData().getDocTransferCode() != null )
{
domainsDocTransferCodeList.add( baseTplDocTransferEntity.getData().getDocTransferCode() );
}
else
{
domainsDocTransferCodeList.add( "" );
}
if ( baseTplDocTransferEntity.getData().getOwnDestAcctInd() != null )
{
domainsOwnDestAcctIndList.add( baseTplDocTransferEntity.getData().getOwnDestAcctInd() );
}
else
{
domainsOwnDestAcctIndList.add( "" );
}
if ( baseTplDocTransferEntity.getData().getTxnTypeCode() != null )
{
domainsTxnTypeCodeList.add( baseTplDocTransferEntity.getData().getTxnTypeCode() );
}
else
{
domainsTxnTypeCodeList.add( "" );
}
}
String[] domainsDocTransferCodeArray = new String[ domainsDocTransferCodeList.size() ];
String[] domainsAgnBankCodeArray = new String[ domainsAgnBankCodeList.size() ];
String[] domainsAgnBankNameArray = new String[ domainsAgnBankCodeList.size() ];
String[] domainsBrchCodeArray = new String[ domainsBrchCodeList.size() ];
String[] domainsBrchNameArray = new String[ domainsBrchCodeList.size() ];
String[] domainsCurAcctCodeArray = new String[ domainsCurAcctCodeList.size() ];
String[] domainsOwnDestAcctIndArray = new String[ domainsOwnDestAcctIndList.size() ];
String[] domainsTxnTypeCodeArray = new String[ domainsTxnTypeCodeList.size() ];
//Fazendo a verredura de campos pelo atributo chave, atribuindo os
// valores
// aos vetores
for ( int i = 0; i < domainsDocTransferCodeList.size(); i++ )
{
domainsDocTransferCodeArray[ i ] = domainsDocTransferCodeList.get( i ).toString();
domainsCurAcctCodeArray[ i ] = domainsCurAcctCodeList.get( i ).toString();
domainsOwnDestAcctIndArray[ i ] = domainsOwnDestAcctIndList.get( i ).toString();
domainsTxnTypeCodeArray[ i ] = domainsTxnTypeCodeList.get( i ).toString();
domainsAgnBankCodeArray[ i ] = domainsAgnBankCodeList.get( i ).toString();
domainsAgnBankNameArray[ i ] = buildBankName( domainsAgnBankCodeList.get(
i ).toString() );
domainsBrchCodeArray[ i ] = domainsBrchCodeList.get( i ).toString();
domainsBrchNameArray[ i ] = buildBranchName(
domainsBrchCodeList.get( i ).toString(),
domainsAgnBankCodeList.get(
i ).toString() );
}
baseIpDocPrvtDetailForm.setDomainsDocTransferCode( domainsDocTransferCodeArray );
baseIpDocPrvtDetailForm.setDomainsAgnBankCode( domainsAgnBankCodeArray );
baseIpDocPrvtDetailForm.setDomainsAgnBankName( domainsAgnBankNameArray );
baseIpDocPrvtDetailForm.setDomainsBrchCode( domainsBrchCodeArray );
baseIpDocPrvtDetailForm.setDomainsBrchName( domainsBrchNameArray );
baseIpDocPrvtDetailForm.setDomainsCurAcctCode( domainsCurAcctCodeArray );
baseIpDocPrvtDetailForm.setDomainsOwnDestAcctInd( domainsOwnDestAcctIndArray );
baseIpDocPrvtDetailForm.setDomainsTxnTypeCode( domainsTxnTypeCodeArray );
baseIpDocPrvtDetailForm.setDocTransferCode( "" );
baseIpDocPrvtDetailForm.setAgnBankCode( "" );
baseIpDocPrvtDetailForm.setBrchCode( "" );
baseIpDocPrvtDetailForm.setCurAcctNbr( "" );
baseIpDocPrvtDetailForm.setOwnDestAcctInd( "" );
baseIpDocPrvtDetailForm.setTxnTypeCode( "" );
// Atualização do grid de Callback
ArrayList domainsFullNameTextList = new ArrayList();
ArrayList domainsCtcNbrList = new ArrayList();
BaseTplIpDocCallbackEntity baseTplIpDocCallbackEntity = baseIpDocPrvtDetailFncVO.getBaseTplIpDocCallbackEntity();
ArrayList ipDocCallbackEntities = baseTplIpDocPrvtEntity.getBaseIpDocCallbackEntities();
Iterator ipDocCallbackEntitiesIt = ipDocCallbackEntities.iterator();
while ( ipDocCallbackEntitiesIt.hasNext() )
{
baseTplIpDocCallbackEntity = ( TplIpDocCallbackHistEntity ) ipDocCallbackEntitiesIt.next();
if ( baseTplIpDocCallbackEntity.getData().getCtcNbr() != null )
{
domainsCtcNbrList.add( baseTplIpDocCallbackEntity.getData().getCtcNbr() );
}
else
{
domainsCtcNbrList.add( "" );
}
if ( baseTplIpDocCallbackEntity.getFullNameText() != null )
{
domainsFullNameTextList.add( baseTplIpDocCallbackEntity.getFullNameText() );
}
else
{
domainsFullNameTextList.add( "" );
}
}
String[] domainsCtcNbrArray = new String[ domainsCtcNbrList.size() ];
String[] domainsFullNameTextArray = new String[ domainsFullNameTextList.size() ];
String[] domainsPhoneArray = new String[ domainsCtcNbrList.size() ];
//Fazendo a verredura de campos pelo atributo chave, atribuindo os
// valores
// aos vetores
for ( int i = 0; i < domainsCtcNbrList.size(); i++ )
{
domainsCtcNbrArray[ i ] = domainsCtcNbrList.get( i ).toString();
String domainsArray[] = buildCtcName(new BigInteger(
domainsCtcNbrList.get(i ).toString() ),
baseTplIpDocCallbackEntity.getData().getCustNbr() );
domainsFullNameTextArray[ i ] = domainsArray[0];
domainsPhoneArray[i] = domainsArray[1];
}
baseIpDocPrvtDetailForm.setDomainsCtcNbr( domainsCtcNbrArray );
baseIpDocPrvtDetailForm.setDomainsFullNameText( domainsFullNameTextArray );
baseIpDocPrvtDetailForm.setCtcNbr( "" );
baseIpDocPrvtDetailForm.setFullNameText( "" );
IpDocPrvtHistoryDetailFncVO ipDocPrvtHistoryDetailFncVO = ( IpDocPrvtHistoryDetailFncVO ) fncVO_;
IpDocPrvtHistoryDetailForm ipDocPrvtHistoryDetailForm = ( IpDocPrvtHistoryDetailForm ) form_;
TplIpDocPrvtHistEntityVO tplIpDocPrvtHistEntityVO = ( TplIpDocPrvtHistEntityVO ) ipDocPrvtHistoryDetailFncVO.getBaseTplIpDocPrvtEntity().getData();
String lastUserId = ( ipDocPrvtHistoryDetailFncVO.getBaseTplIpDocPrvtEntity().getData().getLastUpdUserId() != null
&& ipDocPrvtHistoryDetailFncVO.getBaseTplIpDocPrvtEntity().getData().getLastUpdUserId().length() > 0
? ipDocPrvtHistoryDetailFncVO.getBaseTplIpDocPrvtEntity().getData().getLastUpdUserId()
: null );
String lastAuthUserId = ( tplIpDocPrvtHistEntityVO.getLastAuthUserId() != null
&& tplIpDocPrvtHistEntityVO.getLastAuthUserId().length() > 0
? tplIpDocPrvtHistEntityVO.getLastAuthUserId()
: null );
String lastUpdDate = ( ipDocPrvtHistoryDetailFncVO.getBaseTplIpDocPrvtEntity().getData().getLastUpdDate() != null
? formatDateTime( ipDocPrvtHistoryDetailFncVO.getBaseTplIpDocPrvtEntity().getData().getLastUpdDate() )
: null );
String lastAuthUpdDate = ( tplIpDocPrvtHistEntityVO.getLastAuthDate() != null
? formatDateTime( tplIpDocPrvtHistEntityVO.getLastAuthDate() )
: null );
String ipRefDate = ( tplIpDocPrvtHistEntityVO.getIpDocRefDate() != null
? formatDateTime( tplIpDocPrvtHistEntityVO.getIpDocRefDate() )
: null );
ipDocPrvtHistoryDetailForm.setLastAuthDate( lastAuthUpdDate );
ipDocPrvtHistoryDetailForm.setLastAuthUserId( lastAuthUserId );
ipDocPrvtHistoryDetailForm.setLastUpdDate( lastUpdDate );
ipDocPrvtHistoryDetailForm.setLastUpdUserId( lastUserId );
ipDocPrvtHistoryDetailForm.setIpDocRefDate( ipRefDate );
} /*
* (non-Javadoc)
* @see com.citibank.ods.modules.client.ipdocprvt.functionality.BaseIpDocPrvtDetailFnc#updateFncVOFromForm(org.apache.struts.action.ActionForm,
* com.citibank.ods.common.functionality.valueobject.BaseFncVO)
*/
public void updateFncVOFromForm( ActionForm form_, BaseFncVO fncVO_ )
{
super.updateFncVOFromForm( form_, fncVO_ );
IpDocPrvtHistoryDetailFncVO fncVO = ( IpDocPrvtHistoryDetailFncVO ) fncVO_;
IpDocPrvtHistoryDetailForm form = ( IpDocPrvtHistoryDetailForm ) form_;
String lastUpdUserId = ( form.getLastUpdUserId() != null
? form.getLastUpdUserId()
: null );
SimpleDateFormat formatter = new SimpleDateFormat(
FuncionalityFormatKeys.C_FORMAT_TIMESTAMP );
Date ipDocRefDate;
try
{
ipDocRefDate = ( form.getIpDocRefDate() != null
? formatter.parse( form.getIpDocRefDate() )
: null );
}
catch ( ParseException e_ )
{
ipDocRefDate = null;
}
fncVO.setLastUpdUserId( lastUpdUserId );
TplIpDocPrvtHistEntityVO entityVO = ( TplIpDocPrvtHistEntityVO ) fncVO.getBaseTplIpDocPrvtEntity().getData();
entityVO.setIpDocRefDate( ipDocRefDate );
}
private String formatDateTime( Date date_ )
{
DateFormat dateFormat = new SimpleDateFormat(
Globals.FuncionalityFormatKeys.C_FORMAT_PRESENTATION );
return dateFormat.format( date_ );
}
}
|
package com.t.client;
/**
* @author tb
* @date 2018/12/18 9:48
*/
public class JobClient {
}
|
package light.c;
import java.io.InputStream;
import java.io.Reader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
class Batchinterface
{
Process p;
String outp;
String errr;
Batchinterface(final String cmmnd) throws IOException {
this.p = Runtime.getRuntime().exec("cmd /c " + cmmnd);
this.outp = this.getoutput();
this.errr = this.geterr();
}
public String getoutput() throws IOException {
final InputStream stdout = this.p.getInputStream();
final BufferedReader brCleanUp = new BufferedReader(new InputStreamReader(stdout));
String input = "";
String line;
while ((line = brCleanUp.readLine()) != null) {
input = input + line + "\n";
}
brCleanUp.close();
return input;
}
public String geterr() throws IOException {
final InputStream stderr = this.p.getErrorStream();
final BufferedReader brCleanUp = new BufferedReader(new InputStreamReader(stderr));
String input = "";
String line;
while ((line = brCleanUp.readLine()) != null) {
input = input + line + "\n";
}
brCleanUp.close();
return input;
}
}
|
package com.mindtree.spring.dao;
import com.mindtree.spring.entity.AddTask;
public interface AddTaskDAO {
public void saveAddTaskData(AddTask ddTask);
public String getProjectNameById(String id);
}
|
package com.yoga.dao;
import java.util.List;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.yoga.entity.TbRoleLimit;
public class TbRoleLimitDAO extends BaseHibernateDAO {
private static final Logger log = LoggerFactory.getLogger(TbRoleLimitDAO.class);
// property constants
public void save(TbRoleLimit transientInstance) {
Session session = getSession();
Transaction beginTransaction = session.beginTransaction();
log.debug("saving TbRoleLimit instance");
try {
session.save(transientInstance);
beginTransaction.commit();
log.debug("save successful");
} catch (RuntimeException re) {
beginTransaction.rollback();
log.error("save failed", re);
throw re;
}
}
/**
* 根据角色编号删除对应信息
*
* @param roleId
*/
public void delete(int roleId) {
log.debug("deleting TbRoleLimit instance");
Session session = getSession();
Transaction beginTransaction = session.beginTransaction();
try {
//2015-5-11,写sql代码
SQLQuery createSQLQuery = session.createSQLQuery("DELETE * FROM tb_role_limit WHERE role_id=" + roleId);
createSQLQuery.executeUpdate();
beginTransaction.commit();
log.debug("delete successful");
} catch (RuntimeException re) {
beginTransaction.rollback();
log.error("delete failed", re);
throw re;
}finally{
session.close();
}
}
public void delete(TbRoleLimit persistentInstance) {
log.debug("deleting TbRoleLimit instance");
Session session = getSession();
Transaction beginTransaction = session.beginTransaction();
try {
session.delete(persistentInstance);
beginTransaction.commit();
log.debug("delete successful");
} catch (RuntimeException re) {
beginTransaction.rollback();
log.error("delete failed", re);
throw re;
}
}
public TbRoleLimit findById(java.lang.Integer id) {
log.debug("getting TbRoleLimit instance with id: " + id);
try {
TbRoleLimit instance = (TbRoleLimit) getSession().get("com.yoga.entity.TbRoleLimit", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List findByExample(TbRoleLimit instance) {
log.debug("finding TbRoleLimit instance by example");
try {
List results = getSession().createCriteria("com.yoga.entity.TbRoleLimit").add(Example.create(instance)).list();
log.debug("find by example successful, result size: " + results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
public List findByProperty(String propertyName, Object value) {
log.debug("finding TbRoleLimit instance with property: " + propertyName + ", value: " + value);
try {
String queryString = "from TbRoleLimit as model where model." + propertyName + "= ?";
Query queryObject = getSession().createQuery(queryString);
queryObject.setParameter(0, value);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}
public List findAll(int id) {
log.debug("finding all TbRoleLimit instances");
try {
String queryString = "from TbRoleLimit where tbRole.id= " + id;
Query queryObject = getSession().createQuery(queryString);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}
public TbRoleLimit merge(TbRoleLimit detachedInstance) {
log.debug("merging TbRoleLimit instance");
try {
TbRoleLimit result = (TbRoleLimit) getSession().merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public void attachDirty(TbRoleLimit instance) {
log.debug("attaching dirty TbRoleLimit instance");
try {
getSession().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void attachClean(TbRoleLimit instance) {
log.debug("attaching clean TbRoleLimit instance");
try {
getSession().buildLockRequest(LockOptions.NONE).lock(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
}
|
/*
###PROGRAMMKOPF###
Berechnung Zimmergröße
FS23
Marc Freytag
Version: 1
20121016
Berechnung der Quadratmeter zweier Längenwerte
*/
public class aslp1
{
// ###HAUPTFUNKTION###
public static void main(String[] args )
{
// ###DEKLARATIONSTEIL###
float zahl1 = 0f, zahl2 = 0f;
float quadratmeter = 0f;
// gibt Text auf Bildschirm aus
System.out.print("Bitte geben Sie die Länge des Raumes ein:");
// wartet auf Eingabe einer Zahl
zahl1 = Tastatur.liesFloat();
// gibt Text auf Bildschirm aus
System.out.print("Bitte geben Sie die Breite des Raumes ein:");
// wartet auf Eingabe einer Zahl
zahl2 = Tastatur.liesFloat();
// multipliziere zahl1 und zahl2 und speichere es in quadratmeter
quadratmeter = zahl1 * zahl2;
// gibt Text auf Bildschirm aus
System.out.print("Ergebnis der Berechnung lautet: \n");
// gibt die Ergebnisse untereinander aus
System.out.print("Länge (m): " + zahl1 + "\n");
System.out.print("Breite (m): " + zahl2 + "\n");
System.out.print("Das Zimmer hat " + quadratmeter + "qm" + "\n");
}
}
|
package PACKAGE_NAME;public class PercussionInstrument {
}
|
package egovframework.adm.cfg.aut.service.impl;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.annotation.Resource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;
import egovframework.adm.cfg.aut.controller.MenuAuthorityController;
import egovframework.adm.cfg.aut.dao.MenuAuthorityDAO;
import egovframework.adm.cfg.aut.service.MenuAuthorityService;
import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl;
@Service("menuAuthorityService")
public class MenuAuthorityServiceImpl extends EgovAbstractServiceImpl implements MenuAuthorityService{
/** log */
protected static final Log log = LogFactory.getLog(MenuAuthorityServiceImpl.class);
@Resource(name="menuAuthorityDAO")
private MenuAuthorityDAO menuAuthorityDAO;
public List selectListGadmin(Map<String, Object> commandMap) throws Exception{
return menuAuthorityDAO.selectListGadmin(commandMap);
}
public List selectMenuAuthList(Map<String, Object> commandMap) throws Exception{
return menuAuthorityDAO.selectMenuAuthList(commandMap);
}
public int menuAuthUpdate(Map<String, Object> commandMap) throws Exception{
int isOk = 1;
List list = menuAuthorityDAO.selectListGadmin(commandMap);
menuAuthorityDAO.menuAuthDelete(commandMap);
String[] vecMenu;
String[] vecMenuSubseq;
String[] vecGadmin;
for( int i=0; i<list.size(); i++ ){
Map m = (Map)list.get(i);
String gadmin = (String)m.get("gadmin");
vecMenu = (String[])commandMap.get("p_menu"+gadmin);
vecMenuSubseq = (String[])commandMap.get("p_menusubseq"+gadmin);
vecGadmin = (String[])commandMap.get("p_gadmin"+gadmin);
String[] param = new String[vecMenu.length];
for( int j=0; j<vecMenu.length; j++ ){
String strR = "";
String strW = "";
if( commandMap.get("p_"+gadmin+"R"+j) != null ) strR = (String)commandMap.get("p_"+gadmin+"R"+j);
if( commandMap.get("p_"+gadmin+"W"+j) != null ) strW = (String)commandMap.get("p_"+gadmin+"W"+j);
param[j] = vecMenu[j] + "@" + vecMenuSubseq[j] + "@" + vecGadmin[j] + "@" + strR+strW;
}
commandMap.put("param", param);
menuAuthorityDAO.menuAuthInsert(commandMap);
}
return isOk;
}
}
|
package com.crackdevelopers.goalnepal.Leagues;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.crackdevelopers.goalnepal.R;
import com.crackdevelopers.goalnepal.Volley.CacheRequest;
import com.crackdevelopers.goalnepal.Volley.VolleySingleton;
import com.github.rahatarmanahmed.cpv.CircularProgressView;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by trees on 8/24/15.
*/
public class LeagueFixtures extends Fragment
{
private static final String URL="http://www.goalnepal.com/json_fixtures_2015.php?tournament_id=";
private long TOURNAMENT_ID;
private static final String CLUB_A_NAME="clubA";
private static final String CLUB_B_NAME="clubB";
private static final String CLUB_A_SCORE="score_of_clubA";
private static final String CLUB_B_SCORE="score_of_clubB";
private static final String CLUB_A_ICON="clubA_icon";
private static final String CLUB_B_ICON="clubB_icon";
private static final String MATCH_DATE="match_date";
private static final String MATCH_TIME="match_time";
private static final String MATCH_STATUS="match_status";
private static final String MATCHES="matches";
private static final String TITLE="title";
private static final String MATCH_ID="id";
private static final String FIXTURES="fixtures";
private RecyclerView leagueFixtures;
private Context context;
private LeagueFixtureAdapter leagueFixtureAdapter;
private RequestQueue queue;
private CircularProgressView progressView;
@Override
public void onCreate(@Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TOURNAMENT_ID=LeagueActivity.TOURNAMENT_ID;
queue= VolleySingleton.getInstance().getQueue();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.league_fixture_fragment, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
context=getActivity();
leagueFixtures=(RecyclerView)getActivity().findViewById(R.id.fixture_table);
leagueFixtureAdapter=new LeagueFixtureAdapter(context);
leagueFixtures.setAdapter(leagueFixtureAdapter);
leagueFixtures.setLayoutManager(new LinearLayoutManager(context));
final StickyRecyclerHeadersDecoration decoration=new StickyRecyclerHeadersDecoration(leagueFixtureAdapter);
leagueFixtures.addItemDecoration(decoration);
progressView = (CircularProgressView)getActivity().findViewById(R.id.progress_view_fixture);
progressView.startAnimation();
///STICKY ADAPTER THAT MANAGES THE STICKY
leagueFixtureAdapter.registerAdapterDataObserver
(
new RecyclerView.AdapterDataObserver() {
@Override
public void onChanged() {
decoration.invalidateHeaders();
}
}
);
sendFixtureReuest();
}
private void sendFixtureReuest()
{
progressView.setVisibility(View.VISIBLE);
CacheRequest fixtureRequest=new CacheRequest(Request.Method.GET, URL+TOURNAMENT_ID,
new Response.Listener<NetworkResponse>()
{
@Override
public void onResponse(NetworkResponse response)
{
try
{
final String jsonResponseString=new String(response.data, HttpHeaderParser.parseCharset(response.headers));
JSONObject responseJson=new JSONObject(jsonResponseString);
leagueFixtureAdapter.setData(parseData(responseJson));
progressView.setVisibility(View.GONE);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
} catch (JSONException e)
{
e.printStackTrace();
}
}
}
,
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
}
});
fixtureRequest.setTag(this);
queue.add(fixtureRequest);
}
@Override
public void onStart()
{
super.onPause();
sendFixtureReuest();
}
@Override
public void onStop()
{
super.onResume();
queue.cancelAll(this);
}
private List<FixtureRow> parseData(JSONObject rootJson)
{
List<FixtureRow> tempList=new ArrayList<>();
if(rootJson!=null)
{
if(rootJson.length()!=0)
{
if(rootJson.has(FIXTURES))
{
try
{
JSONArray fixtures=rootJson.getJSONArray(FIXTURES);
for(int i=0;i<fixtures.length();i++)
{
JSONObject fixture=fixtures.getJSONObject(i);
JSONArray matches=null;
String title="";
if(fixture.has(TITLE)) title=fixture.getString(TITLE);
if(fixture.has(MATCHES))
{
matches=fixture.getJSONArray(MATCHES);
for(int j=0;j<matches.length();j++)
{
JSONObject match=matches.getJSONObject(j);
String club_a_name="", club_b_name="", club_a_score="-", club_b_score="-", club_a_icon="", club_b_icon="",
match_date="", match_time="", match_status=""; long match_id=-1;
if(match.has(CLUB_A_NAME)) club_a_name=match.getString(CLUB_A_NAME);
if(match.has(CLUB_B_NAME)) club_b_name=match.getString(CLUB_B_NAME);
if(match.has(CLUB_A_ICON)) club_a_icon=match.getString(CLUB_A_ICON);
if(match.has(CLUB_B_ICON)) club_b_icon=match.getString(CLUB_B_ICON);
if(match.has(MATCH_DATE)) match_date=match.getString(MATCH_DATE);
if(match.has(MATCH_TIME)) match_time=match.getString(MATCH_TIME);
if(match.has(MATCH_STATUS)) match_status=match.getString(MATCH_STATUS);
if(match.has(MATCH_ID)) match_id=match.getLong(MATCH_ID);
if(match_status.equals("Played"))
{
if(match.has(CLUB_A_SCORE)) club_a_score=match.getString(CLUB_A_SCORE);
if(match.has(CLUB_B_SCORE)) club_b_score=match.getString(CLUB_B_SCORE);
}
tempList.add(new FixtureRow(club_a_name, club_b_name, club_a_score, club_b_score,
club_a_icon, club_b_icon, match_date, match_time, title, match_id));
}
}
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
}
return tempList;
}
}
|
package consumers;
import gui.TalkToGui;
import org.apache.activemq.ActiveMQConnectionFactory;
import javax.jms.*;
import java.io.Serializable;
public abstract class CustomListener {
private final ActiveMQConnectionFactory connectionFactory;
private Session session;
private Connection connection;
private Destination topicDestination;
protected final TalkToGui talkToGui;
protected MessageConsumer messageConsumer;
public CustomListener(ActiveMQConnectionFactory connectionFactory, TalkToGui talkToGui) {
this.connectionFactory = connectionFactory;
this.talkToGui = talkToGui;
}
public void sendMessage(Serializable obj) throws JMSException{
// Create a MessageProducer from the session to the topic or queue
MessageProducer producer = session.createProducer(topicDestination);
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
ObjectMessage objectMessage = session.createObjectMessage(obj);
producer.send(objectMessage);
producer.close();
}
public void setupConnection(String topicName) throws JMSException {
// Creating a connection
connection = connectionFactory.createConnection();
connection.start();
// Creating a session
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
// Creates a topic, if the topic exists it will return it
topicDestination = session.createTopic(topicName);
// Create a message producer from the session to the topic or queue
messageConsumer = session.createConsumer(topicDestination);
}
}
|
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.util;
import java.util.Properties;
import org.junit.jupiter.api.Test;
import org.springframework.util.PropertyPlaceholderHelper.PlaceholderResolver;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
/**
* @author Rob Harrop
*/
class PropertyPlaceholderHelperTests {
private final PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper("${", "}");
@Test
void withProperties() {
String text = "foo=${foo}";
Properties props = new Properties();
props.setProperty("foo", "bar");
assertThat(this.helper.replacePlaceholders(text, props)).isEqualTo("foo=bar");
}
@Test
void withMultipleProperties() {
String text = "foo=${foo},bar=${bar}";
Properties props = new Properties();
props.setProperty("foo", "bar");
props.setProperty("bar", "baz");
assertThat(this.helper.replacePlaceholders(text, props)).isEqualTo("foo=bar,bar=baz");
}
@Test
void recurseInProperty() {
String text = "foo=${bar}";
Properties props = new Properties();
props.setProperty("bar", "${baz}");
props.setProperty("baz", "bar");
assertThat(this.helper.replacePlaceholders(text, props)).isEqualTo("foo=bar");
}
@Test
void recurseInPlaceholder() {
String text = "foo=${b${inner}}";
Properties props = new Properties();
props.setProperty("bar", "bar");
props.setProperty("inner", "ar");
assertThat(this.helper.replacePlaceholders(text, props)).isEqualTo("foo=bar");
text = "${top}";
props = new Properties();
props.setProperty("top", "${child}+${child}");
props.setProperty("child", "${${differentiator}.grandchild}");
props.setProperty("differentiator", "first");
props.setProperty("first.grandchild", "actualValue");
assertThat(this.helper.replacePlaceholders(text, props)).isEqualTo("actualValue+actualValue");
}
@Test
void withResolver() {
String text = "foo=${foo}";
PlaceholderResolver resolver = placeholderName -> "foo".equals(placeholderName) ? "bar" : null;
assertThat(this.helper.replacePlaceholders(text, resolver)).isEqualTo("foo=bar");
}
@Test
void unresolvedPlaceholderIsIgnored() {
String text = "foo=${foo},bar=${bar}";
Properties props = new Properties();
props.setProperty("foo", "bar");
assertThat(this.helper.replacePlaceholders(text, props)).isEqualTo("foo=bar,bar=${bar}");
}
@Test
void unresolvedPlaceholderAsError() {
String text = "foo=${foo},bar=${bar}";
Properties props = new Properties();
props.setProperty("foo", "bar");
PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper("${", "}", null, false);
assertThatIllegalArgumentException().isThrownBy(() ->
helper.replacePlaceholders(text, props));
}
}
|
package com.ai.platform.agent.util;
/***
* agent服务端向客户端发送指令列表
*
* @author Administrator
*
*/
public class AgentServerCommandConstant {
// 1期指令列表(以下都是Agent服务端通过Agent客户端操作)
// * 1.1、开启远端服务器会话指令(ssh)
// * 1.2、关闭远端服务端器(指定)会话指令
// * 1.3、在远端服务器上执行命令、脚本
// * 1.4、上传文件到远端服务器指定目录
/** 服务端向客户端发送开启ssh命令 服务端向客户端发送 */
public static final byte[] PACKAGE_TYPE_SSH_OPEN = { 4, 0 };
/** 服务端向客户端发送关闭ssh命令 服务端向客户端发送 */
public static final byte[] PACKAGE_TYPE_SSH_CLOSE = { 4, 1 };
/** 字符类型的命令数据包 服务端向客户端发送 */
public static final byte[] PACKAGE_TYPE_EXEC_COMMAND = { 2, 0 };
/** 文件的数据包 开始包 */
public static final byte[] PACKAGE_TYPE_FILE_OPEN = { 3, 0 };
/** 文件的数据包 数据包 */
public static final byte[] PACKAGE_TYPE_FILE_WRITE = { 3, 1 };
/** 文件的数据包 结束包 */
public static final byte[] PACKAGE_TYPE_FILE_CLOSE = { 3, 2 };
/** 一次性命令 */
public static final byte[] PACKAGE_TYPE_SIMP_COMMAND = { 5, 0 };
/** 简单传输文件命令 */
public static final byte[] PACKAGE_TYPE_SIMP_FILE_COMMAND = { 6, 0 };
}
|
package com.example.prog3.alkasaffollowup;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.example.prog3.alkasaffollowup.Adapters.InvoicesRecyclerAdapter;
import com.example.prog3.alkasaffollowup.Data.UrlPath;
import com.example.prog3.alkasaffollowup.Model.ProjInvoi.ProjectInvoice;
import com.example.prog3.alkasaffollowup.Services.ProjectsInterface;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ProjInvoicesFollowup extends AppCompatActivity {
private RecyclerView invoicesrecycler;
private String guid;
private int sn;
private String ref;
private ProgressBar mProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_proj_invoices_followup);
guid = getIntent().getExtras().getString("guid");
sn = getIntent().getExtras().getInt("sn");
ref = getIntent().getExtras().getString("ref");
invoicesrecycler=findViewById(R.id.invoicesrecycler);
mProgressBar=findViewById(R.id.progress_bar);
LinearLayoutManager lmgr=new LinearLayoutManager(this);
invoicesrecycler.setLayoutManager(lmgr);
getAllProjectInvoices();
}
private void getAllProjectInvoices() {
String url= UrlPath.path;
Retrofit.Builder builder=new Retrofit.Builder();
builder.baseUrl(url).addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
ProjectsInterface projectsInterface = retrofit.create(ProjectsInterface.class);
Call<List<ProjectInvoice>> projectInvoices = projectsInterface.getProjectInvoices(sn, guid);
projectInvoices.enqueue(new Callback<List<ProjectInvoice>>() {
@Override
public void onResponse(Call<List<ProjectInvoice>> call, Response<List<ProjectInvoice>> response) {
List<ProjectInvoice> invoices = response.body();
viewAllProjectInvoices(invoices);
}
@Override
public void onFailure(Call<List<ProjectInvoice>> call, Throwable t) {
Toast.makeText(ProjInvoicesFollowup.this,t.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
}
private void viewAllProjectInvoices(List<ProjectInvoice> invoices) {
InvoicesRecyclerAdapter adapter=new InvoicesRecyclerAdapter(ProjInvoicesFollowup.this,invoices,ref);
invoicesrecycler.setAdapter(adapter);
invoicesrecycler.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.GONE);
}
}
|
package com.needii.dashboard.model;
public class ShippersExtendFeeExtend {
private int id;
private int cityId;
private int districtId;
private String cityName;
private String startDayStr;
private String endDayStr;
private String dayApplyInWeek;
private String hourMinutesStart;
private String hourMinutesEnd;
private Float ratioShip;
private String groupDistrictName;
public ShippersExtendFeeExtend(){}
public ShippersExtendFeeExtend(ShippersExtendFee shippersExtendFee, String groupDistrictName) {
this.id = shippersExtendFee.getId();
this.cityName = shippersExtendFee.getCityName();
this.startDayStr = shippersExtendFee.getStartDayStr();
this.endDayStr = shippersExtendFee.getEndDayStr();
this.dayApplyInWeek = shippersExtendFee.getDayApplyInWeek();
this.hourMinutesStart = shippersExtendFee.getHourMinutesStart();
this.hourMinutesEnd = shippersExtendFee.getHourMinutesEnd();
this.ratioShip = shippersExtendFee.getRatioShip();
this.groupDistrictName = groupDistrictName;
this.cityId = shippersExtendFee.getCityId();
this.districtId = shippersExtendFee.getDistrictId();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getStartDayStr() {
return startDayStr;
}
public void setStartDayStr(String startDayStr) {
this.startDayStr = startDayStr;
}
public String getEndDayStr() {
return endDayStr;
}
public void setEndDayStr(String endDayStr) {
this.endDayStr = endDayStr;
}
public String getDayApplyInWeek() {
return dayApplyInWeek;
}
public void setDayApplyInWeek(String dayApplyInWeek) {
this.dayApplyInWeek = dayApplyInWeek;
}
public String getHourMinutesStart() {
return hourMinutesStart;
}
public void setHourMinutesStart(String hourMinutesStart) {
this.hourMinutesStart = hourMinutesStart;
}
public String getHourMinutesEnd() {
return hourMinutesEnd;
}
public void setHourMinutesEnd(String hourMinutesEnd) {
this.hourMinutesEnd = hourMinutesEnd;
}
public Float getRatioShip() {
return ratioShip;
}
public void setRatioShip(Float ratioShip) {
this.ratioShip = ratioShip;
}
public String getGroupDistrictName() {
return groupDistrictName;
}
public void setGroupDistrictName(String groupDistrictName) {
this.groupDistrictName = groupDistrictName;
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
public int getDistrictId() {
return districtId;
}
public void setDistrictId(int districtId) {
this.districtId = districtId;
}
}
|
/**
* @Title:MachineInfo.java
* @Package:com.git.cloud.resource.model.po
* @Description:TODO
* @author LINZI
* @date 2015-1-7 下午03:47:24
* @version V1.0
*/
package com.git.cloud.resource.model.po;
import com.git.cloud.common.model.base.BaseBO;
/**
* @ClassName:MachineInfo
* @Description:TODO
* @author LINZI
* @date 2015-1-7 下午03:47:24
*
*
*/
public class MachineInfoPo extends BaseBO {
private String dataCenter;
private String poolName;
private String cdpName;
private String clusterName;
private String hostName;
private String sn;
private String platForm;
private String virtualName;
private String cpu;
private String mem;
private String controlTime;
private String ips;
private String manufacturer;
private String model;
private String hostId;
private String status;
public String getHostId() {
return hostId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public void setHostId(String hostId) {
this.hostId = hostId;
}
public String getDataCenter() {
return dataCenter;
}
public void setDataCenter(String dataCenter) {
this.dataCenter = dataCenter;
}
public String getPoolName() {
return poolName;
}
public void setPoolName(String poolName) {
this.poolName = poolName;
}
public String getCdpName() {
return cdpName;
}
public void setCdpName(String cdpName) {
this.cdpName = cdpName;
}
public String getClusterName() {
return clusterName;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public String getSn() {
return sn;
}
public void setSn(String sn) {
this.sn = sn;
}
public String getPlatForm() {
return platForm;
}
public void setPlatForm(String platForm) {
this.platForm = platForm;
}
public String getVirtualName() {
return virtualName;
}
public void setVirtualName(String virtualName) {
this.virtualName = virtualName;
}
public String getCpu() {
return cpu;
}
public void setCpu(String cpu) {
this.cpu = cpu;
}
public String getMem() {
return mem;
}
public void setMem(String mem) {
this.mem = mem;
}
public String getControlTime() {
return controlTime;
}
public void setControlTime(String controlTime) {
this.controlTime = controlTime;
}
public String getIps() {
return ips;
}
public void setIps(String ips) {
this.ips = ips;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
/**
* @Fields serialVersionUID:long TODO
*/
private static final long serialVersionUID = 1L;
/* (non-Javadoc)
* <p>Title:getBizId</p>
* <p>Description:</p>
* @return
* @see com.git.cloud.common.model.base.BaseBO#getBizId()
*/
@Override
public String getBizId() {
// TODO Auto-generated method stub
return null;
}
}
|
package com.icic.loans.carloans.houseloans;
public class Calculations {
int a, b,c;
public Calculations(int a,int b)
{
super();
this.a=a;
this.b=b;
}
public void add()
{
c=a+b;
System.out.println("addition of two numbers" +c);
}
public static void main(String[] args) {
Calculations c=new Calculations(20,30);
c.add();
}
}
|
package com.LambdaExpressions;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Supplier;
public class assignment2 {
public static void main(String[] args)
{
List<Order> allOrders=OrderList.getOrders();
OrderList.printOrders(allOrders);
OrderPredicate predicatePrice=(Order o)->o.getPrice()>10000;
System.out.println("\n\n filtered list");
Consumer <List<Order>>c= (List<Order> x)->System.out.println(x);
List<Order> filteredOrders=filterOrders(allOrders,predicatePrice,c);
//OrderList.printOrders(filteredOrders);
}
public static List<Order> filterOrders(List<Order> orders, OrderPredicate predicate,Consumer <List<Order>>c) {
List<Order> filteredOrders = new ArrayList<Order>();
for(Order o: orders) {
if (predicate.test(o)) {
filteredOrders.add(o);
}
}
c.accept(filteredOrders);
return filteredOrders;
}
}
|
package com.t.client.domain;
/**
* @author tb
* @date 2018/12/18 9:50
*/
public class JobClientAppContext {
}
|
package leetCode;
import java.util.ArrayList;
import java.util.List;
/**
* Created by gengyu.bi on 2015/1/9.
*/
public class PopulatingNextRightPointersInEachNodeII {
public void connect(TreeLinkNode root) {
if (root == null)
return;
add(root);
connect(root.left);
connect(root.right);
}
private void add(TreeLinkNode node) {
List<TreeLinkNode> nodeList = new ArrayList<TreeLinkNode>();
while (node != null) {
if (node != null) {
if (node.left != null)
nodeList.add(node.left);
if (node.right != null)
nodeList.add(node.right);
}
node = node.next;
}
for (int i = 0; i < nodeList.size() - 1; i++) {
nodeList.get(i).next = nodeList.get(i + 1);
}
}
public static void main(String[] args) {
PopulatingNextRightPointersInEachNodeII populatingNextRightPointersInEachNodeII = new PopulatingNextRightPointersInEachNodeII();
TreeLinkNode t1 = new TreeLinkNode(1);
TreeLinkNode t2 = new TreeLinkNode(2);
TreeLinkNode t3 = new TreeLinkNode(3);
TreeLinkNode t4 = new TreeLinkNode(4);
TreeLinkNode t5 = new TreeLinkNode(5);
TreeLinkNode t6 = new TreeLinkNode(6);
TreeLinkNode t7 = new TreeLinkNode(7);
TreeLinkNode t8 = new TreeLinkNode(8);
t1.left = t2;
t1.right = t3;
t2.left = t4;
t2.right = t5;
t3.right = t6;
t4.left = t7;
t6.right = t8;
populatingNextRightPointersInEachNodeII.connect(t1);
System.out.println("Populating Next Right Pointers in Each Node II");
}
}
|
package download.service;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import common.util.HtmlCleaner;
public class CleanTamquocdiennghia {
// Đường dẫn thư mục chứa các file
private static final String ROOT_PATH = "/media/locke/data/literature/la quan trung - tam quoc dien nghia/part 1/";
/**
* Clean nội dung file
* @param filePath Đường dẫn file
* @return Xâu nội dung đã được clean
*/
private String clean(String filePath) throws Exception {
String content = getCleanHtmlFromFile(filePath);
// Bỏ các ký tự thừa
content = cleanCharacters(content);
Document doc = Jsoup.parseBodyFragment(content);
addCssClass(doc);
processImages(doc);
doc.outputSettings().syntax(Document.OutputSettings.Syntax.xml);
return doc.body().html();
}
private String getCleanHtmlFromFile(String filePath) throws Exception {
File file = new File(filePath);
Document doc = Jsoup.parse(file, "UTF-8");
HtmlCleaner htmlCleaner = new HtmlCleaner();
String content = (htmlCleaner.filterTextImageLink(doc.body()));
return content;
}
private String cleanCharacters(String content) {
content = content.replace("<p>Tam Quốc Diễn Nghĩa</p>", "");
content = content.replace("<p>Nguyên tác : La Quán Trung</p>", "");
content = content.replace("<p>Dịch giả : Phan Kế Bính</p>", "");
content = content.replace("<br><br></p>", "");
content = content.replace("<br></p>", "");
content = content.replace("<p><br><br>", "");
content = content.replace("<p><br>", "");
return content;
}
private void addCssClass(Document doc) throws Exception {
Elements elements = doc.body().children();
Element chapterNumberNode = null;
for (Element element : elements) {
if (element.nodeName().equals("p")) {
String text = element.text().trim();
if (isChapterNumberTag(text)) {
chapterNumberNode = element;
break;
}
}
}
if (chapterNumberNode != null) {
chapterNumberNode.addClass("chapter-number");
// 2 dòng tên tiêu đề tiếp theo
Element chapterTitle1 = chapterNumberNode.nextElementSibling();
chapterTitle1.addClass("chapter-title");
if (chapterTitle1.text().endsWith(".") || chapterTitle1.text().endsWith(";")) {
chapterTitle1.text(chapterTitle1.text().substring(0, chapterTitle1.text().length() - 1));
}
Element chapterTitle2 = chapterTitle1.nextElementSibling();
chapterTitle2.addClass("chapter-title");
if (chapterTitle2.text().endsWith(".") || chapterTitle2.text().endsWith(";")) {
chapterTitle2.text(chapterTitle2.text().substring(0, chapterTitle2.text().length() - 1));
}
// Comment nếu có ảnh
Element comment = chapterNumberNode.previousElementSibling();
if (comment.nodeName().equals("p")) {
comment.addClass("comment");
}
}
}
private boolean isChapterNumberTag(String textContent) {
String regex = "^Hồi \\d+$";
return textContent.matches(regex);
}
private void processImages(Document doc) {
Elements images = doc.getElementsByTag("img");
for (Element e : images) {
e.wrap("<p></p>");
String src = e.attr("src");
//System.out.println(src);
// Copy
// Tạo ánh xạ
}
}
/**
* Xử lý một chương.
* @param number Chỉ số chương
*/
public void process(int number) throws Exception {
// Thêm các chữ số 0 ở đầu
String fileName = String.valueOf(number + 1000).substring(1);
// Tên file đầu vào
String filePath = ROOT_PATH + fileName + ".html";
// Clean nội dung file đầu vào
String content = clean(filePath);
// Ghi ra file mới
writeFile("new-" + fileName, "Hồi " + number, content);
}
/**
* Ghi file mới.
* @param file Tên file
* @param title Tiêu đề
* @param content Nội dung
*/
private void writeFile(String file, String title, String content) throws IOException {
PrintWriter pw = new PrintWriter(new FileWriter(ROOT_PATH + file + ".html", false));
pw.append("<!DOCTYPE html>\n"
+ "<html>\n"
+ "<head>\n"
+ " <title>" + title + "</title>\n"
+ " <meta charset='UTF-8'/>\n"
+ " <link href='css/style.css' rel='stylesheet'/>\n" + "</head>\n"
+ "<body>\n"
+ " <article>\n"
+ content
+ " </article>\n"
+ "</body>\n"
+ "</html>\n");
pw.close();
}
/**
* Xử lý chính.
*/
@Test
public void testProcess() throws Exception {
CleanTamquocdiennghia obj = new CleanTamquocdiennghia();
int startChapter = 1;
int endChapter = 20;
for (int number = startChapter; number <= endChapter; number++) {
obj.process(number);
}
System.out.println("Finish");
}
}
|
package cn.test.singleton;
/**
* Created by xiaoni on 2019/1/16.
*/
public class ElvisSerializable {
//无论那种方法,反序列化时为了保证唯一,必需声明所有的实例都是瞬时(Transient)的
public static final ElvisSerializable INSTASNCE = new ElvisSerializable();
private ElvisSerializable(){}
public void leaveTheBuilding() {}
//readResolve method to preserver singleton property
private Object readResolve() {
//Return the one true Elvis and let the garbage collector
//take care of the Elvis impersonator
return INSTASNCE;
}
}
|
package com.tide.demo10;
public class Demo01Final {
public static void main(String[] args) {
Student stu=new Student();
stu.introduce();
}
}
|
package com.citibank.ods.modules.client.classcmplc.functionality;
import java.math.BigInteger;
import org.apache.struts.action.ActionForm;
import com.citibank.ods.common.functionality.BaseFnc;
import com.citibank.ods.common.functionality.valueobject.BaseFncVO;
import com.citibank.ods.common.util.ODSConstraintDecoder;
import com.citibank.ods.modules.client.classcmplc.form.BaseClassCmplcListForm;
import com.citibank.ods.modules.client.classcmplc.functionality.valueobject.BaseClassCmplcListFncVO;
//
//©2002-2007 Accenture. All rights reserved.
//
/**
* [Class description]
*
* @see package
* com.citibank.ods.modules.client.classcmplc.functionality.valueobject;
* @version 1.0
* @author gerson.a.rodrigues,Mar 13, 2007
*
* <PRE>
*
* <U>Updated by: </U> <U>Description: </U>
*
* </PRE>
*/
public abstract class BaseClassCmplcListFnc extends BaseFnc
{
/*
* (non-Javadoc)
* @see com.citibank.ods.common.functionality.BaseFnc#updateFncVOFromForm(org.apache.struts.action.ActionForm,
* com.citibank.ods.common.functionality.valueobject.BaseFncVO)
*/
public void updateFncVOFromForm( ActionForm form_, BaseFncVO fncVO_ )
{
// Faz cast para os tipos corretos
BaseClassCmplcListFncVO classCmplcListFncVO = ( BaseClassCmplcListFncVO ) fncVO_;
BaseClassCmplcListForm classCmplcListForm = ( BaseClassCmplcListForm ) form_;
// Atualiza os dados: Form -> FncVO
BigInteger classCmplcCode = ( classCmplcListForm.getClassCmplcCodeSrc() != null
&& classCmplcListForm.getClassCmplcCodeSrc().length() > 0
? new BigInteger(
classCmplcListForm.getClassCmplcCodeSrc() )
: null );
String classCmplcText = ( classCmplcListForm.getClassCmplcTextSrc() != null
&& classCmplcListForm.getClassCmplcTextSrc().length() > 0
? new String(
classCmplcListForm.getClassCmplcTextSrc() )
: null );
String sensInd = ( classCmplcListForm.getSensIndSrc() != null
&& classCmplcListForm.getSensIndSrc().length() > 0
? new String(
classCmplcListForm.getSensIndSrc() )
: null );
classCmplcListFncVO.setClassCmplcCodeSrc( classCmplcCode );
classCmplcListFncVO.setClassCmplcTextSrc( classCmplcText );
classCmplcListFncVO.setSensIndSrc( sensInd );
}
/*
* (non-Javadoc)
* @see com.citibank.ods.common.functionality.BaseFnc#updateFormFromFncVO(org.apache.struts.action.ActionForm,
* com.citibank.ods.common.functionality.valueobject.BaseFncVO)
*/
public void updateFormFromFncVO( ActionForm form_, BaseFncVO fncVO_ )
{
BaseClassCmplcListFncVO classCmplcListFncVO = ( BaseClassCmplcListFncVO ) fncVO_;
BaseClassCmplcListForm classCmplcListForm = ( BaseClassCmplcListForm ) form_;
classCmplcListForm.setSensIndDomain( classCmplcListFncVO.getSensIndDomain() );
classCmplcListForm.setResults( classCmplcListFncVO.getResults() );
}
/*
* Parametro BaseFncVO
*
* O metodo correga as irmformações iniciais da tela
*/
public void load( BaseFncVO fncVO_ )
{
BaseClassCmplcListFncVO classCmplcListFncVO = ( BaseClassCmplcListFncVO ) fncVO_;
loadSensIndDomain( classCmplcListFncVO );
classCmplcListFncVO.setResults( null );
classCmplcListFncVO.setClassCmplcCodeSrc( null );
classCmplcListFncVO.setClassCmplcTextSrc( null );
}
public void loadSensIndDomain( BaseClassCmplcListFncVO classCmplcListFncVO_ )
{
classCmplcListFncVO_.setSensIndDomain( ODSConstraintDecoder.decodeIndicador() );
}
}
|
package com.github.galimru.telegram.objects;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonTypeInfo(
use = JsonTypeInfo.Id.CLASS,
include = JsonTypeInfo.As.PROPERTY,
defaultImpl = ReplyKeyboardMarkup.class
)
public interface ReplyMarkup {
}
|
package maksplo.study.vectorsumm;
public class Vector {
Point vectorStart;
Point vectorFinish;
void multiply(int multiplier) {
vectorStart.multyPoint(multiplier);
vectorFinish.multyPoint(multiplier);
}
void summ(Vector vectorSum){
vectorStart.x = vectorStart.x + vectorSum.vectorStart.x;
vectorStart.y = vectorStart.y + vectorSum.vectorStart.y;
vectorFinish.x = vectorFinish.x + vectorSum.vectorFinish.x;
vectorFinish.y = vectorFinish.y + vectorSum.vectorFinish.y;
}
}
|
package rmi;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class Calculator extends UnicastRemoteObject implements MathInterface
{
public Calculator() throws RemoteException {
}
@Override
public int sum(int num1, int num2) {
return num1 + num2;
}
@Override
public int sub(int num1, int num2) {
return num1 - num2;
}
}
|
package com.ma.pluginframework.domain.event;
import android.os.Parcel;
import android.os.Parcelable;
public abstract class PluginEvent implements Parcelable {
/**
* 收到消息的QQ
*/
private long currentUin;
private String extra;
public PluginEvent(long currentUin, String extra) {
this.currentUin = currentUin;
this.extra = extra;
}
protected PluginEvent(Parcel in) {
currentUin = in.readLong();
extra = in.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(currentUin);
dest.writeString(extra);
}
@Override
public int describeContents() {
return 0;
}
// public static final Creator<PluginEvent> CREATOR = new Creator<PluginEvent>() {
// @Override
// public PluginEvent createFromParcel(Parcel in) {
// return new PluginEvent(in);
// }
//
// @Override
// public PluginEvent[] newArray(int size) {
// return new PluginEvent[size];
// }
// };
public long getCurrentUin() {
return currentUin;
}
public void setCurrentUin(long currentUin) {
this.currentUin = currentUin;
}
public String getExtra() {
return extra;
}
public void setExtra(String extra) {
this.extra = extra;
}
@Override
public String toString() {
return "PluginEvent{" +
"currentUin=" + currentUin +
", extra='" + extra + '\'' +
'}';
}
}
|
package suba.task.coding.Orders;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.text.DecimalFormat;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class OrdersApplicationTests {
DecimalFormat df2 = new DecimalFormat("0.00");
String load(String Uri){
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(Uri))
.build();
try {
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
return response.body();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
Double getordercost(String response) throws IOException {
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getFactory();
JsonParser parser = factory.createParser(response);
JsonNode actualObj = mapper.readTree(parser);
return actualObj.get("total_cost").asDouble();
}
// Task 1 checks
@Test
void AppleOranges() throws IOException {
String response = load("http://localhost:8080/neworder?Orange=67&Apple=23");
assertEquals("30.55",df2.format(getordercost(response)));
}
@Test
void Appleonly() throws IOException {
String response = load("http://localhost:8080/neworder?Apple=23");
assertEquals("13.80",df2.format(getordercost(response)));
}
@Test
void Orangesonly() throws IOException {
String response = load("http://localhost:8080/neworder?Orange=67");
assertEquals("16.75",df2.format(getordercost(response)));
}
@Test
void Invaildnumbers() throws IOException {
String response = load("http://localhost:8080/neworder?Orange=-7");
assertEquals("Invaild input",response);
}
@Test
void ZeroOrder() throws IOException {
String response = load("http://localhost:8080/neworder?Orange=0&Apple=0");
assertEquals("NO item in the order",response);
}
// Step 2 test:
@Test
void WithofferAppleeven() throws IOException {
String response = load("http://localhost:8080/neworderwithoffer?Apple=6");
assertEquals("1.80",df2.format(getordercost(response)));
}
@Test
void WithofferAppleodd() throws IOException {
String response = load("http://localhost:8080/neworderwithoffer?Apple=7");
assertEquals("2.40",df2.format(getordercost(response)));
}
@Test
void WithofferAppleSingle() throws IOException {
String response = load("http://localhost:8080/neworderwithoffer?Apple=1");
assertEquals("0.60",df2.format(getordercost(response)));
}
void WithofferAppleDouble() throws IOException {
String response = load("http://localhost:8080/neworderwithoffer?Apple=2");
assertEquals("0.60",df2.format(getordercost(response)));
}
@Test
void WithofferOrangesx3() throws IOException {
String response = load("http://localhost:8080/neworderwithoffer?Orange=9");
assertEquals("1.50",df2.format(getordercost(response)));
}
@Test
void WithofferOrangesx3plus1() throws IOException {
String response = load("http://localhost:8080/neworderwithoffer?Orange=10");
assertEquals("1.75",df2.format(getordercost(response)));
}
@Test
void WithofferOrangesx3minus1() throws IOException {
String response = load("http://localhost:8080/neworderwithoffer?Orange=8");
assertEquals("1.50",df2.format(getordercost(response)));
}
@Test
void WithofferOrangesx3Single() throws IOException {
String response = load("http://localhost:8080/neworderwithoffer?Orange=1");
assertEquals("0.25",df2.format(getordercost(response)));
}
@Test
void WithofferOrangesdouble() throws IOException {
String response = load("http://localhost:8080/neworderwithoffer?Orange=2");
assertEquals("0.50",df2.format(getordercost(response)));
}
@Test
void WithofferOrangestriple() throws IOException {
String response = load("http://localhost:8080/neworderwithoffer?Orange=3");
assertEquals("0.50",df2.format(getordercost(response)));
}
// Task 3 checks
@Test
void checkgetallorder() throws IOException {
String response = load("http://localhost:8080/getallorders");
assertNotEquals("[]",response);
}
@Test
void checkorderbyid() throws IOException {
String response = load("http://localhost:8080/neworderwithoffer?Orange=23"); //to add atleast one record
response = load("http://localhost:8080/getbyorderid?id=1");
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getFactory();
JsonParser parser = factory.createParser(response);
JsonNode actualObj = mapper.readTree(parser);
int orderno = actualObj.get("order_Number").asInt();
assertEquals(1,orderno);
}
@Test
void checkorderbyincorrectid() throws IOException {
String response = load("http://localhost:8080/getbyorderid?id=100000000");
assertEquals("No order exists with that order id",response);
}
@Test
void contextLoads() {
}
}
|
package fxKuntosali.test;
// Generated by ComTest BEGIN
import fxKuntosali.*;
import kuntosali.*;
import static org.junit.Assert.*;
import org.junit.*;
// Generated by ComTest END
/**
* Test class made by ComTest
* @version 2020.08.03 13:41:14 // Generated by ComTest
*
*/
@SuppressWarnings({ "all" })
public class HarkkaGUIControllerTest {
// Generated by ComTest BEGIN
/** testAsiakkuusLoppumassa345 */
@Test
public void testAsiakkuusLoppumassa345() { // HarkkaGUIController: 345
Kuntosali kuntosali = new Kuntosali();
Asiakas asiakas = new Asiakas();
Asiakas asiakas1 = new Asiakas();
Asiakas asiakas2 = new Asiakas();
asiakas1.parse("5|Kari Taalasmaa|0402470506|Kahvakuulantie 7|56700|Kangasala|kari.taalasmaa@hotmail.com|2018-02-23|2020-11-24");
asiakas.parse("6|Seppo Taalasmaa|0405330207|Kalliokuja 21|56700|Helsinki|seppo.ukko@hotmail.com|2017-12-01|2020-06-01");
asiakas2.parse("2|Koira Ukko|0123456789|Koirakuja 7|63700|Koirakyla|koiruli@koiramail.com|1998-06-21|2020-08-05");
assertEquals("From: HarkkaGUIController line: 355", -63, kuntosali.asiakkuusLoppumassa(asiakas));
assertEquals("From: HarkkaGUIController line: 356", 113, kuntosali.asiakkuusLoppumassa(asiakas1));
assertEquals("From: HarkkaGUIController line: 357", 2, kuntosali.asiakkuusLoppumassa(asiakas2));
} // Generated by ComTest END
}
|
package com.wwings.iau;
import java.io.File;
import java.util.*;
import java.util.concurrent.CompletionException;
import org.hyperledger.fabric.protos.common.Configtx;
import org.hyperledger.fabric.sdk.*;
import org.hyperledger.fabric.sdk.security.CryptoSuite;
import org.hyperledger.fabric.sdk.testutils.TestConfig;
import org.hyperledger.fabric.sdkintegration.SampleOrg;
import org.hyperledger.fabric.sdkintegration.SampleStore;
import org.hyperledger.fabric.sdkintegration.SampleUser;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static java.lang.String.format;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.hyperledger.fabric.sdk.Channel.PeerOptions.createPeerOptions;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestfabricdemoApplicationTests {
private static final TestConfig testConfig = TestConfig.getConfig();
private static final int DEPLOYWAITTIME = testConfig.getDeployWaitTime();
private static final boolean IS_FABRIC_V10 = testConfig.isRunningAgainstFabric10();
private static final String TEST_ADMIN_NAME = "admin";
private static final String TESTUSER_1_NAME = "user1";
private static final String TEST_FIXTURES_PATH = "src/test/fixture";
private static final String FOO_CHANNEL_NAME = "foo";
private static final String BAR_CHANNEL_NAME = "bar";
//private final TestConfigHelper configHelper = new TestConfigHelper();
String testTxID = null; // save the CC invoke TxID and use in queries
SampleStore sampleStore;
private Collection<SampleOrg> testSampleOrgs;
String testName = "End2endAndBackAgainIT";
String CHAIN_CODE_FILEPATH = "sdkintegration/gocc/sample_11";
String CHAIN_CODE_NAME = "example_cc_go";
String CHAIN_CODE_PATH = "github.com/example_cc";
String CHAIN_CODE_VERSION_11 = "11";
String CHAIN_CODE_VERSION = "1";
TransactionRequest.Type CHAIN_CODE_LANG = TransactionRequest.Type.GO_LANG;
ChaincodeID chaincodeID = ChaincodeID.newBuilder().setName(CHAIN_CODE_NAME)
.setVersion(CHAIN_CODE_VERSION)
.setPath(CHAIN_CODE_PATH).build();
ChaincodeID chaincodeID_11 = ChaincodeID.newBuilder().setName(CHAIN_CODE_NAME)
.setVersion(CHAIN_CODE_VERSION_11)
.setPath(CHAIN_CODE_PATH).build();
File sampleStoreFile = new File(System.getProperty("java.io.tmpdir") + "/HFCSampletest.properties");
@Test
public void contextLoads() throws Exception {
testSampleOrgs = testConfig.getIntegrationTestsSampleOrgs();
sampleStore = new SampleStore(sampleStoreFile);
for (SampleOrg sampleOrg : testSampleOrgs) {
final String orgName = sampleOrg.getName();
SampleUser admin = sampleStore.getMember(TEST_ADMIN_NAME, orgName);
sampleOrg.setAdmin(admin); // The admin of this org.
SampleUser user = sampleStore.getMember(TESTUSER_1_NAME, orgName);
sampleOrg.addUser(user); //Remember user belongs to this Org
sampleOrg.setPeerAdmin(sampleStore.getMember(orgName + "Admin", orgName));
}
HFClient client = HFClient.createNewInstance();
client.setCryptoSuite(CryptoSuite.Factory.getCryptoSuite());
////////////////////////////
//Reconstruct and run the channels
SampleOrg sampleOrg = testConfig.getIntegrationTestsSampleOrg("peerOrg1");
Channel fooChannel = reconstructChannel(FOO_CHANNEL_NAME, client, sampleOrg);
// runChannel(client, fooChannel, sampleOrg, 0);
client.setUserContext(sampleOrg.getUser(TESTUSER_1_NAME));
queryChaincodeForExpectedValue(client, fooChannel, "" + (300 + 0), chaincodeID);
}
private void queryChaincodeForExpectedValue(HFClient client, Channel channel, final String expect, ChaincodeID chaincodeID) {
//out("Now query chaincode %s on channel %s for the value of b expecting to see: %s", chaincodeID, channel.getName(), expect);
QueryByChaincodeRequest queryByChaincodeRequest = client.newQueryProposalRequest();
queryByChaincodeRequest.setArgs("b".getBytes(UTF_8)); // test using bytes as args. End2end uses Strings.
queryByChaincodeRequest.setFcn("query");
queryByChaincodeRequest.setChaincodeID(chaincodeID);
Collection<ProposalResponse> queryProposals;
try {
queryProposals = channel.queryByChaincode(queryByChaincodeRequest);
} catch (Exception e) {
throw new CompletionException(e);
}
for (ProposalResponse proposalResponse : queryProposals) {
if (!proposalResponse.isVerified() || proposalResponse.getStatus() != ChaincodeResponse.Status.SUCCESS) {
fail("Failed query proposal from peer " + proposalResponse.getPeer().getName() + " status: " + proposalResponse.getStatus() +
". Messages: " + proposalResponse.getMessage()
+ ". Was verified : " + proposalResponse.isVerified());
} else {
String payload = proposalResponse.getProposalResponse().getResponse().getPayload().toStringUtf8();
System.out.println("返回的价钱是"+payload);
//out("Query payload of b from peer %s returned %s", proposalResponse.getPeer().getName(), payload);
assertEquals(format("Failed compare on channel %s chaincode id %s expected value:'%s', but got:'%s'",
channel.getName(), chaincodeID, expect, payload), expect, payload);
}
}
}
private Channel reconstructChannel(String name, HFClient client, SampleOrg sampleOrg) throws Exception {
//out("Reconstructing %s channel", name);
client.setUserContext(sampleOrg.getUser(TESTUSER_1_NAME));
Channel newChannel;
if (BAR_CHANNEL_NAME.equals(name)) { // bar channel was stored in samplestore in End2endIT testcase.
/**
* sampleStore.getChannel uses {@link HFClient#deSerializeChannel(byte[])}
*/
newChannel = sampleStore.getChannel(client, name);
if (!IS_FABRIC_V10) {
}
assertEquals(testConfig.isFabricVersionAtOrAfter("1.3") ? 0 : 2, newChannel.getEventHubs().size());
//out("Retrieved channel %s from sample store.", name);
} else {
newChannel = client.newChannel(name);
for (String ordererName : sampleOrg.getOrdererNames()) {
newChannel.addOrderer(client.newOrderer(ordererName, sampleOrg.getOrdererLocation(ordererName),
testConfig.getOrdererProperties(ordererName)));
}
boolean everyOther = false;
for (String peerName : sampleOrg.getPeerNames()) {
String peerLocation = sampleOrg.getPeerLocation(peerName);
Properties peerProperties = testConfig.getPeerProperties(peerName);
Peer peer = client.newPeer(peerName, peerLocation, peerProperties);
final Channel.PeerOptions peerEventingOptions = // we have two peers on one use block on other use filtered
everyOther ?
createPeerOptions().registerEventsForBlocks().setPeerRoles(EnumSet.of(Peer.PeerRole.ENDORSING_PEER, Peer.PeerRole.LEDGER_QUERY,
Peer.PeerRole.CHAINCODE_QUERY, Peer.PeerRole.EVENT_SOURCE)) :
createPeerOptions().registerEventsForFilteredBlocks().setPeerRoles(EnumSet.of(Peer.PeerRole.ENDORSING_PEER,
Peer.PeerRole.LEDGER_QUERY, Peer.PeerRole.CHAINCODE_QUERY, Peer.PeerRole.EVENT_SOURCE));
newChannel.addPeer(peer, IS_FABRIC_V10 ?
createPeerOptions().setPeerRoles(EnumSet.of(Peer.PeerRole.ENDORSING_PEER, Peer.PeerRole.LEDGER_QUERY,
Peer.PeerRole.CHAINCODE_QUERY)) : peerEventingOptions);
everyOther = !everyOther;
}
//For testing mix it up. For v1.1 use just peer eventing service for foo channel.
if (IS_FABRIC_V10) {
for (String eventHubName : sampleOrg.getEventHubNames()) {
EventHub eventHub = client.newEventHub(eventHubName, sampleOrg.getEventHubLocation(eventHubName),
testConfig.getEventHubProperties(eventHubName));
newChannel.addEventHub(eventHub);
}
} else {
}
assertEquals(IS_FABRIC_V10 ? sampleOrg.getEventHubNames().size() : 0, newChannel.getEventHubs().size());
}
byte[] serializedChannelBytes = newChannel.serializeChannel();
//Just checks if channel can be serialized and deserialized .. otherwise this is just a waste :)
// Get channel back.
newChannel.shutdown(true);
newChannel = client.deSerializeChannel(serializedChannelBytes);
newChannel.initialize();
//Begin tests with de-serialized channel.
//Query the actual peer for which channels it belongs to and check it belongs to this channel
for (Peer peer : newChannel.getPeers()) {
Set<String> channels = client.queryChannels(peer);
if (!channels.contains(name)) {
throw new AssertionError(format("Peer %s does not appear to belong to channel %s", peer.getName(), name));
}
}
//Just see if we can get channelConfiguration. Not required for the rest of scenario but should work.
final byte[] channelConfigurationBytes = newChannel.getChannelConfigurationBytes();
Configtx.Config channelConfig = Configtx.Config.parseFrom(channelConfigurationBytes);
Configtx.ConfigGroup channelGroup = channelConfig.getChannelGroup();
Map<String, Configtx.ConfigGroup> groupsMap = channelGroup.getGroupsMap();
//Before return lets see if we have the chaincode on the peers that we expect from End2endIT
//And if they were instantiated too. this requires peer admin user
client.setUserContext(sampleOrg.getPeerAdmin());
client.setUserContext(sampleOrg.getUser(TESTUSER_1_NAME));
return newChannel;
}
}
|
package HibFiles;
// Generated Jun 15, 2016 6:41:39 PM by Hibernate Tools 4.3.1
/**
* RecipeHasIngredient generated by hbm2java
*/
public class RecipeHasIngredient implements java.io.Serializable {
private Integer idrecipeHasIngredient;
private Ingredient ingredient;
private Recipe recipe;
private Unit unit;
private Double quantity;
private Boolean mainIngredient;
public RecipeHasIngredient() {
}
public RecipeHasIngredient(Ingredient ingredient, Recipe recipe, Unit unit) {
this.ingredient = ingredient;
this.recipe = recipe;
this.unit = unit;
}
public RecipeHasIngredient(Ingredient ingredient, Recipe recipe, Unit unit, Double quantity, Boolean mainIngredient) {
this.ingredient = ingredient;
this.recipe = recipe;
this.unit = unit;
this.quantity = quantity;
this.mainIngredient = mainIngredient;
}
public Integer getIdrecipeHasIngredient() {
return this.idrecipeHasIngredient;
}
public void setIdrecipeHasIngredient(Integer idrecipeHasIngredient) {
this.idrecipeHasIngredient = idrecipeHasIngredient;
}
public Ingredient getIngredient() {
return this.ingredient;
}
public void setIngredient(Ingredient ingredient) {
this.ingredient = ingredient;
}
public Recipe getRecipe() {
return this.recipe;
}
public void setRecipe(Recipe recipe) {
this.recipe = recipe;
}
public Unit getUnit() {
return this.unit;
}
public void setUnit(Unit unit) {
this.unit = unit;
}
public Double getQuantity() {
return this.quantity;
}
public void setQuantity(Double quantity) {
this.quantity = quantity;
}
public Boolean getMainIngredient() {
return this.mainIngredient;
}
public void setMainIngredient(Boolean mainIngredient) {
this.mainIngredient = mainIngredient;
}
}
|
package com.xinhua.xqjf;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for renewalPaymentInputData complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="renewalPaymentInputData">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="cashDetailList" type="{http://ws.resultrenewalpayment.irenewalpaymentucc.exports.counterchagre.interfaces.cap.tunan.nci.com/}renewalPaymentInputInfo" maxOccurs="unbounded" minOccurs="0"/>
* <element name="fpPrintNoList" type="{http://ws.resultrenewalpayment.irenewalpaymentucc.exports.counterchagre.interfaces.cap.tunan.nci.com/}renewalPaymentInputFP" maxOccurs="unbounded" minOccurs="0"/>
* <element name="functionFlag" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "renewalPaymentInputData", propOrder = {
"cashDetailList",
"fpPrintNoList",
"functionFlag"
})
public class RenewalPaymentInputData {
@XmlElement(nillable = true)
protected List<RenewalPaymentInputInfo> cashDetailList;
@XmlElement(nillable = true)
protected List<RenewalPaymentInputFP> fpPrintNoList;
protected String functionFlag;
/**
* Gets the value of the cashDetailList property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the cashDetailList property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCashDetailList().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link RenewalPaymentInputInfo }
*
*
*/
public List<RenewalPaymentInputInfo> getCashDetailList() {
if (cashDetailList == null) {
cashDetailList = new ArrayList<RenewalPaymentInputInfo>();
}
return this.cashDetailList;
}
/**
* Gets the value of the fpPrintNoList property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the fpPrintNoList property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getFpPrintNoList().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link com.xinhua.xqjf.RenewalPaymentInputFP }
*
*
*/
public List<RenewalPaymentInputFP> getFpPrintNoList() {
if (fpPrintNoList == null) {
fpPrintNoList = new ArrayList<RenewalPaymentInputFP>();
}
return this.fpPrintNoList;
}
/**
* Gets the value of the functionFlag property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFunctionFlag() {
return functionFlag;
}
/**
* Sets the value of the functionFlag property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFunctionFlag(String value) {
this.functionFlag = value;
}
public void setCashDetailList(List<RenewalPaymentInputInfo> cashDetailList) {
this.cashDetailList = cashDetailList;
}
public void setFpPrintNoList(List<RenewalPaymentInputFP> fpPrintNoList) {
this.fpPrintNoList = fpPrintNoList;
}
}
|
package com.nbu.barker;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import java.io.StringReader;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
public class AccommodationPickedActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accommodation_picked);
int nTmp = 0;
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
if (extras.containsKey("id")) {
nTmp = extras.getInt("id");
}
}
if(nTmp <= 0)
{
returnToAccommodations("Accommodation could not be found");
}
final int nId = nTmp;
String sXML = " <Barker requestType=\"viewAccommodation\">\n" +
" <viewAccommodation>\n" +
" <id>" + nId + "</id>\n" +
" </viewAccommodation>\n" +
" </Barker>";
String sResponse = "";
try {
sResponse = Tools.sendRequest(sXML);
Log.println(Log.ERROR, "Response is: ", sResponse);
if (sResponse == "Error" || sResponse.isEmpty()) {
Toast.makeText(AccommodationPickedActivity.this, "Couldn't rate activity.Please try again later", Toast.LENGTH_SHORT).show();
}
Document pDoc = null;
DocumentBuilder pBuilder = null;
DocumentBuilderFactory pFactory = DocumentBuilderFactory.newInstance();
pBuilder = pFactory.newDocumentBuilder();
pDoc = pBuilder.parse(new InputSource(new StringReader(sResponse)));
XPathFactory pXpathFactory = XPathFactory.newInstance();
XPath pXpath = pXpathFactory.newXPath();
XPathExpression pExp = null;
pExp = pXpath.compile("Barker/statusCode");
double nTmpCode = (double) pExp.evaluate(pDoc, XPathConstants.NUMBER);
int nResponseCode = (int) nTmpCode;
if (nResponseCode == Constants.requestStatusToCode(Constants.RequestServerStatus.SUCCESS)) {
pExp = pXpath.compile("Barker/accommodation/name");
String sName = (String) pExp.evaluate(pDoc, XPathConstants.STRING);
pExp = pXpath.compile("Barker/accommodation/description");
String sDescription = (String) pExp.evaluate(pDoc, XPathConstants.STRING);
pExp = pXpath.compile("Barker/accommodation/user");
String sUser = (String) pExp.evaluate(pDoc, XPathConstants.STRING);
pExp = pXpath.compile("Barker/accommodation/rating");
String sRating = (String) pExp.evaluate(pDoc, XPathConstants.STRING);
if(sRating.length() > 3) sRating = sRating.substring(0,3);
pExp = pXpath.compile("Barker/accommodation/votedBy");
String sTmp = (String) pExp.evaluate(pDoc, XPathConstants.STRING);
sRating += "/" + sTmp;
TextView tvTitle = findViewById(R.id.tvAccommodationTitle);
TextView tvDescription = findViewById(R.id.tvAccommodationTopicDescription);
TextView tvVoted = findViewById(R.id.tvAccommodationTopicRate);
tvTitle.setText(sName);
tvDescription.setText(sDescription);
tvVoted.setText(sRating);
}
else if (nResponseCode == Constants.requestStatusToCode(Constants.RequestServerStatus.MISSING_ACCOMMODATION)) {
returnToAccommodations("Accommodation no longer exists");
}
else
{
returnToAccommodations("There was an internal error. Please try again later");
}
}
catch(Exception e)
{
e.printStackTrace();
}
final Spinner spAccommodationRate = (Spinner) findViewById(R.id.spAccommodationTopicRate);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.accommodation_rating, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spAccommodationRate.setAdapter(adapter);
Button bRate = findViewById(R.id.bAccommodationPickedRate);
bRate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String sXML = " <Barker requestType=\"rateAccommodation\">\n" +
" <rateAccommodation>\n" +
" <accommodationId>" + nId + "</accommodationId>\n" +
" <rate>" + spAccommodationRate.getSelectedItem() + "</rate>\n" +
" <userEmail>" + SessionParameters.getApplicationUser().getEmail() + "</userEmail>\n" +
" </rateAccommodation>\n" +
" </Barker>";
String sResponse = "";
try {
sResponse = Tools.sendRequest(sXML);
Log.println(Log.ERROR, "Response is: ", sResponse);
if (sResponse == "Error" || sResponse.isEmpty()) {
Toast.makeText(AccommodationPickedActivity.this, "Couldn't rate activity.Please try again later", Toast.LENGTH_SHORT).show();
}
Document pDoc = null;
DocumentBuilder pBuilder = null;
DocumentBuilderFactory pFactory = DocumentBuilderFactory.newInstance();
pBuilder = pFactory.newDocumentBuilder();
pDoc = pBuilder.parse(new InputSource(new StringReader(sResponse)));
XPathFactory pXpathFactory = XPathFactory.newInstance();
XPath pXpath = pXpathFactory.newXPath();
XPathExpression pExp = null;
pExp = pXpath.compile("Barker/statusCode");
double nTmp = (double) pExp.evaluate(pDoc, XPathConstants.NUMBER);
int nResponseCode = (int) nTmp;
if (nResponseCode == Constants.requestStatusToCode(Constants.RequestServerStatus.SUCCESS)) {
Toast.makeText(AccommodationPickedActivity.this, "Accommodation has been rated", Toast.LENGTH_SHORT).show();
Intent intent = getIntent();
finish();
startActivity(intent);
}
else if(nResponseCode == Constants.requestStatusToCode(Constants.RequestServerStatus.ACCOMMODATION_ALREADY_RATED))
{
Toast.makeText(AccommodationPickedActivity.this, "You have already rated this accommodation", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(AccommodationPickedActivity.this, "There was an error. Please try again", Toast.LENGTH_SHORT).show();
}
}
catch(Exception e)
{
Toast.makeText(AccommodationPickedActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
}
});
}
private void returnToAccommodations(String sMessage)
{
Intent pIntent = new Intent(AccommodationPickedActivity.this,AccommodationsActivity.class);
pIntent.putExtra("message", sMessage);
startActivity(pIntent);
}
}
|
package com.techboon.service;
import com.techboon.domain.CaseItem;
import com.techboon.domain.enumeration.Conclusion;
import com.techboon.repository.CaseItemRepository;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.criteria.*;
import java.time.LocalDate;
import java.util.List;
@Service
@Transactional
public class CaseItemService {
private final Logger log = LoggerFactory.getLogger(CaseItemService.class);
private final CaseItemRepository caseItemRepository;
public CaseItemService(CaseItemRepository caseItemRepository){
this.caseItemRepository = caseItemRepository;
}
public Page<CaseItem> findBySpecification(LocalDate fromDate, LocalDate toDate, String condition,
List<Long> orgIds,String conclusion, Pageable pageable) {
log.info(" findBySampleDates {},{},{},{},{} " , fromDate ,toDate, condition,orgIds, conclusion);
return caseItemRepository.findAll( new CaseItemSpecification(fromDate, toDate, condition, orgIds, conclusion), pageable);
}
private class CaseItemSpecification implements Specification<CaseItem> {
private String condition;
private LocalDate fromDate;
private LocalDate toDate;
private List<Long> orgIds;
private String conclusion;
public CaseItemSpecification(LocalDate fromDate, LocalDate toDate, String condition, List<Long> orgIds, String conclusion) {
this.condition = condition;
this.fromDate = fromDate;
this.toDate = toDate;
this.orgIds = orgIds;
this.conclusion = conclusion;
}
@Override
public Predicate toPredicate(Root<CaseItem> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
if ( StringUtils.isBlank(condition)
&& ( fromDate ==null)
&& (toDate ==null)
&& (orgIds ==null)
&& StringUtils.isBlank(conclusion)
){
return criteriaQuery.getRestriction();
}
Predicate predicate = null;
if ( !StringUtils.isBlank(condition) ){
Path<String> name = root.get("name");
Path<String> sampleFlowNumber = root.get("sampleFlowNumber");
Path<String> sn = root.get("sn");
Path<String> memo = root.get("memo");
Path<String> conclusion = root.get("conclusion");
Path<String> mainDoctor = root.get("mainDoctor");
Path<String> treatment = root.get("treatment");
Path<String> virus = root.get("virus");
predicate =
criteriaBuilder.or(criteriaBuilder.like(name, "%" + condition + "%"),
criteriaBuilder.like(sampleFlowNumber, "%" + condition + "%"),
criteriaBuilder.like(sn, "%" + condition + "%"),
criteriaBuilder.like(mainDoctor, "%" + condition + "%"),
criteriaBuilder.like(treatment, "%" + condition + "%"),
// criteriaBuilder.like(virus, "%" + condition + "%"),
criteriaBuilder.like(memo, "%" + condition + "%")
);
}
if (( fromDate !=null) || (toDate !=null)) {
Predicate p = criteriaBuilder.between(root.get("sampleDate"), fromDate, toDate);
predicate = (predicate==null) ? p : criteriaBuilder.and(predicate, p);
}
if (orgIds !=null){
Predicate p = root.get("organization").get("id").in(orgIds);
predicate = (predicate==null) ? p : criteriaBuilder.and(predicate, p);
}
if ( !StringUtils.isBlank(conclusion) ){
Predicate p = criteriaBuilder.equal(root.get("conclusion"), Conclusion.valueOf(conclusion));
predicate = (predicate==null) ? p : criteriaBuilder.and(predicate, p);
}
return predicate;
}
}
}
|
package com.metoo.view.web.tools;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.metoo.core.tools.CommUtil;
import com.metoo.foundation.domain.Navigation;
import com.metoo.foundation.service.IActivityService;
import com.metoo.foundation.service.IArticleService;
import com.metoo.foundation.service.IGoodsClassService;
import com.metoo.foundation.service.INavigationService;
import com.metoo.module.app.buyer.domain.Result;
/**
*
* <p>Title: NavViewTools.java</p>
* <p>Description:前台导航工具类,查询显示对应的导航信息 </p>
* <p>Copyright: Copyright (c) 2014</p>
* <p>Company: 沈阳网之商科技有限公司 www.koala.com</p>
* @author erikzhang
* @date 2014-8-25
* @version koala_b2b2c v2.0 2015版
*/
@Component
public class NavViewTools {
@Autowired
private INavigationService navService;
@Autowired
private IArticleService articleService;
@Autowired
private IActivityService activityService;
@Autowired
private IGoodsClassService goodsClassService;
Result result = null;
/**
* 查询页面导航
*
* @param position
* 导航位置,-1为顶部,0为中间,1为底部
* @param count
* 导航数目,查询导航数目,-1为查询所有
* @return
*/
public List<Navigation> queryNav(int location, int count) {
List<Navigation> navs = new ArrayList<Navigation>();
Map params = new HashMap();
params.put("display", true);
params.put("location", location);
params.put("type", "sparegoods");
navs = this.navService
.query("select obj from Navigation obj where obj.display=:display and obj.location=:location and obj.type!=:type order by obj.sequence asc",
params, 0, count);
return navs;
}
public void queryNav_api(HttpServletRequest request,
HttpServletResponse response,int location, int count) {
List<Navigation> navs = new ArrayList<Navigation>();
Map navigaList = new HashMap();
Map params = new HashMap();
params.put("display", true);
params.put("location", location);
params.put("type", "sparegoods");
navs = this.navService
.query("select obj from Navigation obj where obj.display=:display and obj.location=:location and obj.type!=:type order by obj.sequence asc",
params, 0, count);
if(!navs.isEmpty()){
List<Map> navigamap = new ArrayList<Map>();
for(Navigation navigation:navs){
Map navMap = new HashMap();
navMap.put("", navigation.getUrl());
navMap.put("", navigation.getTitle());
//是否新窗口打开,1为新窗口打开,0为默认页面打开
navMap.put("", navigation.getNew_win());
navMap.put("", navigation.getUrl());
navigamap.add(navMap);
navigaList.put("navigamap", navigamap);
}
}
if(CommUtil.isNotNull(navigaList)){
result = new Result(0,"查询成功",navigaList);
}else{
result = new Result(1,"查询失败");
}
String navigaTemp = Json.toJson(result, JsonFormat.compact());
try {
response.getWriter().print(navigaTemp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package com.cninnovatel.ev.type;
import org.apache.commons.lang3.StringUtils;
public enum Refreshable
{
CONFERENCE(1, "conference"), CALLRECORD(2, "callrecord"), CONTACT(3, "contact"), PARTICIPANT(4, "participant");
private int index;
private String tabName;
Refreshable(int index, String name)
{
this.index = index;
this.tabName = name;
}
public int getIndex()
{
return index;
}
public String getTabName()
{
return this.tabName;
}
public static Refreshable fromTabName(String tabName)
{
if (!StringUtils.isEmpty(tabName))
{
for (Refreshable tab : Refreshable.values())
{
if (tab.getTabName().equals(tabName))
{
return tab;
}
}
}
return CONFERENCE;
}
}
|
package com.mkdutton.feedback;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.mkdutton.feedback.fragments.LoginFragment;
import com.mkdutton.feedback.fragments.RecoverPasswordFragment;
import com.mkdutton.feedback.fragments.RegisterFragment;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
import java.util.List;
public class LoginActivity extends BaseActivity implements LoginFragment.LoginListener, RegisterFragment.RegisterUserListener {
public static final String TAG = "LOGIN_ACTIVITY";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.replace(R.id.login_registerContainer, LoginFragment.newInstance(), LoginFragment.TAG)
.commit();
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null && (PreferenceManager.getDefaultSharedPreferences(this)).getBoolean("remember", false) ) {
loginSuccessful(null);
}
}
@Override
protected int getLayout() {
return R.layout.activity_login;
}
@Override
protected void onStart() {
super.onStart();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == android.R.id.home){
int stackCount = getFragmentManager().getBackStackEntryCount();
if (stackCount > 0){
getFragmentManager().popBackStack();
} else {
finish();
}
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void launchRegisterFragment() {
getFragmentManager().beginTransaction()
.replace(R.id.login_registerContainer, RegisterFragment.newInstance(), RegisterFragment.TAG)
.addToBackStack(RegisterFragment.TAG)
.commit();
}
@Override
public void loginSuccessful( ProgressDialog dialog ) {
Intent campaignIntent = new Intent(this, CampaignListActivity.class);
ActivityCompat.startActivity(this, campaignIntent, null);
if (dialog != null) {
dialog.dismiss();
}
}
@Override
public void launchResetFragment() {
getFragmentManager().beginTransaction()
.replace(R.id.login_registerContainer,
RecoverPasswordFragment.newInstance(), RecoverPasswordFragment.TAG)
.addToBackStack(RecoverPasswordFragment.TAG)
.commit();
}
@Override
public void registerUser(final String userID, String user, String pass, String email, String fName, String lName) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Attempting to register....");
progressDialog.setIndeterminate(true);
progressDialog.show();
ParseUser newUser = new ParseUser();
newUser.setUsername(user);
newUser.setPassword(pass);
newUser.setEmail(email);
newUser.put(Utils.LOGIN_KEY_USER_ID, userID);
newUser.put(Utils.LOGIN_KEY_FIRST_NAME, fName);
newUser.put(Utils.LOGIN_KEY_LAST_NAME, lName);
newUser.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo(Utils.LOGIN_KEY_USER_ID, userID);
query.findInBackground(new FindCallback<ParseUser>() {
@Override
public void done(List<ParseUser> parseUsers, ParseException e) {
if (e == null) {
if (parseUsers.size() == 1) {
loginSuccessful(progressDialog);
} else {
Log.i(TAG, "MULTIPLE USERS WITH SAME USER_ID");
}
} else {
Log.i(TAG, e.getMessage());
}
}
});
} else {
if (e.getCode() == 202) {
alertUser("Oops", e.getMessage());
progressDialog.dismiss();
} else if (e.getCode() == 203 ){
alertUser("Oops", e.getMessage());
progressDialog.dismiss();
}
Log.i(TAG, "" + e.getCode() + e.getMessage());
}
}
});
}
@Override
public void alertUser(String title, String message) {
AlertDialog.Builder alert = new AlertDialog.Builder( this );
alert.setTitle(title).setMessage(message).setPositiveButton("Ok", null).show();
}
@Override
public void onBackPressed() {
super.onBackPressed();
int stackCount = getFragmentManager().getBackStackEntryCount();
if (stackCount > 0){
getFragmentManager().popBackStack();
} else {
finish();
}
}
}
|
package com.timewarp.engine;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.timewarp.engine.animator.Animator;
import com.timewarp.engine.configs.ProjectConfig;
import com.timewarp.engine.entities.GameObject;
import com.timewarp.engine.gui.GUI;
import com.timewarp.games.onedroidcode.AssetManager;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.badlogic.gdx.Gdx.input;
/**
* Controls all scenes and handles system events
*/
public class SceneManager {
/**
* Current instance of SceneManager
*/
public static SceneManager instance;
private Scene currentScene;
private OrthographicCamera orthographicCamera;
// private PerspectiveCamera perspectiveCamera;
private int fps = 0;
private float fpsCheckTimer = 1f;
private boolean backRequested = false;
private boolean sceneJustLoaded = false;
/**
* Starts scene manager
*/
public SceneManager() {
SceneManager.instance = this;
}
/**
* Initializes SceneManager, GUI, OpenGL, Animator and AssetManager
*/
public void init() {
Logger.getAnonymousLogger().log(Level.INFO, "[SceneMG] Initialization");
Time.init();
Time.addTimer("running_time");
Time.addTimer("delta_time");
input.setCatchBackKey(true);
currentScene = null;
GUI.init();
GUI.Width = Gdx.graphics.getWidth();
GUI.Height = Gdx.graphics.getHeight();
// Create sprite batch and set up OpenGL
GUI.batch = new SpriteBatch();
Gdx.gl.glClearColor(
ProjectConfig.BACKGROUND_COLOR.r,
ProjectConfig.BACKGROUND_COLOR.g,
ProjectConfig.BACKGROUND_COLOR.b,
1
);
// Create new camera
orthographicCamera = new OrthographicCamera(GUI.Width, GUI.Height);
// perspectiveCamera = new PerspectiveCamera(70, GUI.Width, GUI.Height);
// Load assets
Animator.Init();
AssetManager.loadAssets();
// Load main scene
loadStartScene();
}
/**
* Loads starting application screen
*/
public void loadStartScene() {
try {
loadScene(ProjectConfig.START_SCENE.getClass().newInstance());
} catch (Exception e) {
Logger.getAnonymousLogger().log(Level.WARNING, "Can not load main scene");
e.printStackTrace();
throw new RuntimeException("Can not load main scene");
}
}
/**
* Loads specified application screen
*
* @param scene Scene to load
*/
public void loadScene(Scene scene) {
if (scene == null) {
loadStartScene();
return;
}
sceneJustLoaded = true;
GUI.resetCameraPosition();
Logger.getAnonymousLogger().log(Level.INFO, "[SceneMG] Loading scene '" + scene.getClass().getSimpleName() + "'");
fpsCheckTimer = 1f;
if (currentScene != null) {
Logger.getAnonymousLogger().log(Level.INFO, "[SceneMG] Unloading old resources");
currentScene.pause();
currentScene.unloadResources();
}
Logger.getAnonymousLogger().log(Level.INFO, "[SceneMG] Initializing scene");
Gdx.gl.glClearColor(
ProjectConfig.BACKGROUND_COLOR.r,
ProjectConfig.BACKGROUND_COLOR.g,
ProjectConfig.BACKGROUND_COLOR.b,
1
);
currentScene = scene;
currentScene.initialize();
Logger.getAnonymousLogger().log(Level.INFO, "[SceneMG] Loading scene resources");
currentScene.loadResources();
Logger.getAnonymousLogger().log(Level.INFO, "[SceneMG] Setting up camera");
currentScene.onResolutionChanged();
}
/**
* Runs every frame
* Updates loaded scene and GUI
*/
public void update() {
sceneJustLoaded = false;
if (Gdx.input.isKeyPressed(Input.Keys.BACK)) {
if (!backRequested && currentScene.onBackRequest()) {
Gdx.app.exit();
return;
}
backRequested = true;
} else backRequested = false;
if (currentScene == null) loadStartScene();
if (GUI.Width != Gdx.graphics.getWidth() || GUI.Height != Gdx.graphics.getHeight()) {
GUI.Width = Gdx.graphics.getWidth();
GUI.Height = Gdx.graphics.getHeight();
currentScene.onResolutionChanged();
}
Time.update();
fpsCheckTimer += Gdx.graphics.getDeltaTime();
if (fpsCheckTimer >= 1f) {
fpsCheckTimer = 0;
fps = (int) (1f / Gdx.graphics.getDeltaTime());
Logger.getAnonymousLogger().log(Level.FINEST, "FPS: " + fps);
}
updateCursorState();
for (GameObject gameObject : currentScene.objects) {
this.updateGameObject(gameObject);
}
currentScene.update();
if (!sceneJustLoaded) {
for (GameObject gameObject : currentScene.objects) {
this.updatePostGameObject(gameObject);
}
}
Time.resetTimer("delta_time");
}
private void updateGameObject(GameObject gameObject) {
if (!gameObject.isActive()) return;
gameObject.update();
}
private void updatePostGameObject(GameObject gameObject) {
if (!gameObject.isActive()) return;
gameObject.postUpdate();
}
private void updateCursorState() {
final float deltaTime = Time.getDeltaTime();
// Recalculate control mouse state
GUI.lastTouchPosition.set(GUI.touchPosition);
GUI.isLastTouched = GUI.isTouched;
GUI.isTouched = input.isTouched();
if (GUI.isTouched) {
GUI.touchPosition.set(input.getX(), input.getY());
if (!GUI.isLastTouched)
GUI.touchStartPosition.set(GUI.touchPosition.copy());
}
if (GUI.isTouched) GUI.timeSinceTouchStart += deltaTime;
else GUI.timeSinceTouchStart = 0;
GUI.isClicked = GUI.isLastTouched && !GUI.isTouched;
GUI.isLastLongClicked = GUI.isLongClicked;
GUI.isLongClicked = GUI.isTouched && GUI.timeSinceTouchStart >= 0.5f && !GUI.isLastLongClicked;
final Vector2D movement = GUI.touchStartPosition.sub(GUI.touchPosition);
GUI.isLongClicked &= movement.getLengthSquared() <= 5 * 5;
GUI.isClicked &= movement.getLengthSquared() <= 5 * 5;
if (!GUI.isTouched) {
GUI.touchStartPosition.set(-1, -1);
}
}
/**
* Runs every frame
* Renders loaded scene and draws GUI
*/
public void render() {
if (currentScene == null) loadStartScene();
if (sceneJustLoaded) return;
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
Gdx.gl.glEnable(GL20.GL_BLEND);
Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
// update 3D camera and render scene
// perspectiveCamera.update();
// render GUI
orthographicCamera.update();
GUI.batch.begin();
for (GameObject gameObject : currentScene.objects) {
this.renderGameObject(gameObject);
}
GUI.beginStaticBlock();
currentScene.render();
GUI.endStaticBlock();
Gdx.gl.glDisable(GL20.GL_BLEND);
GUI.batch.end();
}
private void renderGameObject(GameObject gameObject) {
if (!gameObject.isActive()) return;
if (gameObject.isStatic()) {
GUI.beginStaticBlock();
gameObject.render();
GUI.endStaticBlock();
} else {
gameObject.render();
}
}
/**
* Frees all loaded assets
*/
public void dispose() {
AssetManager.unloadAssets();
GUI.batch.dispose();
GUI.font.dispose();
if (currentScene == null) return;
currentScene.unloadResources();
}
/**
* Pauses application
*/
public void pause() {
if (currentScene == null) return;
currentScene.pause();
for (GameObject gameObject: currentScene.objects) {
gameObject.animator.pause();
}
}
/**
* Resumes application
*/
public void resume() {
GUI.Width = Gdx.graphics.getWidth();
GUI.Height = Gdx.graphics.getHeight();
if (currentScene == null) {
loadStartScene();
return;
}
currentScene.resume();
for (GameObject gameObject : currentScene.objects) {
gameObject.animator.resume();
}
}
/**
* Adds gameobject to the scene
* @param gameObject GameObject that will be added
*/
public void addGameObject(GameObject gameObject) {
if (gameObject == null) return;
this.currentScene.objects.add(gameObject);
}
/**
* Removes gameobject from scene
*
* @param gameObject GameObject that will ne deleted
*/
public void removeGameObject(GameObject gameObject) {
gameObject.isDestroyed = true;
this.currentScene.objects.remove(gameObject);
}
public boolean objectExists(GameObject obj) {
return this.currentScene.objects.contains(obj);
}
/**
* Returns calculated FPS
*
* @return frames per second
*/
public int getFPS() {
return fps;
}
}
|
package be.mxs.common.util.system;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.StringReader;
import java.net.URL;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Properties;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import net.admin.Label;
import net.admin.Parameter;
import net.admin.User;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import be.mxs.common.util.db.MedwanQuery;
import be.openclinic.system.TransactionItem;
public class UpdateSystem implements Runnable {
private int progress = -1;
private String basedir;
Thread thread;
//--- RUN -------------------------------------------------------------------------------------
public void run(){
update(); // perform only once
}
//--- CONSTRUCTOR -----------------------------------------------------------------------------
public UpdateSystem(){
}
//--- START -----------------------------------------------------------------------------------
public void start(){
thread = new Thread(this);
thread.start();
}
//--- SET BASE DIR ----------------------------------------------------------------------------
public void setBasedir(String basedir){
this.basedir = basedir;
}
//--- UPDATE ----------------------------------------------------------------------------------
public void update(){
setProgress(5); // "started"
updateDb();
setProgress(20); // "updateDb done"
updateLabels(basedir);
setProgress(40); // "updateLabels done"
updateTransactionItems(basedir);
setProgress(60); // "updateTransactionItems done"
updateCounters();
setProgress(80); // "updateCounters done"
updateExaminations();
setProgress(90); // "updateExaminations done"
String sDoc = MedwanQuery.getInstance().getConfigString("templateSource") + "application.xml";
SAXReader reader = new SAXReader(false);
try{
Document document = reader.read(new URL(sDoc));
Element element = document.getRootElement().element("version");
int thisversion=Integer.parseInt(element.attribute("major").getValue())*1000000+Integer.parseInt(element.attribute("minor").getValue())*1000+Integer.parseInt(element.attribute("bug").getValue());
MedwanQuery.getInstance().setConfigString("updateVersion",thisversion+"");
}
catch(Exception e){
e.printStackTrace();
}
setProgress(100); // "completed"
}
//--- SET PROGRESS ----------------------------------------------------------------------------
private void setProgress(int progress){
this.progress = progress;
}
//--- GET PROGRESS ----------------------------------------------------------------------------
public int getProgress(){
return this.progress;
}
//--- UPDATE QUERIES --------------------------------------------------------------------------
public void updateQueries(javax.servlet.ServletContext application){
UpdateQueries.updateQueries(application);
}
//--- UPDATE DB -------------------------------------------------------------------------------
public void updateDb(){
try {
String sDoc="";
Connection loc_conn = MedwanQuery.getInstance().getLongOpenclinicConnection();
Connection sta_conn = MedwanQuery.getInstance().getStatsConnection();
Connection lad_conn = MedwanQuery.getInstance().getLongAdminConnection();
String sLocalDbType="?";
try {
sLocalDbType = lad_conn.getMetaData().getDatabaseProductName();
}
catch(Exception e){
//e.printStackTrace();
}
boolean bInit=false;
SAXReader reader = new SAXReader(false);
sDoc = MedwanQuery.getInstance().getConfigString("templateSource","http://localhost/openclinic/_common/xml/")+"db.xml";
org.dom4j.Document document = reader.read(new URL(sDoc));
bInit=true;
Iterator tables = document.getRootElement().elementIterator("table");
Element table;
String sMessage = "";
String sOwnServerId = MedwanQuery.getInstance().getConfigString("serverId");
Element versionColumn = null;
Connection connectionCheck = null;
PreparedStatement psCheck = null;
ResultSet rsCheck = null,rsCheck2=null;
Connection otherAdminConnection = null;
Connection otherOccupConnection = null;
Element model = document.getRootElement();
Element column, index, view, proc, exec, sql;
DatabaseMetaData databaseMetaData;
Hashtable adminTables=new Hashtable(),adminColumns=new Hashtable(),adminIndexes=new Hashtable(),openclinicTables=new Hashtable(),openclinicColumns=new Hashtable(),openclinicIndexes=new Hashtable(),statsTables=new Hashtable(),statsColumns=new Hashtable(),statsIndexes=new Hashtable();
Hashtable hTables=null,hColumns=null,hIndexes=null;
Iterator columns, indexes, indexcolumns, views, sqlIterator, procs, execs;
String sSelect, sVal, sQuery, sCountQuery, otherServerId, inSql, versioncompare, values, outSql, indexname;
Connection source, destination;
boolean inited, indexFound, bDoWork, bInited, bCreate;
PreparedStatement psSync;
ResultSet rsSync, rsCount;
PreparedStatement psCountSync, psSync2;
ResultSet rsCountSync, rsSync2;
Object maxVersion;
HashMap primaryKey, cols;
int counter, total, syncTotal, rowCounter, compareStatus;
Statement stDelete, stCount, st;
Integer nVal;
Vector params;
System.out.println(new SimpleDateFormat("HH:mm:ss.SSS").format(new java.util.Date())+": update tables");
//First load databasemodels
String tableName,columnName,indexName;
databaseMetaData=lad_conn.getMetaData();
rsCheck=databaseMetaData.getColumns(null, null, null, null);
while(rsCheck.next()){
tableName=rsCheck.getString("TABLE_NAME");
columnName=rsCheck.getString("COLUMN_NAME");
if(adminTables.get(tableName)==null){
rsCheck2=databaseMetaData.getIndexInfo(null, null, tableName, false, true);
while(rsCheck2.next()){
indexName=rsCheck2.getString("INDEX_NAME");
adminIndexes.put((tableName+"$"+indexName).toLowerCase(),"");
}
adminTables.put(tableName.toLowerCase(),"");
}
adminColumns.put((tableName+"$"+columnName).toLowerCase(),"");
}
setProgress(7);
databaseMetaData=loc_conn.getMetaData();
rsCheck=databaseMetaData.getColumns(null, null, null, null);
while(rsCheck.next()){
tableName=rsCheck.getString("TABLE_NAME");
columnName=rsCheck.getString("COLUMN_NAME");
if(openclinicTables.get(tableName)==null){
openclinicTables.put(tableName.toLowerCase(),"");
rsCheck2=databaseMetaData.getIndexInfo(null, null, tableName, false, true);
while(rsCheck2.next()){
indexName=rsCheck2.getString("INDEX_NAME");
openclinicIndexes.put((tableName+"$"+indexName).toLowerCase(),"");
}
}
openclinicColumns.put((tableName+"$"+columnName).toLowerCase(),"");
}
setProgress(9);
databaseMetaData=sta_conn.getMetaData();
rsCheck=databaseMetaData.getColumns(null, null, null, null);
while(rsCheck.next()){
tableName=rsCheck.getString("TABLE_NAME");
columnName=rsCheck.getString("COLUMN_NAME");
if(statsTables.get(tableName)==null){
statsTables.put(tableName.toLowerCase(),"");
rsCheck2=databaseMetaData.getIndexInfo(null, null, tableName, false, true);
while(rsCheck2.next()){
indexName=rsCheck2.getString("INDEX_NAME");
statsIndexes.put((tableName+"$"+indexName).toLowerCase(),"");
}
}
statsColumns.put((tableName+"$"+columnName).toLowerCase(),"");
}
setProgress(11);
tables = model.elementIterator("table");
while (tables.hasNext()) {
table = (Element) tables.next();
if (table.attribute("db").getValue().equalsIgnoreCase("ocadmin")) {
connectionCheck = lad_conn;
hTables=adminTables;
hColumns=adminColumns;
hIndexes=adminIndexes;
} else if (table.attribute("db").getValue().equalsIgnoreCase("openclinic")) {
connectionCheck = loc_conn;
hTables=openclinicTables;
hColumns=openclinicColumns;
hIndexes=openclinicIndexes;
} else if (table.attribute("db").getValue().equalsIgnoreCase("stats")) {
connectionCheck = sta_conn;
hTables=statsTables;
hColumns=statsColumns;
hIndexes=statsIndexes;
}
boolean tableExists=hTables.get(table.attribute("name").getValue().toLowerCase())!=null;
if (tableExists) {
//verify the table columns
versionColumn = null;
columns = table.element("columns").elementIterator("column");
while (columns.hasNext()) {
try {
column = (Element) columns.next();
if (column.attribute("version") != null && column.attribute("version").getValue().equalsIgnoreCase("1")) {
versionColumn = column;
}
rsCheck = databaseMetaData.getColumns(null, null, table.attribute("name").getValue(), column.attribute("name").getValue());
boolean columnExists=hColumns.get(table.attribute("name").getValue().toLowerCase()+"$"+column.attribute("name").getValue().toLowerCase())!=null;
if (!columnExists) {
sSelect = "alter table " + table.attribute("name").getValue() + " add " + column.attribute("name").getValue() + " ";
if (column.attribute("dbtype").getValue().equalsIgnoreCase("char") || column.attribute("dbtype").getValue().equalsIgnoreCase("varchar")) {
sSelect += column.attribute("dbtype").getValue() + "(" + column.attribute("size").getValue() + ")";
} else {
sSelect += column.attribute("dbtype").getValue();
}
sSelect += " null";
psCheck = connectionCheck.prepareStatement(sSelect);
psCheck.execute();
psCheck.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
} else {
//create the table
sSelect = "create table " + table.attribute("name").getValue() + "(";
columns = table.element("columns").elementIterator("column");
inited = false;
while (columns.hasNext()) {
column = (Element) columns.next();
if (inited) {
sSelect += ",";
} else {
inited = true;
}
sSelect += column.attribute("name").getValue() + " ";
if (column.attribute("dbtype").getValue().equalsIgnoreCase("char") || column.attribute("dbtype").getValue().equalsIgnoreCase("varchar")) {
sSelect += column.attribute("dbtype").getValue() + "(" + column.attribute("size").getValue() + ")";
} else {
sSelect += column.attribute("dbtype").getValue();
}
if (column.attribute("nulls") != null && column.attribute("nulls").getValue().equalsIgnoreCase("0")) {
sSelect += " not null";
} else {
sSelect += " null";
}
}
try {
sSelect += ")";
psCheck = connectionCheck.prepareStatement(sSelect);
psCheck.execute();
psCheck.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
//Now verify the indexes of the table
if (table.element("indexes") != null) {
indexes = table.element("indexes").elementIterator("index");
while (indexes.hasNext()) {
try {
index = (Element) indexes.next();
indexFound = hIndexes.get(table.attribute("name").getValue().toLowerCase()+"$"+index.attribute("name").getValue().toLowerCase())!=null;
if (!indexFound) {
sSelect = "create ";
if (index.attribute("unique") != null && index.attribute("unique").getValue().equalsIgnoreCase("1")) {
sSelect += " unique ";
}
sSelect += "index " + index.attribute("name").getValue() + " on " + table.attribute("name").getValue() + "(";
indexcolumns = index.elementIterator("indexcolumn");
inited = false;
while (indexcolumns.hasNext()) {
Element indexcolumn = (Element) indexcolumns.next();
if (inited) {
sSelect += ",";
} else {
inited = true;
}
if (indexcolumn.attribute("order").getValue().equalsIgnoreCase("ASC")) {
sSelect += indexcolumn.attribute("name").getValue();
} else {
sSelect += indexcolumn.attribute("name").getValue() + " " + indexcolumn.attribute("order").getValue();
}
}
sSelect += ")";
psCheck = connectionCheck.prepareStatement(sSelect);
psCheck.execute();
psCheck.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
System.out.println(new SimpleDateFormat("HH:mm:ss.SSS").format(new java.util.Date())+": update views");
views = model.elementIterator("view");
while (views.hasNext()) {
try {
view = (Element) views.next();
//Checking existence of view
//First select right connection
sqlIterator = view.elementIterator("sql");
String s = "";
while (sqlIterator.hasNext()) {
sql = (Element) sqlIterator.next();
if (sql.attribute("db") == null || sql.attribute("db").getValue().equalsIgnoreCase(sLocalDbType)) {
s = sql.getText().replaceAll("@admin@", MedwanQuery.getInstance().getConfigString("admindbName","ocadmin"));
}
}
if (s.trim().length() > 0) {
if (view.attribute("db").getValue().equalsIgnoreCase("ocadmin")) {
connectionCheck = lad_conn;
hTables=adminTables;
} else if (view.attribute("db").getValue().equalsIgnoreCase("openclinic")) {
connectionCheck = loc_conn;
hTables=openclinicTables;
} else if (view.attribute("db").getValue().equalsIgnoreCase("stats")) {
connectionCheck = sta_conn;
hTables=statsTables;
}
//Now verify existence of view
boolean viewExists=hTables.get(view.attribute("name").getValue().toLowerCase())!=null;
bCreate = true;
if (viewExists) {
if (view.attribute("drop") != null && view.attribute("drop").getValue().equalsIgnoreCase("1")) {
//drop the view
psCheck = connectionCheck.prepareStatement("drop view " + view.attribute("name").getValue());
psCheck.execute();
psCheck.close();
} else {
bCreate = false;
}
}
else {
}
sqlIterator = view.elementIterator("sql");
while (sqlIterator.hasNext()) {
sql = (Element) sqlIterator.next();
if (sql.attribute("db") == null || sql.attribute("db").getValue().equalsIgnoreCase(sLocalDbType)) {
st = connectionCheck.createStatement();
String sq = sql.getText().replaceAll("@admin@", MedwanQuery.getInstance().getConfigString("admindbName","ocadmin")).replaceAll("@openclinic@", MedwanQuery.getInstance().getConfigString("openclinicdbName","openclinic"));
sq = sq.replaceAll("\n", " ");
sq = sq.replaceAll("\r", " ");
st.addBatch(sq);
st.executeBatch();
st.close();
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
loc_conn.close();
lad_conn.close();
sta_conn.close();
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println(new SimpleDateFormat("HH:mm:ss.SSS").format(new java.util.Date())+": end updatedb");
}
//--- UPDATE LABELS ---------------------------------------------------------------------------
public void updateLabels(String basedir){
System.out.println(new SimpleDateFormat("HH:mm:ss.SSS").format(new java.util.Date())+": reload labels");
reloadSingleton();
System.out.println(new SimpleDateFormat("HH:mm:ss.SSS").format(new java.util.Date())+": end reload labels");
System.out.println(new SimpleDateFormat("HH:mm:ss.SSS").format(new java.util.Date())+": start updateLabels");
String paramName, paramValue;
String[] identifiers;
String[] languages = MedwanQuery.getInstance().getConfigString("supportedLanguages","nl,fr,en,pt").split("\\,");
for(int n=0;n<languages.length;n++){
System.out.println(new SimpleDateFormat("HH:mm:ss.SSS").format(new java.util.Date())+": load Labels."+languages[n]+".ini");
Properties iniProps = getPropertyFile(basedir+"/_common/xml/Labels."+languages[n]+".ini");
System.out.println(new SimpleDateFormat("HH:mm:ss.SSS").format(new java.util.Date())+": Labels."+languages[n]+".ini loaded");
Enumeration e = iniProps.keys();
boolean exists;
Hashtable langHashtable,typeHashtable,idHashtable;
Label label;
while(e.hasMoreElements()){
paramName = (String)e.nextElement();
paramValue = iniProps.getProperty(paramName);
identifiers = paramName.split("\\$");
exists=false;
langHashtable = MedwanQuery.getInstance().getLabels();
if(langHashtable!=null && identifiers.length>2){
typeHashtable = (Hashtable) langHashtable.get(identifiers[2]);
if(typeHashtable!=null){
idHashtable = (Hashtable) typeHashtable.get(identifiers[0].toLowerCase());
if(idHashtable!=null){
label = (Label) idHashtable.get(identifiers[1]);
if(label!=null){
exists=true;
}
}
}
}
if(!exists && identifiers.length>2){
try {
String excludedLabelTypes = "*datacenterserver*datacenterservergroup*labanalysis*labanalysis.short*labanalysis.monster*labanalysis.group*insurance.types*prestation.type*resultprofiles*"+
" *admin.category*labanalysis.refcomment*"+
" *labprofiles*activitycodes*worktime*patientsharecoverageinsurance*patientsharecoverageinsurance2*"+
" *urgency.origin*encountertype*prestation.type*product.productgroup*costcenter*"+
" *insurance.types*labanalysis.group*drug.category*planningresource*systemmessages*product.unit*credit.type*wicketcredit.type*"+
" *productstockoperation.sourcedestinationtype*queue*anonymousqueue*costcenter*ikirezi.functional.signs*mir_type*radiologist*"; // default
if(MedwanQuery.getInstance().getConfigString("excludedLabelTypes",excludedLabelTypes).indexOf(identifiers[0])<0){
MedwanQuery.getInstance().storeLabel(identifiers[0],identifiers[1],identifiers[2],paramValue,0);
}
}
catch(Exception ep) {
System.out.println("Error label: "+paramName);
ep.printStackTrace();
}
}
}
}
setProgress(25);
String sDeliveries=MedwanQuery.getInstance().getConfigString("autorizedProductStockOperationDeliveries","'medicationdelivery.1','medicationdelivery.2','medicationdelivery.3','medicationdelivery.4','medicationdelivery.5','medicationdelivery.99'");
String sReceipts=MedwanQuery.getInstance().getConfigString("autorizedProductStockOperationReceipts","'medicationreceipt.1','medicationreceipt.2','medicationreceipt.3','medicationreceipt.4','medicationreceipt.99'");
String sOutcomes=MedwanQuery.getInstance().getConfigString("autorizedEncounterOutcomes","'better','contrareference','dead','deterioration','escape','other','recovered','reference'");
Connection conn = MedwanQuery.getInstance().getOpenclinicConnection();
try{
PreparedStatement ps = conn.prepareStatement("delete from OC_LABELS where OC_LABEL_TYPE='productstockoperation.medicationdelivery' and OC_LABEL_ID not in ("+sDeliveries+")");
ps.execute();
ps = conn.prepareStatement("delete from OC_LABELS where OC_LABEL_TYPE='productstockoperation.medicationreceipt' and OC_LABEL_ID not in ("+sReceipts+")");
ps.execute();
ps = conn.prepareStatement("delete from OC_LABELS where OC_LABEL_TYPE='encounter.outcome' and OC_LABEL_ID not in ("+sOutcomes+")");
ps.execute();
ps.close();
conn.close();
}
catch(Exception e){
e.printStackTrace();
}
setProgress(30);
//Clear non-existing extrainsurars
try{
PreparedStatement ps = conn.prepareStatement("delete from OC_LABELS where OC_LABEL_TYPE='patientsharecoverageinsurance' and replace(OC_LABEL_ID,'"+MedwanQuery.getInstance().getConfigString("serverId")+".','') not in (select OC_INSURAR_OBJECTID from OC_INSURARS)");
ps.execute();
ps = conn.prepareStatement("delete from OC_LABELS where OC_LABEL_TYPE='patientsharecoverageinsurance2' and replace(OC_LABEL_ID,'"+MedwanQuery.getInstance().getConfigString("serverId")+".','') not in (select OC_INSURAR_OBJECTID from OC_INSURARS)");
ps.execute();
ps.close();
conn.close();
}
catch(Exception e){
e.printStackTrace();
}
System.out.println(new SimpleDateFormat("HH:mm:ss.SSS").format(new java.util.Date())+": reload labels");
reloadSingleton();
System.out.println(new SimpleDateFormat("HH:mm:ss.SSS").format(new java.util.Date())+": end updateLabels");
}
//--- UPDATE TRANSACTION ITEMS ----------------------------------------------------------------
public void updateTransactionItems(String basedir){
System.out.println(new SimpleDateFormat("HH:mm:ss.SSS").format(new java.util.Date())+": start updatetransactionitems");
Hashtable transactionItems = MedwanQuery.getInstance().getAllTransactionItems();
String paramName, paramValue;
TransactionItem objTI;
Properties iniProps = getPropertyFile(basedir+"/_common/xml/TransactionItems.ini");
Enumeration e = iniProps.keys();
int n =0,n2=iniProps.size();
while(e.hasMoreElements()){
n++;
setProgress(40+20*n/n2);
paramName = (String)e.nextElement();
paramValue = iniProps.getProperty(paramName);
if (transactionItems.get(paramName)==null) {
objTI = new TransactionItem();
objTI.setTransactionTypeId(paramName.split("\\$")[0]);
objTI.setItemTypeId(paramName.split("\\$")[1]);
if(paramValue.split("\\$")!=null && paramValue.split("\\$").length>0){
objTI.setDefaultValue(paramValue.split("\\$")[0]);
if(paramValue.split("\\$")!=null && paramValue.split("\\$").length>1){
objTI.setModifier(paramValue.split("\\$")[1]);
}
else {
objTI.setModifier("");
}
}
else {
objTI.setDefaultValue("");
objTI.setModifier("");
}
TransactionItem.addTransactionItem(objTI);
}
}
Connection conn = MedwanQuery.getInstance().getOpenclinicConnection();
try{
PreparedStatement ps = conn.prepareStatement("drop table if exists ti");
ps.execute();
ps.close();
ps=conn.prepareStatement("create table ti like transactionitems");
ps.execute();
ps.close();
ps=conn.prepareStatement("insert into ti select distinct * from transactionitems");
ps.execute();
ps.close();
ps=conn.prepareStatement("delete from transactionitems");
ps.execute();
ps.close();
ps=conn.prepareStatement("insert into transactionitems select * from ti");
ps.execute();
ps.close();
ps=conn.prepareStatement("drop table ti");
ps.execute();
ps.close();
conn.close();
}
catch(Exception r){
r.printStackTrace();
}
System.out.println(new SimpleDateFormat("HH:mm:ss.SSS").format(new java.util.Date())+": end updatetransactionitems");
}
//--- RELOAD SINGLETON ------------------------------------------------------------------------
public void reloadSingleton() {
Hashtable labelLanguages = new Hashtable();
Hashtable labelTypes = new Hashtable();
Hashtable labelIds;
net.admin.Label label;
// only load labels in memory that are service nor function.
Vector vLabels = net.admin.Label.getNonServiceFunctionLabels();
Iterator iter = vLabels.iterator();
if (Debug.enabled) Debug.println("About to (re)load labels.");
while(iter.hasNext()){
label = (net.admin.Label)iter.next();
// type
labelTypes = (Hashtable) labelLanguages.get(label.language);
if (labelTypes == null) {
labelTypes = new Hashtable();
labelLanguages.put(label.language, labelTypes);
//Debug.println("new language : "+label.language);
}
// id
labelIds = (Hashtable) labelTypes.get(label.type);
if (labelIds == null) {
labelIds = new Hashtable();
labelTypes.put(label.type, labelIds);
//Debug.println("new type : "+label.type);
}
labelIds.put(label.id, label);
}
// status info
if (Debug.enabled) {
Debug.println("Labels (re)loaded.");
Debug.println(" * " + labelLanguages.size() + " languages");
Debug.println(" * " + labelTypes.size() + " types per language");
}
MedwanQuery.getInstance().putLabels(labelLanguages);
}
//--- RELOAD SINGLETON ------------------------------------------------------------------------
public static void reloadSingletonNoSession() {
Hashtable labelLanguages = new Hashtable();
Hashtable labelTypes = new Hashtable();
Hashtable labelIds;
net.admin.Label label;
// only load labels in memory that are service nor function.
Vector vLabels = net.admin.Label.getNonServiceFunctionLabels();
Iterator iter = vLabels.iterator();
if (Debug.enabled) Debug.println("About to (re)load labels.");
while(iter.hasNext()){
label = (net.admin.Label)iter.next();
// type
labelTypes = (Hashtable) labelLanguages.get(label.language);
if (labelTypes == null) {
labelTypes = new Hashtable();
labelLanguages.put(label.language, labelTypes);
//Debug.println("new language : "+label.language);
}
// id
labelIds = (Hashtable) labelTypes.get(label.type);
if (labelIds == null) {
labelIds = new Hashtable();
labelTypes.put(label.type, labelIds);
//Debug.println("new type : "+label.type);
}
labelIds.put(label.id, label);
}
// status info
if (Debug.enabled) {
Debug.println("Labels (re)loaded.");
Debug.println(" * " + labelLanguages.size() + " languages");
Debug.println(" * " + labelTypes.size() + " types per language");
}
MedwanQuery.getInstance().putLabels(labelLanguages);
}
//--- UPDATE PROJECT --------------------------------------------------------------------------
public void updateProject(String sProject){
Connection conn = MedwanQuery.getInstance().getAdminConnection();
PreparedStatement ps;
try {
ps = conn.prepareStatement("update Users set project=?");
ps.setString(1, sProject);
ps.execute();
ps.close();
conn.close();
MedwanQuery.getInstance().setConfigString("availableProjects", sProject);
MedwanQuery.getInstance().setConfigString("defaultProject", sProject);
} catch (SQLException e) {
e.printStackTrace();
}
}
//--- GET PROPERTY FILE -----------------------------------------------------------------------
private Properties getPropertyFile(String sFilename) {
FileInputStream iniIs;
Properties iniProps = new Properties();
// create ini file if they do not exist
try {
iniIs = new FileInputStream(sFilename);
iniProps.load(iniIs);
iniIs.close();
}
catch (FileNotFoundException e) {
// create the file if it does not exist
try {
new FileOutputStream(sFilename);
}
catch (Exception e1) {
if (Debug.enabled) Debug.println(e1.getMessage());
}
}
catch (Exception e) {
if (Debug.enabled) Debug.println(e.getMessage());
}
return iniProps;
}
//--- VALIDATE COUNCIL REGISTRATIONS ----------------------------------------------------------
public void validateCouncilRegistrations(){
String regnrs="";
Hashtable hRegs=new Hashtable();
Hashtable councils=new Hashtable();
try{
Connection conn = MedwanQuery.getInstance().getAdminConnection();
PreparedStatement ps = conn.prepareStatement("select distinct userid,value from UserParameters a where parameter='automaticorganizationidvalidation' and active=1");
ResultSet rs = ps.executeQuery();
while(rs.next()){
String council = rs.getString("value");
int userid = rs.getInt("userid");
PreparedStatement ps2 = conn.prepareStatement("select * from UserParameters where userid=? and parameter='organisationid' and active=1");
ps2.setInt(1, userid);
ResultSet rs2=ps2.executeQuery();
if(rs2.next()){
String reg=rs2.getString("value");
if(hRegs.get(reg)==null){
String regs = (String)councils.get(council);
if(regs==null){
regs="";
}
if(regs.length()>0){
regs+=";";
}
regs+=reg;
councils.put(council, regs);
hRegs.put(reg,"1");
}
}
rs2.close();
ps2.close();
}
rs.close();
ps.close();
//We now have all id's to verify
Enumeration r = councils.keys();
while(r.hasMoreElements()){
String council = (String)r.nextElement();
String regs = (String)councils.get(council);
//Launch the updatequery for this council
HttpClient client = new HttpClient();
MedwanQuery.getInstance().reloadLabels();
String lookupUrl=ScreenHelper.getTran(null,"professional.council.url",council,"fr");
Debug.println("launching post to "+lookupUrl);
PostMethod method = new PostMethod(lookupUrl);
method.setRequestHeader("Content-type","text/xml; charset=windows-1252");
NameValuePair nvp1= new NameValuePair("regnrs",regs);
NameValuePair nvp2= new NameValuePair("key",MedwanQuery.getInstance().getConfigString("councilLookupKey"));
method.setQueryString(new NameValuePair[]{nvp1,nvp2});
try{
int statusCode = client.executeMethod(method);
Debug.println("resultcode = "+statusCode);
if(statusCode==200){
String xml = method.getResponseBodyAsString();
org.dom4j.Document document=null;
Element root=null;
BufferedReader br = new BufferedReader(new StringReader(xml));
SAXReader reader=new SAXReader(false);
document=reader.read(br);
Debug.println("xml = "+document.asXML());
root=document.getRootElement();
if(root.getName().equalsIgnoreCase("registration")){
Iterator elements = root.elementIterator("status");
while(elements.hasNext()){
Element element = (Element)elements.next();
ps=conn.prepareStatement("select * from UserParameters where parameter='organisationid' and value=? and active=1");
ps.setString(1, element.attributeValue("regnr"));
rs=ps.executeQuery();
while(rs.next()){
User user = User.get(rs.getInt("userid"));
if(user !=null && !user.getParameter("registrationstatus").equalsIgnoreCase(element.attributeValue("id"))){
user.updateParameter(new Parameter("registrationstatus",element.attributeValue("id")));
user.updateParameter(new Parameter("registrationstatusdate",ScreenHelper.stdDateFormat.format(new java.util.Date())));
}
else if(user!=null && !user.getParameter("registrationstatus").equalsIgnoreCase("0")){
if(MedwanQuery.getInstance().getConfigInt("enableProfessionalCouncilRegistrationCancellation",0)==1){
try{
long trimester = 24*3600*1000;
trimester=trimester*MedwanQuery.getInstance().getConfigInt("professionalCouncilRegistrationCancellationDelay",90);
if(new java.util.Date().getTime()-ScreenHelper.parseDate(user.getParameter("registrationstatusdate")).getTime()>trimester){
//Cancel user access
user.stop=ScreenHelper.stdDateFormat.format(new java.util.Date());
user.saveToDB();
}
}
catch(Exception e4){
e4.printStackTrace();
}
}
}
user.updateParameter(new Parameter("registrationstatusupdatetime",ScreenHelper.stdDateFormat.format(new java.util.Date())));
}
rs.close();
ps.close();
}
}
MedwanQuery.getInstance().setConfigString("lastProfessionalCouncilValidation", new SimpleDateFormat("yyyyMMdd").format(new java.util.Date()));
}
}
catch(Exception e3){
e3.printStackTrace();
}
}
conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
//--- UPDATE SETUP ----------------------------------------------------------------------------
public void updateSetup(String section, String code, HttpServletRequest request){
MedwanQuery.getInstance().setConfigString("setup."+section, code);
try{
SAXReader xmlReader = new SAXReader();
Document document;
String sMenuXML = MedwanQuery.getInstance().getConfigString("setupXMLFile","setup.xml");
String sMenuXMLUrl = MedwanQuery.getInstance().getConfigString("templateSource") + sMenuXML;
// Check if menu file exists, else use file at templateSource location.
document = xmlReader.read(new URL(sMenuXMLUrl));
if (document != null) {
Element root = document.getRootElement();
if (root != null) {
Iterator elements = root.elementIterator(section);
while (elements.hasNext()) {
Element e = (Element) elements.next();
if(e.attributeValue("code").equalsIgnoreCase(code)){
Iterator configelements = e.elementIterator();
while(configelements.hasNext()){
Element configelement = (Element)configelements.next();
if(configelement.getName().equalsIgnoreCase("config")){
//This is an OC_CONFIG setting
String setupdir=request.getSession().getServletContext().getRealPath("/").replaceAll("\\\\","/");
String context = request.getRequestURL().toString().replaceAll(request.getServletPath(),"");
String minicontext =request.getContextPath().replaceAll("/", "");
String localcontext = request.getProtocol().split("/")[0].toLowerCase()+"://localhost:"+request.getServerPort()+request.getContextPath();
String key=configelement.attributeValue("key");
String value=configelement.attributeValue("value")+"";
String configkey=key.replaceAll("\\$setupdir\\$", setupdir).replaceAll("\\$context\\$", context).replaceAll("\\$localcontext\\$", localcontext).replaceAll("\\$minicontext\\$", minicontext).replaceAll("\\$project\\$", MedwanQuery.getInstance().getConfigString("defaultProject","oc"));
String configvalue=value.replaceAll("\\$setupdir\\$", setupdir).replaceAll("\\$context\\$", context).replaceAll("\\$localcontext\\$", localcontext).replaceAll("\\$minicontext\\$", minicontext).replaceAll("\\$project\\$", MedwanQuery.getInstance().getConfigString("defaultProject","oc"));
MedwanQuery.getInstance().setConfigString(configkey,configvalue);
if(ScreenHelper.checkString(configelement.attributeValue("mkdir")).equalsIgnoreCase("true")){
try{
if(!new java.io.File(configvalue).exists()){
new java.io.File(configvalue).mkdirs();
}
}
catch(Exception io){
io.printStackTrace();
}
}
}
else if(configelement.getName().equalsIgnoreCase("labels")){
//This is a label list
//First erase existing entries
Connection conn = MedwanQuery.getInstance().getOpenclinicConnection();
PreparedStatement ps = conn.prepareStatement("delete from OC_LABELS where OC_LABEL_TYPE=?");
ps.setString(1, configelement.attributeValue("type"));
ps.execute();
ps.close();
conn.close();
//Then, add every label that is inside this label list
Iterator labels = configelement.elementIterator("label");
while(labels.hasNext()){
Element labelelement = (Element)labels.next();
Label label = new Label(configelement.attributeValue("type"),labelelement.attributeValue("id"),labelelement.attributeValue("language"),labelelement.getText(),"1","4");
label.saveToDB();
}
MedwanQuery.getInstance().reloadLabels();
}
}
}
}
}
}
}catch (Exception e){
e.printStackTrace();
}
}
//--- INITIAL SETUP ---------------------------------------------------------------------------
public void initialSetup(String section, String code, HttpServletRequest request){
MedwanQuery.getInstance().setConfigString("setup."+section, code);
try{
SAXReader xmlReader = new SAXReader();
Document document;
String sMenuXML = MedwanQuery.getInstance().getConfigString("setupXMLFile","setup.xml");
String sMenuXMLUrl = MedwanQuery.getInstance().getConfigString("templateSource") + sMenuXML;
// Check if menu file exists, else use file at templateSource location.
document = xmlReader.read(new URL(sMenuXMLUrl));
if (document != null) {
Element root = document.getRootElement();
if (root != null) {
Iterator elements = root.elementIterator(section);
while (elements.hasNext()) {
Element e = (Element) elements.next();
if(e.attributeValue("code").equalsIgnoreCase(code)){
Iterator configelements = e.elementIterator();
while(configelements.hasNext()){
Element configelement = (Element)configelements.next();
if(configelement.getName().equalsIgnoreCase("config")){
//This is an OC_CONFIG setting
String setupdir=request.getSession().getServletContext().getRealPath("/").replaceAll("\\\\","/");
String context = request.getRequestURL().toString().replaceAll(request.getServletPath(),"");
String key=configelement.attributeValue("key");
String value=configelement.attributeValue("value")+"";
MedwanQuery.getInstance().setConfigString(key,value.replaceAll("\\$setupdir\\$", setupdir).replaceAll("\\$context\\$", context));
}
else if(configelement.getName().equalsIgnoreCase("labels")){
//This is a label list
//First erase existing entries
Connection conn = MedwanQuery.getInstance().getOpenclinicConnection();
PreparedStatement ps = conn.prepareStatement("delete from OC_LABELS where OC_LABEL_TYPE=?");
ps.setString(1, configelement.attributeValue("type"));
ps.execute();
ps.close();
conn.close();
//Then, add every label that is inside this label list
Iterator labels = configelement.elementIterator("label");
while(labels.hasNext()){
Element labelelement = (Element)labels.next();
Label label = new Label(configelement.attributeValue("type"),labelelement.attributeValue("id"),labelelement.attributeValue("language"),labelelement.getText(),"1","4");
label.saveToDB();
}
MedwanQuery.getInstance().reloadLabels();
}
else if(configelement.getName().equalsIgnoreCase("project")){
updateProject(configelement.getText());
}
}
}
}
}
}
}catch (Exception e){
e.printStackTrace();
}
}
//--- UPDATE EXAMINATIONS ---------------------------------------------------------------------
public int updateExaminations(){
int counter=0;
Connection conn = MedwanQuery.getInstance().getOpenclinicConnection();
PreparedStatement ps=null;
ResultSet rs=null;
try{
SAXReader xmlReader = new SAXReader();
Document document;
String sMenuXML = MedwanQuery.getInstance().getConfigString("examinationsXMLFile","examinations.xml");
String sMenuXMLUrl = MedwanQuery.getInstance().getConfigString("templateSource") + sMenuXML;
// Check if menu file exists, else use file at templateSource location.
document = xmlReader.read(new URL(sMenuXMLUrl));
if (document != null) {
Element root = document.getRootElement();
if (root != null) {
Iterator elements = root.elementIterator("Row");
int n=0,n2=root.elements("Row").size();
while (elements.hasNext()) {
n++;
setProgress(80+10*n/n2);
Element e = (Element) elements.next();
Element id = e.element("id");
Element transactiontype = e.element("transactiontype");
Element data =e.element("Data");
Element fr=e.element("fr");
Element en=e.element("en");
Element es=e.element("es");
Element nl=e.element("nl");
Element pt=e.element("pt");
if(id!=null && transactiontype!=null){
counter++;
//First search if the examination already exists
ps=conn.prepareStatement("select * from examinations where transactiontype=?");
ps.setString(1, transactiontype.getText());
rs=ps.executeQuery();
if(rs.next()){
//Examination exists
int oldid = rs.getInt("id");
if(oldid!=Integer.parseInt(id.getText())){
//Update examinations, serviceexaminations and oc_labels tables with new id value
rs.close();
ps.close();
ps=conn.prepareStatement("update examinations set id=? where id=?");
ps.setInt(1, Integer.parseInt(id.getText()));
ps.setInt(2, oldid);
ps.execute();
ps.close();
ps=conn.prepareStatement("update serviceexaminations set examinationid=? where examinationid=?");
ps.setInt(1, Integer.parseInt(id.getText()));
ps.setInt(2, oldid);
ps.execute();
ps.close();
ps=conn.prepareStatement("update oc_labels set oc_label_id=? where oc_label_id=? and oc_label_type='examination'");
ps.setString(1, id.getText());
ps.setString(2, oldid+"");
ps.execute();
ps.close();
}
if(fr!=null){
Label label = new Label("examination",id.getText(),"fr",fr.getText(),"1","4");
label.saveToDB();
label = new Label("web.occup",transactiontype.getText(),"fr",fr.getText(),"1","4");
label.saveToDB();
}
if(en!=null){
Label label = new Label("examination",id.getText(),"en",en.getText(),"1","4");
label.saveToDB();
label = new Label("web.occup",transactiontype.getText(),"en",fr.getText(),"1","4");
label.saveToDB();
}
if(es!=null){
Label label = new Label("examination",id.getText(),"es",es.getText(),"1","4");
label.saveToDB();
label = new Label("web.occup",transactiontype.getText(),"es",fr.getText(),"1","4");
label.saveToDB();
}
if(nl!=null){
Label label = new Label("examination",id.getText(),"nl",nl.getText(),"1","4");
label.saveToDB();
label = new Label("web.occup",transactiontype.getText(),"nl",fr.getText(),"1","4");
label.saveToDB();
}
if(pt!=null){
Label label = new Label("examination",id.getText(),"pt",pt.getText(),"1","4");
label.saveToDB();
label = new Label("web.occup",transactiontype.getText(),"pt",fr.getText(),"1","4");
label.saveToDB();
}
}
else{
//Examination doesn't exist, let's add it
rs.close();
ps.close();
ps=conn.prepareStatement("insert into examinations(id,transactiontype,priority,data,updatetime,updateuserid,messageKey) values(?,?,1,?,?,4,'')");
ps.setInt(1,Integer.parseInt(id.getText()));
ps.setString(2, transactiontype.getText());
ps.setBytes(3, data!=null?data.asXML().getBytes():"".getBytes());
ps.setTimestamp(4, new java.sql.Timestamp(new java.util.Date().getTime()));
ps.execute();
ps.close();
if(fr!=null){
Label label = new Label("examination",id.getText(),"fr",fr.getText(),"1","4");
label.saveToDB();
label = new Label("web.occup",transactiontype.getText(),"fr",fr.getText(),"1","4");
label.saveToDB();
}
if(en!=null){
Label label = new Label("examination",id.getText(),"en",en.getText(),"1","4");
label.saveToDB();
label = new Label("web.occup",transactiontype.getText(),"en",fr.getText(),"1","4");
label.saveToDB();
}
if(es!=null){
Label label = new Label("examination",id.getText(),"es",es.getText(),"1","4");
label.saveToDB();
label = new Label("web.occup",transactiontype.getText(),"es",fr.getText(),"1","4");
label.saveToDB();
}
if(nl!=null){
Label label = new Label("examination",id.getText(),"nl",nl.getText(),"1","4");
label.saveToDB();
label = new Label("web.occup",transactiontype.getText(),"nl",fr.getText(),"1","4");
label.saveToDB();
}
if(pt!=null){
Label label = new Label("examination",id.getText(),"pt",pt.getText(),"1","4");
label.saveToDB();
label = new Label("web.occup",transactiontype.getText(),"pt",fr.getText(),"1","4");
label.saveToDB();
}
}
}
}
}
}
//Do the same for customexaminations
sMenuXML = MedwanQuery.getInstance().getConfigString("customExaminationsXMLFile","noexaminations");
if(!sMenuXML.equalsIgnoreCase("noexaminations")){
sMenuXMLUrl = MedwanQuery.getInstance().getConfigString("templateSource") + sMenuXML;
document = xmlReader.read(new URL(sMenuXMLUrl));
if (document != null) {
Element root = document.getRootElement();
if (root != null) {
Iterator elements = root.elementIterator("Row");
int n=0,n2=root.elements("Row").size();
while (elements.hasNext()) {
n++;
setProgress(80+10*n/n2);
Element e = (Element) elements.next();
Element id = e.element("id");
Element transactiontype = e.element("transactiontype");
Element data =e.element("Data");
Element fr=e.element("fr");
Element en=e.element("en");
Element es=e.element("es");
Element nl=e.element("nl");
Element pt=e.element("pt");
if(id!=null && transactiontype!=null){
counter++;
//First search if the examination already exists
ps=conn.prepareStatement("select * from examinations where transactiontype=?");
ps.setString(1, transactiontype.getText());
rs=ps.executeQuery();
if(rs.next()){
//Examination exists
int oldid = rs.getInt("id");
if(oldid!=Integer.parseInt(id.getText())){
//Update examinations, serviceexaminations and oc_labels tables with new id value
rs.close();
ps.close();
ps=conn.prepareStatement("update examinations set id=? where id=?");
ps.setInt(1, Integer.parseInt(id.getText()));
ps.setInt(2, oldid);
ps.execute();
ps.close();
ps=conn.prepareStatement("update serviceexaminations set examinationid=? where examinationid=?");
ps.setInt(1, Integer.parseInt(id.getText()));
ps.setInt(2, oldid);
ps.execute();
ps.close();
ps=conn.prepareStatement("update oc_labels set oc_label_id=? where oc_label_id=? and oc_label_type='examination'");
ps.setString(1, id.getText());
ps.setString(2, oldid+"");
ps.execute();
ps.close();
}
else {
//Update has already been performed on this examination, do nothing
}
}
else{
//Examination doesn't exist, let's add it
rs.close();
ps.close();
ps=conn.prepareStatement("insert into examinations(id,transactiontype,priority,data,updatetime,updateuserid,messageKey) values(?,?,1,?,?,4,'')");
ps.setInt(1,Integer.parseInt(id.getText()));
ps.setString(2, transactiontype.getText());
ps.setBytes(3, data!=null?data.asXML().getBytes():"".getBytes());
ps.setTimestamp(4, new java.sql.Timestamp(new java.util.Date().getTime()));
ps.execute();
ps.close();
if(fr!=null){
Label label = new Label("examination",id.getText(),"fr",fr.getText(),"1","4");
label.saveToDB();
}
if(en!=null){
Label label = new Label("examination",id.getText(),"en",en.getText(),"1","4");
label.saveToDB();
}
if(es!=null){
Label label = new Label("examination",id.getText(),"es",es.getText(),"1","4");
label.saveToDB();
}
if(nl!=null){
Label label = new Label("examination",id.getText(),"nl",nl.getText(),"1","4");
label.saveToDB();
}
if(pt!=null){
Label label = new Label("examination",id.getText(),"pt",pt.getText(),"1","4");
label.saveToDB();
}
}
}
}
}
}
}
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
conn.close();
reloadSingleton();
updateCounters();
}
catch(Exception e2){
e2.printStackTrace();
}
}
return counter;
}
//--- UPDATE COUNTERS -------------------------------------------------------------------------
public void updateCounters() {
try{
Connection conn = MedwanQuery.getInstance().getOpenclinicConnection();
PreparedStatement ps = conn.prepareStatement("select * from oc_config where oc_key like 'quickList%'");
ResultSet rs = ps.executeQuery();
while (rs.next()){
String oc_key=rs.getString("OC_KEY");
String oc_value=rs.getString("OC_VALUE");
String news="";
if(oc_value.indexOf("£")<0){
String[] s=oc_value.split(";");
for(int n=0;n<s.length;n++){
if(news.length()>0){
news=";"+news;
}
for (int i=s[n].split("\\.").length-1;i>-1;i--){
if(i==s[n].split("\\.").length-3){
news="£"+news;
}
else if (i<s[n].split("\\.").length-1){
news="."+news;
}
news=s[n].split("\\.")[i]+news;
}
}
MedwanQuery.getInstance().setConfigString(oc_key, news);
}
}
rs.close();
ps.close();
//First check local database server type
String sLocalDbType = conn.getMetaData().getDatabaseProductName();
System.out.println("Local DB Type = "+sLocalDbType);
SAXReader xmlReader = new SAXReader();
Document document;
String sMenuXML = MedwanQuery.getInstance().getConfigString("countersXMLFile","counters.xml");
String sMenuXMLUrl = MedwanQuery.getInstance().getConfigString("templateSource") + sMenuXML;
// Check if menu file exists, else use file at templateSource location.
document = xmlReader.read(new URL(sMenuXMLUrl));
if (document != null) {
Element root = document.getRootElement();
if (root != null) {
Iterator elements = root.elementIterator("counter");
while (elements.hasNext()) {
Element e = (Element) elements.next();
if(ScreenHelper.checkString(e.attributeValue("server")).length()>0 && !e.attributeValue("server").equalsIgnoreCase(sLocalDbType)){
continue;
}
MedwanQuery.getInstance().setSynchroniseCounters(e.attributeValue("name"), e.attributeValue("table"), e.attributeValue("field"), e.attributeValue("bd"));
}
}
}
conn.close();
}catch (Exception e){
e.printStackTrace();
}
//Patients archiveFileCode
String s="select max(archivefilecode) as maxcode from adminview where "+MedwanQuery.getInstance().getConfigString("lengthFunction","len")+"(archivefilecode)=(select max("+MedwanQuery.getInstance().getConfigString("lengthFunction","len")+"(archivefilecode)) from adminview where "+MedwanQuery.getInstance().getConfigString("lengthFunction","len")+"(archivefilecode)<7)";
Connection oc_conn=MedwanQuery.getInstance().getOpenclinicConnection();
try{
PreparedStatement ps=oc_conn.prepareStatement(s);
ResultSet rs = ps.executeQuery();
if(rs.next()){
String maxcode=rs.getString("maxcode");
rs.close();
ps.close();
s="update OC_COUNTERS set OC_COUNTER_VALUE=? where OC_COUNTER_NAME=?";
ps=oc_conn.prepareStatement(s);
ps.setInt(1,ScreenHelper.convertFromAlfabeticalCode(maxcode)+1);
ps.setString(2,"ArchiveFileId");
ps.executeUpdate();
ps.close();
}
else{
rs.close();
ps.close();
}
}
catch(Exception e){
e.printStackTrace();
}
try{
oc_conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
|
package random;
public class C189 {
public static void main(String[] args) {
int[] nums = { 1, 2, 3, 4, 5, 6, 7 };
int k = 3;
Solution_1 solution = new Solution_1();
solution.rotate(nums, k);
}
/**
* for循环的方式 , 但时间复杂度较大
*/
static class Solution_1 {
public void rotate(int[] nums, int k) {
int len = nums.length;
for (int i = 0; i < k; i++) {
int end = nums[len - 1];
for (int j = len - 1; j >= 1; j--) {
nums[j] = nums[j - 1];
}
nums[0] = end;
}
}
}
/** 其实是个环形相乘的道理 */
// static class Solution_2 {
// public void rotate(int[] nums, int k) {
// int len = nums.length;
// for (int i = 0; i < len; i++) {
// int x = (i + k) % len;
// int tmp = nums[i];
// nums[i] = nums[x];
// nums[x] = tmp;
// }
// }
// }
}
|
package exercicios.desafios.uri;
import java.util.Locale;
public class CalculoSimples1010 {
public static void main(String[] args) {
Locale.setDefault(Locale.US);
int cod1 = 12;
int qtd1 = 1;
double valor1 = 5.30;
int cod2 = 16;
int qtd2 = 2;
double valor2 = 5.10;
double custoTotal = qtd1 * valor1 + qtd2 * valor2;
System.out.printf("VALOR A PAGAR: R$ %.2f%n", custoTotal);
}
}
|
package com.aidigame.hisun.imengstar;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Map;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.os.Handler;
import android.view.View;
import com.aidigame.hisun.imengstar.bean.MyUser;
import com.aidigame.hisun.imengstar.constant.Constants;
import com.aidigame.hisun.imengstar.http.HttpUtil;
import com.aidigame.hisun.imengstar.huanxin.DemoHXSDKHelper;
import com.aidigame.hisun.imengstar.huanxin.User;
import com.aidigame.hisun.imengstar.util.HandleHttpConnectionException;
import com.aidigame.hisun.imengstar.util.LogUtil;
import com.aidigame.hisun.imengstar.util.StringUtil;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChat;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.utils.StorageUtils;
import dalvik.system.VMRuntime;
public class PetApplication extends Application{
public static PetApplication petApp;
public MyUser user;
Constants constants;
private final static float TARGET_HEAP_UTILIZATION = 0.75f;
public Bitmap blurBmp;
//登陆是否成功
public static boolean isSuccess=false;
public static String SID;
public static MyUser myUser;
// public static final String ERROR_MESSAGE="COM.AIDIGAME.HISUN.PET.ERROR_MESSAGE";
private Handler handler;
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
handler=HandleHttpConnectionException.getInstance().getHandler(this);
VMRuntime.getRuntime().setTargetHeapUtilization(TARGET_HEAP_UTILIZATION);
final int HEAP_SIZE = 10 * 1024* 1024 ;
VMRuntime.getRuntime().setMinimumHeapSize(HEAP_SIZE);
petApp=this;
CrashHandler crashHandler=CrashHandler.getInstance();
crashHandler.init(this);
LogUtil.i("exception","petApplication执行onCreate方法" );
constants=new Constants();
SharedPreferences sp=getSharedPreferences(Constants.BASEIC_SHAREDPREFERENCE_NAME, Context.MODE_WORLD_WRITEABLE);
Editor ed=sp.edit();
String versions=sp.getString(Constants.BASEIC_VERSION, "");
if(!StringUtil.isEmpty(versions)){
if(!versions.equals(StringUtil.getAPKVersionName(this))){
ed.putString(Constants.BASEIC_VERSION, StringUtil.getAPKVersionName(this));
ed.putBoolean(Constants.BASEIC_SHAREDPREFERENCE_NAME_GUIDE1, true);
ed.putBoolean(Constants.BASEIC_SHAREDPREFERENCE_NAME_GUIDE2, true);
ed.putBoolean(Constants.BASEIC_SHAREDPREFERENCE_NAME_GUIDE3, true);
ed.putBoolean(Constants.BASEIC_SHAREDPREFERENCE_NAME_GUIDE4, true);
ed.putBoolean(Constants.BASEIC_SHAREDPREFERENCE_NAME_GUIDE5, true);
ed.putBoolean(Constants.BASEIC_SHAREDPREFERENCE_NAME_GUIDE6, true);
ed.putBoolean(Constants.BASEIC_SHAREDPREFERENCE_NAME_GUIDE7, true);
ed.putBoolean(Constants.BASEIC_SHAREDPREFERENCE_NAME_GUIDE8, true);
ed.putBoolean(Constants.BASEIC_SHAREDPREFERENCE_NAME_GUIDE9, true);
}else{
}
}else{
ed.putString(Constants.BASEIC_VERSION, StringUtil.getAPKVersionName(this));
ed.putBoolean(Constants.BASEIC_SHAREDPREFERENCE_NAME_GUIDE1, true);
ed.putBoolean(Constants.BASEIC_SHAREDPREFERENCE_NAME_GUIDE2, true);
ed.putBoolean(Constants.BASEIC_SHAREDPREFERENCE_NAME_GUIDE3, true);
ed.putBoolean(Constants.BASEIC_SHAREDPREFERENCE_NAME_GUIDE4, true);
ed.putBoolean(Constants.BASEIC_SHAREDPREFERENCE_NAME_GUIDE5, true);
ed.putBoolean(Constants.BASEIC_SHAREDPREFERENCE_NAME_GUIDE6, true);
ed.putBoolean(Constants.BASEIC_SHAREDPREFERENCE_NAME_GUIDE7, true);
ed.putBoolean(Constants.BASEIC_SHAREDPREFERENCE_NAME_GUIDE8, true);
ed.putBoolean(Constants.BASEIC_SHAREDPREFERENCE_NAME_GUIDE9, true);
}
ed.commit();
File file=new File(Constants.Picture_Root_Path);
if(!file.exists()){
file.mkdir();
}
String path=Constants.Picture_Root_Path+File.separator+".nomedia";
File file2=new File(path);
if(file2.exists()){
if(file2.isDirectory())
{
file2.delete();
try {
file2.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}else{
try {
file2.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* 配置ImageLoaderConfiguration
*/
//图片缓存路径
File cacheDir=StorageUtils.getOwnCacheDirectory(getApplicationContext(), "pet/imageloader/cache");
ImageLoaderConfiguration config=new ImageLoaderConfiguration
.Builder(getApplicationContext())
.threadPriority(Thread.NORM_PRIORITY-2)//
.denyCacheImageMultipleSizesInMemory()
.discCache(new UnlimitedDiscCache(cacheDir))
.discCacheSize(100*1024*1024)
.tasksProcessingOrder(QueueProcessingType.LIFO)
// .memoryCacheSize(2*1024*1024)
.threadPoolSize(2)//建议小于5个
// .memoryCache(new WeakMemoryCache())
// .writeDebugLogs()//当应用发布时移出
.build();//构建完成
ImageLoader.getInstance().init(config);
/**
* 环信初始化
*/
/*EMChat.getInstance().setDebugMode(true);
EMChat.getInstance().init(this);*/
setInit(this);
}
/**
* 环信
*/
public static Context applicationContext;
private static Application instance;
// login user name
public final String PREF_USERNAME = "username";
/**
* 当前用户nickname,为了苹果推送不是userid而是昵称
*/
public static String currentUserNick = "";
public static DemoHXSDKHelper hxSDKHelper = new DemoHXSDKHelper();
/**
* by scx
* 初始化,
*/
public static void setInit(Application application){
applicationContext = application;
instance = application;
/**
* this function will initialize the HuanXin SDK
*
* @return boolean true if caller can continue to call HuanXin related APIs after calling onInit, otherwise false.
*
* 环信初始化SDK帮助函数
* 返回true如果正确初始化,否则false,如果返回为false,请在后续的调用中不要调用任何和环信相关的代码
*
* for example:
* 例子:
*
* public class DemoHXSDKHelper extends HXSDKHelper
*
* HXHelper = new DemoHXSDKHelper();
* if(HXHelper.onInit(context)){
* // do HuanXin related work
* }
*/
hxSDKHelper.onInit(applicationContext);
}
public static Application getInstance() {
return instance;
}
/**
* 获取内存中好友user list
*
* @return
*/
public static Map<String, User> getContactList() {
return hxSDKHelper.getContactList();
}
/**
* 设置好友user list到内存中
*
* @param contactList
*/
public static void setContactList(Map<String, User> contactList) {
hxSDKHelper.setContactList(contactList);
}
/**
* 获取当前登陆用户名
*
* @return
*/
public static String getUserName() {
return hxSDKHelper.getHXId();
}
/**
* 获取密码
*
* @return
*/
public static String getPassword() {
return hxSDKHelper.getPassword();
}
/**
* 设置用户名
*
* @param myUser
*/
public static void setUserName(String username) {
hxSDKHelper.setHXId(username);
}
/**
* 设置密码 下面的实例代码 只是demo,实际的应用中需要加password 加密后存入 preference 环信sdk
* 内部的自动登录需要的密码,已经加密存储了
*
* @param pwd
*/
public static void setPassword(String pwd) {
hxSDKHelper.setPassword(pwd);
}
/**
* 退出登录,清空数据
*/
public static void logout(final EMCallBack emCallBack) {
// 先调用sdk logout,在清理app中自己的数据
hxSDKHelper.logout(emCallBack);
}
}
|
package com.xsis.batch197.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import org.springframework.format.annotation.DateTimeFormat;
@Entity
@Table(name = "biodata")
public class BiodataModel {
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "biodata_seq")
@TableGenerator(name = "biodata_seq", table = "tbl_sequences", pkColumnName = "seq_id", valueColumnName = "seq_value", initialValue = 0, allocationSize = 1)
@Column(name = "id")
private int id;
// "namaLengkap" digunakan untuk memanggil data menggunakan th:text="${item.namaLengkap}
@Column(name = "nama_lengkap", length = 100)
private String namaLengkap;
@Column(name = "alamat", length = 225)
private String alamat;
@Column(name = "tempat_lahir", length = 50)
private String tempatLahir;
@Column(name = "tanggal_lahir", length = 100)
@Temporal(TemporalType.DATE)
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date tanggalLahir;
@Column(name = "agama", length = 10)
private String agama;
@Column(name = "jenis_kelamin", length = 10)
private String jk;
@Column(name = "golongan_darah", length = 2)
private String golDarah;
@Column(name = "kendaraan", length = 1000)
private String kendaraan;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNamaLengkap() {
return namaLengkap;
}
public void setNamaLengkap(String namaLengkap) {
this.namaLengkap = namaLengkap;
}
public String getAlamat() {
return alamat;
}
public void setAlamat(String alamat) {
this.alamat = alamat;
}
public String getTempatLahir() {
return tempatLahir;
}
public void setTempatLahir(String tempatLahir) {
this.tempatLahir = tempatLahir;
}
public Date getTanggalLahir() {
return tanggalLahir;
}
public void setTanggalLahir(Date tanggalLahir) {
this.tanggalLahir = tanggalLahir;
}
public String getAgama() {
return agama;
}
public void setAgama(String agama) {
this.agama = agama;
}
public String getJk() {
return jk;
}
public void setJk(String jk) {
this.jk = jk;
}
public String getGolDarah() {
return golDarah;
}
public void setGolDarah(String golDarah) {
this.golDarah = golDarah;
}
public String getKendaraan() {
return kendaraan;
}
public void setKendaraan(String kendaraan) {
this.kendaraan = kendaraan;
}
}
|
package com.infoworks.lab.components.rest;
import com.infoworks.lab.rest.models.ItemCount;
import com.infoworks.lab.rest.repository.RestRepository;
import com.it.soul.lab.sql.entity.Entity;
import com.it.soul.lab.sql.query.*;
import com.it.soul.lab.sql.query.builder.AbstractQueryBuilder;
import com.it.soul.lab.sql.query.models.Row;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
public class RestRepositoryExecutor extends AbstractRestExecutor{
private final RestRepository repository;
private int maxCount;
private static Logger LOG = Logger.getLogger(RestRepositoryExecutor.class.getSimpleName());
public RestRepositoryExecutor(RestRepository repository) {
this.repository = repository;
}
protected RestRepository getRepository() {
return repository;
}
public int getMaxCount() {
return maxCount;
}
@Override
public AbstractQueryBuilder createQueryBuilder(QueryType queryType) {
return new SQLQuery.Builder(queryType);
}
@Override
public Integer executeInsert(boolean b, SQLInsertQuery sqlInsertQuery) throws SQLException, IllegalArgumentException {
try {
Entity request = (Entity) sqlInsertQuery.getRow().inflate(getRepository().getEntityType());
Entity created = getRepository().insert(request);
return created != null ? 1 : 0;
} catch (RuntimeException e) {
throw new SQLException(e.fillInStackTrace());
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(e.fillInStackTrace());
} catch (InstantiationException e) {
throw new IllegalArgumentException(e.fillInStackTrace());
}
}
@Override
public Integer executeUpdate(SQLUpdateQuery sqlUpdateQuery) throws SQLException {
try {
Entity request = (Entity) sqlUpdateQuery.getRow().inflate(getRepository().getEntityType());
Row row = sqlUpdateQuery.getWhereProperties();
Map kvo = row.keyObjectMap();
Object id = kvo.get(getRepository().getPrimaryKeyName());
Entity updated = getRepository().update(request, id);
return updated != null ? 1 : 0;
} catch (RuntimeException e) {
throw new SQLException(e.fillInStackTrace());
} catch (InstantiationException e) {
throw new IllegalArgumentException(e.fillInStackTrace());
} catch (IllegalAccessException e) {
throw new IllegalArgumentException(e.fillInStackTrace());
}
}
@Override
public Integer executeDelete(SQLDeleteQuery sqlDeleteQuery) throws SQLException {
try {
Row row = sqlDeleteQuery.getWhereProperties();
Map kvo = row.keyObjectMap();
Object id = kvo.get(getRepository().getPrimaryKeyName());
boolean isDeleted = getRepository().delete(id);
LOG.info("Is Deleted: " + isDeleted);
return isDeleted ? 1 : 0;
} catch (RuntimeException e) {
throw new SQLException(e.fillInStackTrace());
}
}
@Override
public Integer getScalarValue(SQLScalarQuery sqlScalarQuery) throws SQLException {
try {
ItemCount count = getRepository().rowCount();
maxCount = count.getCount().intValue();
} catch (RuntimeException e) {
throw new SQLException(e.fillInStackTrace());
}
return maxCount;
}
@Override
public <T> List<T> executeSelect(SQLSelectQuery sqlSelectQuery, Class<T> aClass, Map<String, String> map) throws SQLException, IllegalArgumentException, IllegalAccessException, InstantiationException {
try {
int limit = sqlSelectQuery.getLimit();
int offset = sqlSelectQuery.getOffset();
int page = offset / limit;
if (offset > maxCount) return new ArrayList();
LOG.info(String.format("Offset:%s, Limit:%s, Page:%s", offset, limit, page));
List returned = getRepository().fetch(page, limit);
return returned;
} catch (RuntimeException e) {
throw new SQLException(e.fillInStackTrace());
}
}
}
|
package com.haku.light.scene.gui;
import com.haku.jlm.matrix.Mat4f;
import com.haku.jlm.matrix.Mat4fStack;
import com.haku.light.Light;
import com.haku.light.assets.impl.Shader;
import com.haku.light.assets.impl.Texture;
import com.haku.light.assets.impl.font.BitmapFont;
import com.haku.light.graphics.Color;
import com.haku.light.graphics.g2d.TextMesh;
public class TextView extends View {
private final float[] auxColor = new float[4];
private final TextMesh mesh;
public int fontColor = Color.WHITE;
public String fontName;
public TextView() {
this("");
}
public TextView(String text) {
this(text, BitmapFont.DEFAULT_FONT);
}
public TextView(String text, String fontName) {
BitmapFont font = Light.assets.get(fontName);
if (font != null) this.mesh = font.getTextMesh(text);
else this.mesh = null;
this.fontName = fontName;
}
@Override
public void onUpdate() {
//this.mesh.setMaxWidth(this.parent.getWidth());
super.onUpdate();
}
@Override
public void onRender(Shader shader, Mat4fStack modelStack) {
super.onRender(shader, modelStack);
BitmapFont bmFont = Light.assets.get(this.fontName);
Texture t = bmFont.texture;
Mat4f model = modelStack.push();
model.trn(this.x + this.style.paddingLeft,
this.y + this.style.paddingBottom, 0);
model.setScl(1, 1, 1);
Color.toFloats(this.fontColor, this.auxColor);
shader.setFloat("color", this.auxColor);
shader.setBoolean("hasTexture", true);
shader.setMatrix("model", model);
t.bind();
this.mesh.render(shader.gl);
t.unbind();
shader.setBoolean("hasTexture", false);
modelStack.pop();
}
@Override
public int getContentWidth() {
return (int) this.mesh.getWidth();
}
@Override
public int getContentHeight() {
return (int) this.mesh.getHeight();
}
public void setText(String text) {
this.mesh.setText(text);
this.parent.onUpdate();
}
public String getText() {
return this.mesh.getText();
}
}
|
/**
* Copyright (C) 2008 Atlassian
*
* 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.atlassian.theplugin.idea.config.serverconfig.model;
import com.atlassian.theplugin.commons.ServerType;
import com.atlassian.theplugin.commons.cfg.ServerCfg;
import javax.swing.tree.DefaultMutableTreeNode;
public class ServerNode extends DefaultMutableTreeNode {
private final ServerCfg server;
public ServerNode(ServerCfg aServer) {
this.server = aServer;
}
public ServerType getServerType() {
return server.getServerType();
}
public ServerCfg getServer() {
return server;
}
/**
* Used ultimately by {@link javax.swing.tree.DefaultTreeCellRenderer}. so it must be like this
* Sorry :(
*
* @return server name
*/
@Override
public String toString() {
return server.getName();
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ServerNode that = (ServerNode) o;
if (!server.equals(that.server)) {
return false;
}
return true;
}
public int hashCode() {
return server.hashCode();
}
}
|
package com.cs.test_rxjava;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import java.util.concurrent.TimeUnit;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
/*
使用的时候可以把注释去掉,看LOG就行,建议手动写一下并结合文档会比较好理解
*/
public class MainActivity extends AppCompatActivity {
private String [] names={"大哥","小弟","大侠"};
private String [][] seats={{"01","12"},{"22","33"},{"44","55","33"}};
private String [] number={"0","1","1","2","2","3","3","4","5"};
private final String TAG="TAG";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//getObservabla();//最简单观察者模式 actiona
//simpleObservable();//just关键字
//observablejust();//repeat重复发射的消息
//observablerange();//range 变成for循环发消息
//observablerepeat();
//observerableThead()://Schedulers真正的实现线程之间的切换
//observablemap();//map字符类型转换
//obserablefrom();//from读取数组list等集合
//observableflatmap();//flatmap是比较难理解的,
//observablefilter();//filter过滤的一个效果
// observabletake();//take选择需要的元素符号,从0开始选择,类似的还有takeLast,takeFirst
//observabletakelast();//和take差不多
//observabledistinct();//disdtinct去掉重复的content,有点像set集合
//observableChange();//看注释吧
//observablefirst();//first第一个去发送消息,从last同理;
//observableSkip();//skip和skiplast是跳过,从0开始计数,不解释
//observabletimmer();//timer的使用 和interval区别下
}
private void observabletimmer() {
Observable.just(22, 23, 22, 22, 24).timer(3000, TimeUnit.MILLISECONDS).subscribe(new Action1<Long>() {
@Override
public void call(Long aLong) {
Log.d(TAG,"隔了几秒收到:"+aLong);//along的参数是0
}
});
}
private void observableSkip() {
Observable.just(22,23,22,22,24).skip(2).subscribe(new Action1<Integer>() {
@Override//当数据变化时会调用,这个方法到是挺好的,不过不是很清楚怎么去调用呢
public void call(Integer integer) {
Log.d(TAG,"当前的温度为"+integer);
}
});
}
private void observablefirst() {
Observable.just(22,23,22,22,24).first().subscribe(new Action1<Integer>() {
@Override//当数据变化时会调用,这个方法到是挺好的,不过不是很清楚怎么去调用呢
public void call(Integer integer) {
Log.d(TAG,"当前的温度为"+integer);
}
});
}
private void observableChange() {
Observable.just(22,23,22,22,24).distinctUntilChanged().subscribe(new Action1<Integer>() {
@Override//当数据变化时会调用,这个方法到是挺好的,不过不是很清楚怎么去调用呢
public void call(Integer integer) {
Log.d(TAG,"当前的温度为"+integer);
}
});
}
private void observabledistinct() {
Observable.from(number).distinct().subscribe(new Action1<String>() {
@Override
public void call(String s) {
Log.d(TAG,"当前数字"+s);
}
});
}
private void observabletakelast() {
Observable.just(0,1,2,3,4,4,5,6).takeLast(4).subscribe(new Action1<Integer>() {
@Override
public void call(Integer integer) {
Log.d(TAG,"当前的数字为:"+integer);
}
});
}
private void observabletake() {
Observable.just(0,1,2,3,4,4,5,6).take(4).subscribe(new Action1<Integer>() {
@Override
public void call(Integer integer) {
Log.d(TAG,"当前的数字为:"+integer);
}
});
}
private void observablefilter() {
Observable.just(0,1,1,3,3,4,5,6,4).filter(new Func1<Integer, Boolean>() {
@Override//FUNcl里面的参数第一个是Integer,第二个是我得命令,可进行拓张
public Boolean call(Integer integer) {
return integer>1 && integer>3;
}
}).subscribe(new Action1<Integer>() {
@Override
public void call(Integer integer) {
Log.d(TAG,"当前数字为"+integer);
}
});
}
private void observableflatmap() {
Action1<String> action1 = new Action1<String>() {
@Override
public void call(String s) {
Log.d(TAG,"当前座位号是"+s);
}
};
Observable.from(seats).flatMap(new Func1<String[], Observable<String >>() {
@Override//flatMap好难理解,遍历二维数组
public Observable<String > call(String[] strings) {
return Observable.from(strings);
}
}).subscribe(action1);
}
private void obserablefrom() {
Observable.from(names).map(new Func1<String, String >() {
@Override
public String call(String s) {
return s+"sss";
}
}).subscribe(new Action1<String>() {
@Override//from就是支持数组
public void call(String s) {
Log.d(TAG, "我的名字是:"+s);
}
});
}
private void observablemap() {
Action1<String> action1 = new Action1<String>() {
@Override
public void call(String s) {
Log.d(TAG, "你被调用了"+s);
}
};
//map是类型转换
Observable.just(1,2,3,4).repeat(2).map(new Func1<Integer, String >() {
@Override//funcl第一个数据是前面的,后面的S的
public String call(Integer integer) {
return integer.toString()+2;//数据的可拓展性好强啊
}
}).subscribe(action1);
}
private void observerableThead() {
Observable<String > observable = Observable.create(new Observable.OnSubscribe<String >() {
@Override
public void call(Subscriber<? super String> subscriber) {
Log.d(TAG, "你被调用了"+Thread.currentThread().getName());
subscriber.onNext("你被调用了"+Thread.currentThread().getName());
}
});
Subscriber<String> subscriber = new Subscriber<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
Log.d(TAG,"你有什么丰富"+Thread.currentThread().getName());
}
};
//Schedulers.newThread()
// 子线程//Schedulers.immediate()
//Schedulers.io()读写文件的适合,或者网络,读取文件等耗时操作
//Schedulers.computation()适合计算操作,与cpu有关
observable.observeOn(Schedulers.computation()).subscribe(subscriber);
}
private void observablerepeat() {
Observable.just(1,2,3,4,5).repeat(3).subscribe(new Action1<Integer>() {
@Override//重复执行几次
public void call(Integer integer) {
Log.d(TAG, integer + "");
}
});
}
private void observablerange() {
Observable.range(0, 10).subscribe(new Action1<Integer>() {
@Override//变成for循环了
public void call(Integer integer) {
Log.d(TAG, integer + "");
}
});
}
private void observablejust() {
Observable.just(0,1,2,3,4,5).subscribe(new Action1<Integer>() {
@Override
public void call(Integer integer) {
Log.d(TAG,integer+"");
}
});
}
private void simpleObservable() {
//这里应该是用户
Observable<String> observable = Observable.just("我只要大块的肉");
//开发者或者我们需要程序去做的事情
observable.subscribe(new Action1<String>() {
@Override
public void call(String s) {
Log.d(TAG,s);
}
});
}
private void getObservabla() {
//观察者 顾客
Subscriber<String> subscriber=new Subscriber<String >(){
@Override
public void onNext(String s) {
Log.d(TAG,s);
}
@Override
public void onCompleted() {
Log.d(TAG,"onCompleted");
}
@Override
public void onError(Throwable t) {
}
};
//Observable 即被观察者 老板娘
Observable observable = Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
subscriber.onNext("去拿一大碗米饭");
subscriber.onCompleted();
}
});
observable.subscribe(subscriber);
}
}
|
package dw.game;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.nio.FloatBuffer;
import java.nio.file.Files;
import java.util.ArrayList;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20;
public class Shader {
private String name;
private int program;
private int vertex;
private int fragment;
public Shader(String name) {
this.name = name;
program = GL20.glCreateProgram();
vertex = getShader(name + ".vert", GL20.GL_VERTEX_SHADER);
fragment = getShader(name + ".frag", GL20.GL_FRAGMENT_SHADER);
GL20.glAttachShader(program, vertex);
GL20.glAttachShader(program, fragment);
GL20.glLinkProgram(program);
if (GL20.glGetProgrami(program, GL20.GL_LINK_STATUS) == GL11.GL_FALSE) {
System.out.println("Program '" + name + "' failed to link.");
int length = GL20.glGetShaderi(program, GL20.GL_INFO_LOG_LENGTH);
System.out.println(GL20.glGetProgramInfoLog(program, length));
}
GL20.glValidateProgram(program);
}
public static void loadShaders(ArrayList<Shader> shaders) {
shaders = new ArrayList<Shader>();
shaders.add(new Shader("basic"));
}
public void activate() {
GL20.glUseProgram(program);
}
public void deactivate() {
GL20.glUseProgram(0);
}
public void clear() {
GL20.glDetachShader(program, vertex);
GL20.glDetachShader(program, fragment);
GL20.glDeleteShader(vertex);
GL20.glDeleteShader(fragment);
GL20.glDeleteProgram(program);
}
public void setInt(String variable, int value) {
int location = GL20.glGetUniformLocation(program, variable);
if (location != -1) {
GL20.glUniform1i(location, value);
} else {
System.out.println("Variable '" + variable + "' not found in '" + name + "' shader!");
}
}
public void setFloat(String variable, float value) {
int location = GL20.glGetUniformLocation(program, variable);
if (location != -1) {
GL20.glUniform1f(location, value);
} else {
System.out.println("Variable '" + variable + "' not found in '" + name + "' shader!");
}
}
public void setDouble(String variable, float value) {
int location = GL20.glGetUniformLocation(program, variable);
if (location != -1) {
GL20.glUniform1f(location, value);
} else {
System.out.println("Variable '" + variable + "' not found in '" + name + "' shader!");
}
}
public void setBoolean(String variable, boolean value) {
int location = GL20.glGetUniformLocation(program, variable);
if (location != -1) {
GL20.glUniform1i(location, value ? 1 : 0);
} else {
System.out.println("Variable '" + variable + "' not found in '" + name + "' shader!");
}
}
public void setVector2(String variable, float x, float y) {
int location = GL20.glGetUniformLocation(program, variable);
if (location != -1) {
GL20.glUniform2f(location, x, y);
} else {
System.out.println("Variable '" + variable + "' not found in '" + name + "' shader!");
}
}
public void setVector3(String variable, float x, float y, float z) {
int location = GL20.glGetUniformLocation(program, variable);
if (location != -1) {
GL20.glUniform3f(location, x, y, z);
} else {
System.out.println("Variable '" + variable + "' not found in '" + name + "' shader!");
}
}
public void setMatrix(String variable, Matrix4f matrix) {
int location = GL20.glGetUniformLocation(program, variable);
if (location != -1) {
GL20.glUniformMatrix4fv(location, false, storeInBuffer(matrix));
} else {
System.out
.println("Variable '" + variable + "' not found in '" + name + "' shader!");
}
}
private FloatBuffer storeInBuffer(Matrix4f matrix) {
FloatBuffer buffer = org.lwjgl.BufferUtils.createFloatBuffer(16);
matrix.get(buffer);
return buffer;
}
private String getSource(String name) {
StringBuilder source = new StringBuilder();
File file = new File("src/assets/shaders/" + name);
if (!file.exists()) {
System.out.println(
"Unable to get access to file 'src/assets/shaders/" + name + "'");
}
try {
BufferedReader reader = Files.newBufferedReader(file.toPath());
String line = reader.readLine();
do {
if (line == null)
break;
source.append(line).append("\n");
line = reader.readLine();
} while (line != null);
} catch (IOException e) {
System.out.println(e.getMessage());
}
return source.toString();
}
private int getShader(String name, int type) {
int id = GL20.glCreateShader(type);
GL20.glShaderSource(id, getSource(name).toString());
GL20.glCompileShader(id);
if (GL20.glGetShaderi(id, GL20.GL_COMPILE_STATUS) != GL11.GL_TRUE) {
int length = GL20.glGetShaderi(id, GL20.GL_INFO_LOG_LENGTH);
System.out.println(GL20.glGetShaderInfoLog(id, length));
}
return id;
}
}
|
package servicenow.api;
import org.junit.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import servicenow.api.KeySet;
import servicenow.api.Session;
import servicenow.api.Table;
import static org.junit.Assert.*;
import java.io.IOException;
@RunWith(Parameterized.class)
public class GetKeysTest {
String profile;
Session session;
@Parameters(name = "{index}:{0}")
public static String[] profiles() {
return new String[] {"mydevsoap", "mydevjson"};
}
public GetKeysTest(String profile) {
this.profile = profile;
TestingManager.loadProfile(profile);
session = new Session(TestingManager.getProperties());
}
@Test
public void testAllKeys() throws IOException {
Table inc = session.table("cmn_department");
KeySet keys = null;
if (profile.equals("mydevsoap")) keys = inc.soap().getKeys();
if (profile.equals("mydevjson")) keys = inc.json().getKeys();
assertNotNull(keys);
assertTrue("keys.size() must be greater than 0", keys.size() > 0);
}
}
|
package org.minbox.framework.little.bee.core.tools;
import java.io.*;
/**
* File manipulation tools
*
* @author 恒宇少年
*/
public class FileTools {
/**
* Create a directory
*
* @param dirPath directory path
*/
public static void createDirectory(String dirPath) {
File file = new File(dirPath);
if (!file.exists()) {
file.mkdirs();
}
}
/**
* Create a new file
*
* @param filePath The file full path
* @param isCreateParentDir Whether to create the parent folder of the file,created when true
* @throws IOException File io exception
*/
public static void createFile(String filePath, boolean isCreateParentDir) throws IOException {
File file = new File(filePath);
if (isCreateParentDir) {
File fileParentDir = new File(file.getParent());
if (!fileParentDir.exists()) {
fileParentDir.mkdirs();
}
}
file.createNewFile();
}
/**
* Append line to the end of the file
*
* @param filePath The file full path
* @param line line content
* @throws IOException File io exception
*/
public static void writeLine(String filePath, String line) throws IOException {
writeLines(filePath, line);
}
/**
* Append lines to the end of the file
*
* @param filePath The file full path
* @param lines line content array
* @throws IOException File io exception
*/
public static void writeLines(String filePath, String... lines) throws IOException {
if (ObjectTools.isEmpty(lines)) {
return;
}
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, true)));
for (String line : lines) {
writer.write(line);
}
} catch (IOException e) {
throw e;
} finally {
try {
writer.close();
} catch (IOException e) {
throw e;
}
}
}
/**
* Check file or directory exist
*
* @param filePath file or directory path
* @return Return true if present
*/
public static boolean checkExist(String filePath) {
File file = new File(filePath);
return file.exists();
}
}
|
package com.gxjtkyy.standardcloud.common.utils;
/**
* 文档类型工具类
* @Package com.gxjtkyy.utils
* @Author lizhenhua
* @Date 2018/5/29 18:47
*/
public class DocTypeUtil {
}
|
package ethan.mobilecount;
import java.util.Date;
import java.util.Random;
/**
* @since 2013-11-1
* @author ethan
*/
public class CommonCustomer extends Customer {
public CommonCustomer(String name, Date join) {
super(name, join, 0);
packStrategy = new PackStrategy(0, 0, new Rent(0, TimeUnit.DAY));
}
public void randomCancelPack(Date orderedMonth){
int rand = new Random().nextInt(3);
switch(rand){
case 0:
/*if(packStrategy.getOrderedPhonePack() == null || packStrategy.getOrderedPhonePack().getPackType() == 0){
System.out.println(name + "试图退订根本就没有订过的电话套餐");
return;
}*/
packStrategy.cancelPhonePack(orderedMonth);
System.out.println(name + "退订了" + "电话套餐" + "(从" + DataUtil.formatToMonth(orderedMonth) + "开始)");
actions.add(new Recorder("退订电话套餐",""));
break;
case 1:
/*if(packStrategy.getOrderedMessagePack() ==null || packStrategy.getOrderedMessagePack().getPackType() == 0){
System.out.println(name + "试图退订根本就没有订过的短信套餐");
return;
}*/
packStrategy.cancelMessagePack(orderedMonth);
System.out.println(name + "退订了" + "短信套餐" + "(从" + DataUtil.formatToMonth(orderedMonth) + "开始)");
actions.add(new Recorder("退订短信套餐",""));
break;
case 2:
/* if(packStrategy.getOrderedDataPack()==null || packStrategy.getOrderedDataPack().getPackType() == 0){
System.out.println(name + "试图退订根本就没有订过的数据套餐");
return;
} */
packStrategy.cancelDataPack(orderedMonth);
System.out.println(name + "退订了" + "数据套餐" + "(从" + DataUtil.formatToMonth(orderedMonth) + "开始)");
actions.add(new Recorder("退订数据套餐",""));
break;
}
}
public void randomOrderPack(Date month){
int rand = new Random().nextInt(3);
switch(rand){
case 0:
//if(packStrategy.getOrderedPhonePack()==null || packStrategy.getOrderedPhonePack().getPackType() == 0){
packStrategy.orderPhonePack(month,1);
System.out.println(name + "订购了" + "电话套餐" + "(从" + DataUtil.formatToMonth(month) + "开始)");
actions.add(new Recorder("定电话套餐",""));
//}
break;
case 1:
//if(packStrategy.getOrderedMessagePack() == null || packStrategy.getOrderedMessagePack().getPackType() == 0){
packStrategy.orderMessagePack(month,1);
System.out.println(name + "订购了" + "短信套餐" + "(从" + DataUtil.formatToMonth(month) + "开始)");
actions.add(new Recorder("定短信套餐",""));
//}
break;
case 2:
//if(packStrategy.getOrderedDataPack() == null || packStrategy.getOrderedDataPack().getPackType() == 0){
packStrategy.orderDataPack(month,1);
System.out.println(name + "订购了" + "数据套餐" + "(从" + DataUtil.formatToMonth(month) + "开始)");
actions.add(new Recorder("定数据套餐",""));
//}
break;
}
}
}
|
/**
*
*/
package com.fixit.core.data.mongo;
import org.bson.types.ObjectId;
import com.fixit.core.data.UpdateDateDataModelObject;
/**
* @author Kostyantin
* @createdAt 2017/03/31 16:56:03 GMT+3
*/
public interface UpdateDateMongoModelObject extends MongoModelObject, UpdateDateDataModelObject<ObjectId> {
}
|
package boletin_6_5;
public class Comparacion {
public static void comparacion(Numero num1, Numero num2, Numero num3){
if (num1.getNum() > num2.getNum()){
if (num1.getNum() > num3.getNum()){
System.out.println("El segundo número es el mayor");
}
else{
System.out.println("El tercer número es el mayor");
}
}
else{
if (num2.getNum() > num3.getNum()){
System.out.println("El segundo número es el mayor");
}
else{
System.out.println("El tercer número es el mayor");
}
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.ut.healthelink.model;
import com.ut.healthelink.validator.NoHtml;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.springframework.format.annotation.DateTimeFormat;
/**
*
* @author chadmccue
*/
@Entity
@Table(name = "BATCHUPLOADS")
public class batchUploads {
@Transient
private Integer totalTransactions = 0;
@Transient
private String statusValue;
@Transient
private String usersName;
@Transient
private String orgName;
@Transient
private String transportMethod;
@Transient
private String configName;
@Transient
private Integer transTotalNotFinal = 10; // set to random number that is not 0
@Transient
private String uploadType = "";
@Transient
private String referringBatch = "";
@Transient
private Integer totalOpen = 0;
@Transient
private Integer totalClosed = 0;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID", nullable = false)
private int id;
@Column(name = "ORGID", nullable = false)
private int orgId;
@Column(name = "PROVIDERID", nullable = true)
private int providerId = 0;
@Column(name = "USERID", nullable = false)
private int userId;
@Column(name = "UTBATCHCONFNAME", nullable = true)
private String utBatchConfName = null;
@Column(name = "UTBATCHNAME", nullable = false)
private String utBatchName;
@Column(name = "TRANSPORTMETHODID", nullable = false)
private int transportMethodId;
@NoHtml
@Column(name = "ORIGINALFILENAME", nullable = false)
private String originalFileName;
@Column(name = "STATUSID", nullable = false)
private int statusId;
@Column(name = "STARTDATETIME", nullable = true)
private Date startDateTime = null;
@Column(name = "ENDDATETIME", nullable = true)
private Date endDateTime = null;
@Column(name = "TOTALRECORDCOUNT", nullable = false)
private int totalRecordCount = 0;
@Column(name = "DELETED", nullable = false)
private boolean deleted = false;
@Column(name = "ERRORRECORDCOUNT", nullable = false)
private int errorRecordCount = 0;
@DateTimeFormat(pattern = "dd/MM/yyyy hh:mm:ss")
@Column(name = "DATESUBMITTED", nullable = false)
private Date dateSubmitted = new Date();
@Column(name = "configId", nullable = true)
private Integer configId;
@Column(name = "CONTAINSHEADERROW", nullable = false)
private boolean containsHeaderRow = false;
@Column(name = "delimChar", nullable = true)
private String delimChar;
@Column(name = "fileLocation", nullable = true)
private String fileLocation;
@NoHtml
@Column(name = "originalFolder", nullable = false)
private String originalFolder;
@Column(name = "encodingId", nullable = true)
private Integer encodingId = 1;
@NoHtml
@Column(name = "senderEmail", nullable = false)
private String senderEmail;
public boolean isContainsHeaderRow() {
return containsHeaderRow;
}
public void setContainsHeaderRow(boolean containsHeaderRow) {
this.containsHeaderRow = containsHeaderRow;
}
public String getFileLocation() {
return fileLocation;
}
public void setFileLocation(String fileLocation) {
this.fileLocation = fileLocation;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getOrgId() {
return orgId;
}
public void setOrgId(int orgId) {
this.orgId = orgId;
}
public int getproviderId() {
return providerId;
}
public void setproviderId(int providerId) {
this.providerId = providerId;
}
public int getuserId() {
return userId;
}
public void setuserId(int userId) {
this.userId = userId;
}
public String getutBatchConfName() {
return utBatchConfName;
}
public void setutBatchConfName(String utBatchConfName) {
this.utBatchConfName = utBatchConfName;
}
public String getutBatchName() {
return utBatchName;
}
public void setutBatchName(String utBatchName) {
this.utBatchName = utBatchName;
}
public int gettransportMethodId() {
return transportMethodId;
}
public void settransportMethodId(int transportMethodId) {
this.transportMethodId = transportMethodId;
}
public String getoriginalFileName() {
return originalFileName;
}
public void setoriginalFileName(String originalFileName) {
this.originalFileName = originalFileName;
}
public int getstatusId() {
return statusId;
}
public void setstatusId(int statusId) {
this.statusId = statusId;
}
public Date getstartDateTime() {
return startDateTime;
}
public void setstartDateTime(Date startDateTime) {
this.startDateTime = startDateTime;
}
public Date getendDateTime() {
return endDateTime;
}
public void setendDateTime(Date endDateTime) {
this.endDateTime = endDateTime;
}
public int gettotalRecordCount() {
return totalRecordCount;
}
public void settotalRecordCount(int totalRecordCount) {
this.totalRecordCount = totalRecordCount;
}
public boolean getdeleted() {
return deleted;
}
public void setdeleted(boolean deleted) {
this.deleted = deleted;
}
public int geterrorRecordCount() {
return errorRecordCount;
}
public void seterrorRecordCount(int errorRecordCount) {
this.errorRecordCount = errorRecordCount;
}
public Date getdateSubmitted() {
return dateSubmitted;
}
public void settotalTransactions(int totalTransactions) {
this.totalTransactions = totalTransactions;
}
public int gettotalTransactions() {
return totalTransactions;
}
public String getstatusValue() {
return statusValue;
}
public void setstatusValue(String statusValue) {
this.statusValue = statusValue;
}
public String getusersName() {
return usersName;
}
public void setusersName(String usersName) {
this.usersName = usersName;
}
public Integer getConfigId() {
return configId;
}
public void setConfigId(Integer configId) {
this.configId = configId;
}
public String getDelimChar() {
return delimChar;
}
public void setDelimChar(String delimChar) {
this.delimChar = delimChar;
}
public String getorgName() {
return orgName;
}
public void setorgName(String orgName) {
this.orgName = orgName;
}
public String gettransportMethod() {
return transportMethod;
}
public void settransportMethod(String transportMethod) {
this.transportMethod = transportMethod;
}
public String getConfigName() {
return configName;
}
public void setConfigName(String configName) {
this.configName = configName;
}
public Integer getTransTotalNotFinal() {
return transTotalNotFinal;
}
public void setTransTotalNotFinal(Integer transTotalNotFinal) {
this.transTotalNotFinal = transTotalNotFinal;
}
public String getOriginalFolder() {
return originalFolder;
}
public void setOriginalFolder(String originalFolder) {
this.originalFolder = originalFolder;
}
public Integer getEncodingId() {
return encodingId;
}
public void setEncodingId(Integer encodingId) {
this.encodingId = encodingId;
}
public String getSenderEmail() {
return senderEmail;
}
public void setSenderEmail(String senderEmail) {
this.senderEmail = senderEmail;
}
public String getUploadType() {
return uploadType;
}
public void setUploadType(String uploadType) {
this.uploadType = uploadType;
}
public String getReferringBatch() {
return referringBatch;
}
public void setReferringBatch(String referringBatch) {
this.referringBatch = referringBatch;
}
public Integer getTotalOpen() {
return totalOpen;
}
public void setTotalOpen(Integer totalOpen) {
this.totalOpen = totalOpen;
}
public Integer getTotalClosed() {
return totalClosed;
}
public void setTotalClosed(Integer totalClosed) {
this.totalClosed = totalClosed;
}
}
|
package com.artogrid.bundle.sync.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class SyncBondOfferMethodDTO implements java.io.Serializable{
List<SyncBondOfferDTO> bondOffer ;
/**
* @return the bondOffer
*/
public List<SyncBondOfferDTO> getBondOffer() {
return bondOffer;
}
/**
* @param bondOffer the bondOffer to set
*/
public void setBondOffer(List<SyncBondOfferDTO> bondOffer) {
this.bondOffer = bondOffer;
};
public void add(SyncBondOfferDTO dto){
if(bondOffer==null){
bondOffer=new ArrayList<SyncBondOfferDTO>();
}
bondOffer.add(dto);
}
}
|
package com.atomix.sidrapulse;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.util.Linkify;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import com.atomix.adapter.OfferPromotionAdapter;
import com.atomix.adapter.ViewPagerAdapter;
import com.atomix.customview.SidraTextView;
import com.atomix.interfacecallback.UnReadRequest;
import com.atomix.internetconnection.InternetConnectivity;
import com.atomix.sidrainfo.ConstantValues;
import com.atomix.sidrainfo.SidraPulseApp;
import com.atomix.synctask.FavoriateOrNotAsyncTask;
import com.atomix.utils.Utilities;
public class OffersPromotionsDetailsActivity extends Activity implements OnClickListener {
private Button btnBack;
private Button btnMenu;
private SidraTextView txtViewHeadLine;
private SidraTextView txtViewDate;
private ImageView imgViewFavorite;
private SidraTextView txtViewDescription;
private SidraTextView txtViewTitle;
private SidraTextView txtViewDateField;
private int position;
private ViewPager viewPager;
private LinearLayout linearIndicatorLayout;
private boolean isPathLocal = false;
private String id;
private int isBookMarked;
private int isBookMarkedFirstTime;
private RelativeLayout relativeImageHolder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_offers_promotions_details);
initViews();
setListener();
loadData();
}
private void loadData() {
if(getIntent().getExtras() != null) {
position = getIntent().getExtras().getInt("click_position");
id = Integer.toString(SidraPulseApp.getInstance().getOfferPromotionInfoList().get(position).getId());
isBookMarked = SidraPulseApp.getInstance().getOfferPromotionInfoList().get(position).getIsBookmarked();
isBookMarkedFirstTime = isBookMarked;
//txtViewHeadLine.setText("This is Static Headline");
txtViewTitle.setText(SidraPulseApp.getInstance().getOfferPromotionInfoList().get(position).getTitle());
txtViewDescription.setText(SidraPulseApp.getInstance().getOfferPromotionInfoList().get(position).getDescription());
Log.e("Long term offer is","" + SidraPulseApp.getInstance().getOfferPromotionInfoList().get(position).getLongTerm());
if(SidraPulseApp.getInstance().getOfferPromotionInfoList().get(position).getIsBookmarked() == 1) {
imgViewFavorite.setBackgroundResource(R.drawable.star_icon);
} else {
imgViewFavorite.setBackgroundResource(R.drawable.star_gray_icon);
}
if(SidraPulseApp.getInstance().getOfferPromotionInfoList().get(position).getLongTerm() != 1) {
txtViewDate.setVisibility(View.VISIBLE);
txtViewDate.setText(SidraPulseApp.getInstance().getOfferPromotionInfoList().get(position).getValidUntil());
} else {
txtViewDateField.setText("Always available");
txtViewDate.setVisibility(View.INVISIBLE);
}
Linkify.addLinks(txtViewTitle, Linkify.ALL);
Linkify.addLinks(txtViewDescription, Linkify.ALL);
}
ArrayList<HashMap<String, String>> mediaList = new ArrayList<HashMap<String, String>>();
if(SidraPulseApp.getInstance().getOfferPromotionInfoList().get(position).getPhotoArray() != null) {
for(int j = 0; j < SidraPulseApp.getInstance().getOfferPromotionInfoList().get(position).getPhotoArray().size(); j++) {
ImageView image = new ImageView(OffersPromotionsDetailsActivity.this);
image.setBackgroundResource(R.drawable.circle);
image.setTag(j);
linearIndicatorLayout.addView(image);
}
linearIndicatorLayout.findViewWithTag(0).setBackgroundResource(R.drawable.circle_selected);
for(int count = 0; count < SidraPulseApp.getInstance().getOfferPromotionInfoList().get(position).getPhotoArray().size(); count++) {
HashMap<String, String> map1 = new HashMap<String, String>();
map1.put("url", SidraPulseApp.getInstance().getOfferPromotionInfoList().get(position).getPhotoArray().get(count).getPhoto());
mediaList.add(map1);
}
}else {
HashMap<String, String> map1 = new HashMap<String, String>();
map1.put("url", SidraPulseApp.getInstance().getOfferPromotionInfoList().get(position).getCompanyThumb());
mediaList.add(map1);
}
viewPager.setAdapter(new ViewPagerAdapter(OffersPromotionsDetailsActivity.this, mediaList, isPathLocal, true, 3));
}
private void initViews() {
relativeImageHolder = (RelativeLayout) findViewById(R.id.relative_image_holder);
btnBack = (Button) findViewById(R.id.btn_back);
btnMenu = (Button) findViewById(R.id.btn_menu);
imgViewFavorite = (ImageView) findViewById(R.id.img_view_favorite_or_not);
//txtViewHeadLine = (SidraTextView) findViewById(R.id.txt_view_title);
txtViewDate = (SidraTextView) findViewById(R.id.txt_view_date);
txtViewDescription = (SidraTextView) findViewById(R.id.txt_view_description);
txtViewTitle = (SidraTextView) findViewById(R.id.txt_view_headline);
viewPager = (ViewPager) findViewById(R.id.view_pager);
linearIndicatorLayout = (LinearLayout) findViewById(R.id.linear_indicator);
txtViewDateField = (SidraTextView) findViewById(R.id.textView2);
}
private void setListener() {
btnBack.setOnClickListener(this);
btnMenu.setOnClickListener(this);
imgViewFavorite.setOnClickListener(this);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int index) {
Log.d("Page", "**** onPageSelected = " + index);
for(int count = 0; count < SidraPulseApp.getInstance().getOfferPromotionInfoList().get(position).getPhotoArray().size(); count++) {
if (index == count) {
linearIndicatorLayout.findViewWithTag(count).setBackgroundResource(R.drawable.circle_selected);
} else{
linearIndicatorLayout.findViewWithTag(count).setBackgroundResource(R.drawable.circle);
}
}
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
@Override
public void onBackPressed() {
if(isBookMarked != isBookMarkedFirstTime) {
changeBookMarkStatus();
}
super.onBackPressed();
}
private void changeBookMarkStatus() {
if(isBookMarked == 1) {
SidraPulseApp.getInstance().getOfferPromotionInfoList().get(position).setIsBookmarked(1);
} else {
SidraPulseApp.getInstance().getOfferPromotionInfoList().get(position).setIsBookmarked(0);
if(ConstantValues.offersTabIndex == 3) {
SidraPulseApp.getInstance().getOfferPromotionInfoList().remove(position);
}
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_back:
onBackPressed();
break;
case R.id.btn_menu:
if(isBookMarked != isBookMarkedFirstTime) {
changeBookMarkStatus();
}
startActivity(new Intent(OffersPromotionsDetailsActivity.this, MainMenuActivity.class));
finish();
break;
case R.id.img_view_favorite_or_not:
if (InternetConnectivity.isConnectedToInternet(OffersPromotionsDetailsActivity.this)) {
if(isBookMarked == 0) {
//SidraPulseApp.getInstance().getOfferPromotionInfoList().get(position).setIsBookmarked(1);
new FavoriateOrNotAsyncTask(OffersPromotionsDetailsActivity.this, id, "1", ConstantValues.FUNC_ID_BOOKMARK_OFFERS_AND_PROMOTION, new UnReadRequest() {
@Override
public void onTaskCompleted(int status) {
if(status == 1){
isBookMarked = 1;
Utilities.showToast(OffersPromotionsDetailsActivity.this, getResources().getString(R.string.toast_add_bookmark_for_offers));
imgViewFavorite.setBackgroundResource(R.drawable.star_icon);
}else{
Utilities.showToast(OffersPromotionsDetailsActivity.this, ConstantValues.failureMessage);
}
}
}).execute();
} else {
//SidraPulseApp.getInstance().getOfferPromotionInfoList().get(position).setIsBookmarked(0);
new FavoriateOrNotAsyncTask(OffersPromotionsDetailsActivity.this, id, "0", ConstantValues.FUNC_ID_BOOKMARK_OFFERS_AND_PROMOTION ,new UnReadRequest() {
@Override
public void onTaskCompleted(int status) {
if(status == 1){
isBookMarked = 0;
Utilities.showToast(OffersPromotionsDetailsActivity.this, getResources().getString(R.string.toast_remove_bookmark_for_offers));
imgViewFavorite.setBackgroundResource(R.drawable.star_gray_icon);
} else if(status == 5) {
SidraPulseApp.getInstance().accessTokenChange(OffersPromotionsDetailsActivity.this);
}else{
Utilities.showToast(OffersPromotionsDetailsActivity.this, ConstantValues.failureMessage);
}
}
}).execute();
}
} else {
SidraPulseApp.getInstance().openDialogForInternetChecking(OffersPromotionsDetailsActivity.this);
}
break;
default:
break;
}
}
}
|
package BinaryTrees;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class lab12 {
public static void main(String[]args) {
try {
BinarySearchTree<StudentGPA> order = new BinarySearchTree<>();
TreeIterator<StudentGPA>a = (TreeIterator<StudentGPA>)order.iterator();
Scanner inputFile= new Scanner(new File("students.in"));
String b = inputFile.nextLine();
while(inputFile.hasNextLine()) {
Scanner other = new Scanner(b);
int id= other.nextInt();
String name= other.next();
double gpa= other.nextDouble();
if(!other.hasNext()) {
StudentGPA order1= new StudentGPA(id,name,gpa);
order.insert(order1);
}
else {
String ad = other.next();
GraduateStudentGPA order2= new GraduateStudentGPA(id,name,gpa,ad);
order.insert(order2);
}
if(!inputFile.hasNext()) {
break;
}
else {
b=inputFile.nextLine();
}
}
inputFile.close();
a.printInorder();
}
catch(IOException e) {
System.err.println("IOError\n"+e);
System.exit(9);
}
}
}
|
package com.yuneec.IPCameraManager;
public class Cameras {
private int id;
private String p_codep;
private String p_codev;
private String p_dr;
private String p_f;
private String p_intervalp;
private String p_intervalv;
private String p_n;
private String p_name;
private String p_t1;
private String p_t2;
private String p_type;
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.p_name;
}
public void setName(String name) {
this.p_name = name;
}
public String getType() {
return this.p_type;
}
public void setType(String type) {
this.p_type = type;
}
public String getDr() {
return this.p_dr;
}
public void setDr(String dr) {
this.p_dr = dr;
}
public String getF() {
return this.p_f;
}
public void setF(String f) {
this.p_f = f;
}
public String getN() {
return this.p_n;
}
public void setN(String n) {
this.p_n = n;
}
public String getT1() {
return this.p_t1;
}
public void setT1(String t1) {
this.p_t1 = t1;
}
public String getT2() {
return this.p_t2;
}
public void setT2(String t2) {
this.p_t2 = t2;
}
public String getIntervalp() {
return this.p_intervalp;
}
public void setIntervalp(String intervalp) {
this.p_intervalp = intervalp;
}
public String getCodep() {
return this.p_codep;
}
public void setCodep(String codep) {
this.p_codep = codep;
}
public String getIntervalv() {
return this.p_intervalv;
}
public void setIntervalv(String intervalv) {
this.p_intervalv = intervalv;
}
public String getCodev() {
return this.p_codev;
}
public void setCodev(String codev) {
this.p_codev = codev;
}
}
|
package intromethods;
import java.util.ArrayList;
import java.util.List;
public class TodoList {
private List<Todo> todos = new ArrayList<>();
public void addTodo(String caption) {
todos.add(new Todo(caption));
}
public void finishTodo(String caption) {
for (Todo item : todos) {
if (item.getCaption().equals(caption)) {
item.finish();
}
}
}
public void finishAllTodos(List<Todo> todo) {
for (Todo item1 : todo) {
for (Todo item2 : todos) {
if (item1.getCaption().equals(item2.getCaption())) {
item2.finish();
}
}
}
}
public List<Todo> todosToFinish() {
List<Todo> retVal = new ArrayList<>();
for (Todo item : todos) {
if (!item.isFinished()) {
retVal.add(item);
}
}
return retVal;
}
public int numberOfFinishedTodos() {
int counter = 0;
for (Todo item : todos) {
if (item.isFinished()) {
counter++;
}
}
return counter;
}
@Override
public String toString() {
return "TodoList{" +
"todos=" + todos.toString() +
'}';
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.