text
stringlengths 10
2.72M
|
|---|
package edu.kit.pse.osip.core.io.files;
import static org.junit.Assert.assertEquals;
import edu.kit.pse.osip.core.model.base.TankSelector;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* Test class for ServerSettingsWrapper.
*
* @author Maximilian Schwarzmann
* @version 1.0
*/
public class ServerSettingsWrapperTest {
private ServerSettingsWrapper wrapper;
private File tempTestFile;
/**
* Sets up.
*
* @throws Exception Exception in file loading or IO errors.
*/
@Before
public void setUp() throws Exception {
tempTestFile = File.createTempFile("testServerSettingsTemp", ".properties");
PrintWriter outStream = new PrintWriter(tempTestFile);
outStream.print("serverPort_" + (TankSelector.valuesWithoutMix()[0]) + "=" + "1000");
outStream.println();
outStream.close();
wrapper = new ServerSettingsWrapper(tempTestFile);
}
/**
* Tests setting server ports.
*/
@Test
public void testSetServerPort() {
wrapper.setServerPort(TankSelector.valuesWithoutMix()[0], 1042);
assertEquals(1042, wrapper.getServerPort(TankSelector.valuesWithoutMix()[0], -1));
}
/**
* Tests getting server ports.
*/
@Test
public void testGetServerPort() {
int result = wrapper.getServerPort(TankSelector.valuesWithoutMix()[0], -1);
assertEquals(1000, result);
}
/**
* Tests writing to file.
*
* @throws IOException Exception in IO streams.
*/
@Test
public void testSaveSettings() throws IOException {
wrapper.setServerPort(TankSelector.valuesWithoutMix()[0], 1122);
wrapper.saveSettings();
wrapper = new ServerSettingsWrapper(tempTestFile);
assertEquals(1122, wrapper.getServerPort(TankSelector.valuesWithoutMix()[0], -1));
}
/**
* Tests getting tank that is not in properties file.
*/
@Test
public void testGetServerPortNull() {
int result = wrapper.getServerPort(TankSelector.valuesWithoutMix()[1], -1);
assertEquals(-1, result);
}
/**
* Tests null argument in constructor.
*/
@Test(expected = NullPointerException.class)
public void testNullArgConstructor() {
ServerSettingsWrapper serverWrapper = new ServerSettingsWrapper(null);
}
/**
* Resets file.
*
* @throws IOException Exception in IO streams.
*/
@After
public void tearDown() throws IOException {
tempTestFile.delete();
}
}
|
package com.yunhe.cargomanagement.service;
import com.yunhe.cargomanagement.entity.WarehouseUndetermined;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author 史江浩
* @since 2019-01-10
*/
public interface IWarehouseUndeterminedService extends IService<WarehouseUndetermined> {
}
|
package com.tt.miniapp.base.file;
import com.bytedance.sandboxapp.b.a;
import com.bytedance.sandboxapp.protocol.service.f.a;
import com.tt.miniapp.storage.filestorge.FileManager;
import d.f.b.l;
import java.io.File;
public final class FileService implements a {
private final a context;
public FileService(a parama) {
this.context = parama;
}
public final boolean canWrite(String paramString) {
l.b(paramString, "filePath");
File file = new File(FileManager.inst().getRealFilePath(paramString));
return FileManager.inst().canWrite(file);
}
public final a getContext() {
return this.context;
}
public final boolean isParentDirExists(String paramString) {
l.b(paramString, "filePath");
File file = (new File(FileManager.inst().getRealFilePath(paramString))).getParentFile();
return (file == null) ? false : file.exists();
}
public final void onDestroy() {}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\base\file\FileService.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package com.crio.starter.exceptions;
public class NoMemeFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public NoMemeFoundException() {
}
public NoMemeFoundException(String message) {
super(message);
}
}
|
/*
* LumaQQ - Java QQ Client
*
* Copyright (C) 2004 luma <stubma@163.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.tsinghua.lumaqq.qq.beans;
import static org.apache.commons.codec.digest.DigestUtils.*;
import edu.tsinghua.lumaqq.qq.QQ;
import edu.tsinghua.lumaqq.qq.Util;
/**
* 封装QQ用户的信息
*
* @author luma
*/
public class QQUser {
// Double MD5处理的用户密码
private byte[] md5pwd;
// 初始密钥
private byte[] iniKey;
// 请求登录令牌时的随机密钥
private byte[] loginTokenRandomKey;
// 登录令牌
private byte[] loginToken;
// 会话密钥
private byte[] sessionKey;
// 文件传输会话密钥
private byte[] fileSessionKey;
// 文件中转服务器通讯密钥,来自0x001D - 0x4
private byte[] fileAgentKey;
// 客户端key
private byte[] clientKey;
// 未知用途密钥,来自0x001D
private byte[] unknown03Key;
private byte[] unknown06Key;
private byte[] unknown07Key;
private byte[] unknown08Key;
// 文件中转认证令牌
private byte[] fileAgentToken;
// 未知令牌
private byte[] unknown03Token;
private byte[] unknown06Token;
private byte[] unknown07Token;
private byte[] unknown08Token;
// 认证令牌
private byte[] authToken;
// QQ号
private int qq;
// 本地IP
private byte[] ip;
// 本地端口,在QQ中其实只有两字节
private int port;
// 服务器IP
private byte[] serverIp;
// 服务器端口,在QQ中其实只有两字节
private int serverPort;
// 本次登陆时间
private long loginTime;
// 上一次登陆IP
private byte[] lastLoginIp;
// 上一次登陆时间,在QQ中其实只有4字节
private long lastLoginTime;
// 当前登陆状态,为true表示已经登陆
private boolean loggedIn;
// 登陆模式,隐身还是非隐身
private byte loginMode;
// 设置登陆服务器的方式是UDP还是TCP
private boolean udp;
// 当前的状态,比如在线,隐身等等
private byte status;
// ContactInfo
private ContactInfo contactInfo;
// 是否显示虚拟摄像头
private boolean showFakeCam;
/**
* @param qq QQ号
* @param pwd 密码
*/
public QQUser(int qqNum, String pwd) {
this.qq = qqNum;
setPassword(pwd);
ip = new byte[4];
serverIp = new byte[4];
lastLoginIp = new byte[4];
loggedIn = false;
loginMode = QQ.QQ_LOGIN_MODE_NORMAL;
udp = true;
contactInfo = new ContactInfo();
showFakeCam = false;
iniKey = Util.randomKey();
loginTokenRandomKey = Util.randomKey();
}
/**
* @param qq QQ号
* @param md5pwd 经过Double MD5的密码字节数组
*/
public QQUser(int qqNum, byte[] md5pwd) {
this.qq = qqNum;
this.md5pwd = md5pwd;
ip = new byte[4];
serverIp = new byte[4];
lastLoginIp = new byte[4];
loggedIn = false;
loginMode = QQ.QQ_LOGIN_MODE_NORMAL;
udp = true;
contactInfo = new ContactInfo();
showFakeCam = false;
iniKey = Util.randomKey();
loginTokenRandomKey = Util.randomKey();
}
/**
* @return Returns the qq.
*/
public int getQQ() {
return qq;
}
/**
* @param qq The qq to set.
*/
public void setQQ(int qqNum) {
this.qq = qqNum;
}
/**
* @return Returns the sessionKey.
*/
public byte[] getSessionKey() {
return sessionKey;
}
/**
* @param sessionKey The sessionKey to set.
*/
public void setSessionKey(byte[] sessionKey) {
this.sessionKey = sessionKey;
}
/**
* 设置用户的密码,不会保存明文形式的密码,立刻用Double MD5算法加密
* @param pwd 明文形式的密码
*/
public void setPassword(String pwd) {
md5pwd = md5(md5(pwd.getBytes()));
}
/**
* @return 被Double MD5处理过的密码
*/
public byte[] getPasswordKey() {
return md5pwd;
}
/**
* @return Returns the ip.
*/
public byte[] getIp() {
return ip;
}
/**
* @param ip The ip to set.
*/
public void setIp(byte[] ip) {
this.ip = ip;
}
/**
* @return Returns the lastLoginIp.
*/
public byte[] getLastLoginIp() {
return lastLoginIp;
}
/**
* @param lastLoginIp The lastLoginIp to set.
*/
public void setLastLoginIp(byte[] lastLoginIp) {
this.lastLoginIp = lastLoginIp;
}
/**
* @return Returns the port.
*/
public int getPort() {
return port;
}
/**
* @param port The port to set.
*/
public void setPort(int port) {
this.port = port;
}
/**
* @return Returns the serverIp.
*/
public byte[] getServerIp() {
return serverIp;
}
/**
* @param serverIp The serverIp to set.
*/
public void setServerIp(byte[] serverIp) {
this.serverIp = serverIp;
}
/**
* @return Returns the serverPort.
*/
public int getServerPort() {
return serverPort;
}
/**
* @param serverPort The serverPort to set.
*/
public void setServerPort(int serverPort) {
this.serverPort = serverPort;
}
/**
* @return Returns the lastLoginTime.
*/
public long getLastLoginTime() {
return lastLoginTime;
}
/**
* @param lastLoginTime The lastLoginTime to set.
*/
public void setLastLoginTime(long lastLoginTime) {
this.lastLoginTime = lastLoginTime;
}
/**
* @return Returns the loginTime.
*/
public long getLoginTime() {
return loginTime;
}
/**
* @param loginTime The loginTime to set.
*/
public void setLoginTime(long loginTime) {
this.loginTime = loginTime;
}
/**
* @return Returns the loggedIn.
*/
public boolean isLoggedIn() {
return loggedIn;
}
/**
* @param loggedIn The loggedIn to set.
*/
public void setLoggedIn(boolean loggedIn) {
this.loggedIn = loggedIn;
}
/**
* @param loginMode
* The loginMode to set.
*/
public void setLoginMode(byte loginMode) {
this.loginMode = loginMode;
}
/**
* @return Returns the loginMode.
*/
public byte getLoginMode() {
return loginMode;
}
/**
* @return Returns the udp.
*/
public boolean isUdp() {
return udp;
}
/**
* @param udp The udp to set.
*/
public void setUdp(boolean udp) {
this.udp = udp;
}
/**
* @return Returns the status.
*/
public byte getStatus() {
return status;
}
/**
* @param status The status to set.
*/
public void setStatus(byte status) {
this.status = status;
}
/**
* @return Returns the contactInfo.
*/
public ContactInfo getContactInfo() {
return contactInfo;
}
/**
* @param contactInfo The contactInfo to set.
*/
public void setContactInfo(ContactInfo contactInfo) {
this.contactInfo = contactInfo;
}
/**
* @return Returns the fileKey.
*/
public byte[] getFileSessionKey() {
return fileSessionKey;
}
/**
* @param fileKey The fileKey to set.
*/
public void setFileSessionKey(byte[] fileKey) {
this.fileSessionKey = fileKey;
}
/**
* @return Returns the fileAgentKey.
*/
public byte[] getFileAgentKey() {
return fileAgentKey;
}
/**
* @param fileAgentKey The fileAgentKey to set.
*/
public void setFileAgentKey(byte[] fileAgentKey) {
this.fileAgentKey = fileAgentKey;
}
/**
* @return Returns the unknownKey.
*/
public byte[] getUnknown03Key() {
return unknown03Key;
}
/**
* @param unknownKey The unknownKey to set.
*/
public void setUnknown03Key(byte[] unknownKey) {
this.unknown03Key = unknownKey;
}
/**
* @return Returns the fileAgentToken.
*/
public byte[] getFileAgentToken() {
return fileAgentToken;
}
/**
* @param fileAgentToken The fileAgentToken to set.
*/
public void setFileAgentToken(byte[] fileAgentToken) {
this.fileAgentToken = fileAgentToken;
}
/**
* @return Returns the unknownToken.
*/
public byte[] getUnknown03Token() {
return unknown03Token;
}
/**
* @param unknownToken The unknownToken to set.
*/
public void setUnknown03Token(byte[] unknownToken) {
this.unknown03Token = unknownToken;
}
/**
* @return Returns the showFakeCam.
*/
public boolean isShowFakeCam() {
return showFakeCam;
}
/**
* @param showFakeCam The showFakeCam to set.
*/
public void setShowFakeCam(boolean showFakeCam) {
this.showFakeCam = showFakeCam;
}
/**
* @return
* client key
*/
public byte[] getClientKey() {
return clientKey;
}
/**
* @param clientKey
* client key
*/
public void setClientKey(byte[] clientKey) {
this.clientKey = clientKey;
}
/**
* @return
* 初始密钥
*/
public byte[] getInitKey() {
return iniKey;
}
/**
* @return Returns the loginToken.
*/
public byte[] getLoginToken() {
return loginToken;
}
/**
* @param loginToken The loginToken to set.
*/
public void setLoginToken(byte[] loginToken) {
this.loginToken = loginToken;
}
/**
* @return the unknown06Key
*/
public byte[] getUnknown06Key() {
return unknown06Key;
}
/**
* @param unknown06Key the unknown06Key to set
*/
public void setUnknown06Key(byte[] unknown06Key) {
this.unknown06Key = unknown06Key;
}
/**
* @return the unknown07Key
*/
public byte[] getUnknown07Key() {
return unknown07Key;
}
/**
* @param unknown07Key the unknown07Key to set
*/
public void setUnknown07Key(byte[] unknown07Key) {
this.unknown07Key = unknown07Key;
}
/**
* @return the unknown08Key
*/
public byte[] getUnknown08Key() {
return unknown08Key;
}
/**
* @param unknown08Key the unknown08Key to set
*/
public void setUnknown08Key(byte[] unknown08Key) {
this.unknown08Key = unknown08Key;
}
/**
* @return the unknown06Token
*/
public byte[] getUnknown06Token() {
return unknown06Token;
}
/**
* @param unknown06Token the unknown06Token to set
*/
public void setUnknown06Token(byte[] unknown06Token) {
this.unknown06Token = unknown06Token;
}
/**
* @return the unknown07Token
*/
public byte[] getUnknown07Token() {
return unknown07Token;
}
/**
* @param unknown07Token the unknown07Token to set
*/
public void setUnknown07Token(byte[] unknown07Token) {
this.unknown07Token = unknown07Token;
}
/**
* @return the unknown08Token
*/
public byte[] getUnknown08Token() {
return unknown08Token;
}
/**
* @param unknown08Token the unknown08Token to set
*/
public void setUnknown08Token(byte[] unknown08Token) {
this.unknown08Token = unknown08Token;
}
/**
* @return the authToken
*/
public byte[] getAuthToken() {
return authToken;
}
/**
* @param authToken the authToken to set
*/
public void setAuthToken(byte[] authToken) {
this.authToken = authToken;
}
public byte[] getLoginTokenRandomKey() {
return loginTokenRandomKey;
}
}
|
package com.lspring.annotation;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpirngTest {
// @Test
public void addPerson(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans_annotation.xml");
IPersonServiceImp serviceImp = applicationContext.getBean(IPersonServiceImp.class);
serviceImp.addPerson(new Person());
}
}
|
package Presentacion;
import Logica.RNA;
import archivo.Archivo;
import java.io.IOException;
import javax.swing.JOptionPane;
import javax.swing.JFileChooser;
public class Entrenamiento extends javax.swing.JFrame {
private MenuInicio menu;
private RNA red;
private boolean band = false;
private String direccion;
public Entrenamiento(MenuInicio m) {
initComponents();
menu = m;
red = menu.getRed();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabelTitulo = new javax.swing.JLabel();
jLabelCarga = new javax.swing.JLabel();
jButtonExaminar = new javax.swing.JButton();
jLabelRuta = new javax.swing.JLabel();
jButtonAceptar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jLabelTitulo.setBackground(new java.awt.Color(255, 0, 0));
jLabelTitulo.setFont(new java.awt.Font("Tahoma", 1, 20)); // NOI18N
jLabelTitulo.setForeground(new java.awt.Color(255, 0, 0));
jLabelTitulo.setText("ENTRENAMIENTO");
jLabelCarga.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jLabelCarga.setText("Cargue el archivo del DataSet");
jButtonExaminar.setText("Examinar");
jButtonExaminar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonExaminarActionPerformed(evt);
}
});
jButtonAceptar.setText("Aceptar");
jButtonAceptar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonAceptarActionPerformed(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()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(96, 96, 96)
.addComponent(jLabelTitulo))
.addGroup(layout.createSequentialGroup()
.addGap(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabelRuta, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabelCarga, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButtonExaminar, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jButtonAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(46, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabelTitulo)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(4, 4, 4)
.addComponent(jLabelCarga))
.addComponent(jButtonExaminar))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabelRuta, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jButtonAceptar)
.addContainerGap(22, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButtonExaminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonExaminarActionPerformed
JFileChooser dig = new JFileChooser();
int opcion = dig.showOpenDialog(this);
if (opcion == JFileChooser.APPROVE_OPTION) {
String file = dig.getSelectedFile().getName();
band = true;
jLabelRuta.setText("Archivo: " + file);
direccion = dig.getSelectedFile().getAbsolutePath();
}
}//GEN-LAST:event_jButtonExaminarActionPerformed
private void jButtonAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAceptarActionPerformed
if (band) {
Archivo a = new Archivo(direccion);
try {
red.setCantidadLineas(a.CantidadLineas());
jLabelRuta.setText("Por Favor Espera, La Red Está Entrenando...");
JOptionPane.showMessageDialog(null, "Patrones De Entrenamiento Cargados", "Informacion", JOptionPane.INFORMATION_MESSAGE);
String ciclos = JOptionPane.showInputDialog("Ingresa la cantidad de Iteraciones por ciclo de Entrenamiento");
String factorAprendizaje = JOptionPane.showInputDialog("Ingresa el Factor de Aprendizaje");
String momentum = JOptionPane.showInputDialog("Ingresa el Momentum");
try {
red.setCiclos(Integer.parseInt(ciclos));
red.setDirEntradas(direccion);
red.setFactorAprendizaje(Double.parseDouble(factorAprendizaje));
red.setMomentum(Double.parseDouble(momentum));
try {
String error = red.training("Error.txt");
JOptionPane.showMessageDialog(null, "Entrenamiento Realizado Exitosamente", "Informacion", JOptionPane.INFORMATION_MESSAGE);
if(error != null)
JOptionPane.showMessageDialog(rootPane, "Error Cuadratico Medio: " + error);
menu.setVisible(true);
this.dispose();
} catch (Exception ex) {
JOptionPane.showMessageDialog(rootPane, "Ocurrio un Error Al Entrenar La Red", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(rootPane, "Datos Incorrectos", "Error I/O", JOptionPane.ERROR_MESSAGE);
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(rootPane, "Error Al Cargar Archivo:\n" + direccion, "Error I/O", JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null, "Debe cargar un Archivo", "Informacion", JOptionPane.INFORMATION_MESSAGE);
}
}//GEN-LAST:event_jButtonAceptarActionPerformed
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
menu.setVisible(true);
}//GEN-LAST:event_formWindowClosing
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButtonAceptar;
private javax.swing.JButton jButtonExaminar;
private javax.swing.JLabel jLabelCarga;
private javax.swing.JLabel jLabelRuta;
private javax.swing.JLabel jLabelTitulo;
// End of variables declaration//GEN-END:variables
}
|
package Geometry;
import GameObjects.GameObject;
import java.util.LinkedList;
public interface RangeQueryTree<E extends GameObject> {
public void add(E elem);
public LinkedList<E> getObjectsInRange(int x1, int y1, int x2, int y2);
public void remove(E elem);
}
|
package com.samirthebti.amen_go;
import mx.com.quiin.contactpicker.Contact;
/**
* Amen_Go
* Created by Samir Thebti on 5/16/17.
* thebtisam@gmail.com
*/
public interface ContactSelectionListener {
void onContactSelected(Contact contact, String communication);
void onContactDeselected(Contact contact, String communication);
void onContactDelate(Contact contact, String communication);
}
|
package com.gp.beershop.service;
import com.gp.beershop.dto.Beer;
import com.gp.beershop.entity.BeerEntity;
import com.gp.beershop.exception.NoSuchBeerException;
import com.gp.beershop.exception.SuchBeerAlreadyExistException;
import com.gp.beershop.mapper.BeerMapper;
import com.gp.beershop.repository.BeerRepository;
import lombok.Data;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
import java.util.stream.Collectors;
@Data
@Service
public class BeerService {
private final BeerRepository beerRepository;
private final BeerMapper beerMapper;
public List<Beer> getBeers() {
return beerRepository.findAll()
.stream()
.map(beerMapper::destinationToSource)
.collect(Collectors.toList());
}
public Beer getBeerById(final Integer id) throws NoSuchBeerException {
checkExistingBeer(id);
return beerRepository.findById(id)
.map(beerMapper::destinationToSource)
.get();
}
public List<Beer> getBeersByFilter(final String beerType) {
return beerRepository.findAll()
.stream()
.map(beerMapper::destinationToSource)
.filter(b -> b.getType().equals(beerType))
.collect(Collectors.toList());
}
@Transactional
public Integer addBeer(final Beer beer) throws SuchBeerAlreadyExistException {
if (beerRepository.findFirstByName(beer.getName()).isPresent()) {
throw new SuchBeerAlreadyExistException("Beer with name = " + beer.getName() + " already exists.");
}
final BeerEntity beerEntity = beerMapper.sourceToDestination(beer);
final BeerEntity beerEntityOutput = beerRepository.save(beerEntity);
return beerEntityOutput.getId();
}
public Beer updateBeerById(final Integer id, final Beer beer) throws NoSuchBeerException {
checkExistingBeer(id);
beer.setId(id);
final BeerEntity beerEntity = beerMapper.sourceToDestination(beer);
beerRepository.save(beerEntity);
return beerMapper.destinationToSource(beerEntity);
}
public void deleteBeerById(final Integer id) throws NoSuchBeerException {
checkExistingBeer(id);
beerRepository.deleteById(id);
}
private void checkExistingBeer(final Integer id) throws NoSuchBeerException {
final boolean isFound = beerRepository.existsById(id);
if (!isFound) {
throw new NoSuchBeerException("No beer with id = " + id + " was found.");
}
}
}
|
/*
* Copyright 2009 Kjetil Valstadsve
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package vanadis.lang.piji;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vanadis.lang.piji.fun.Functions;
import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* An interpreter is mainly holder of a top-level context which it
* fills with the standard set of internal functions, reflection
* functions and the odd utility function.
*
* @author Kjetil Valstadsve
*/
public final class Interpreter {
private static final Logger log = LoggerFactory.getLogger(Interpreter.class);
private static final Symbol INTERPRETER = Symbol.get("interpreter");
private static final Symbol INTER_STDIN = Symbol.get("inter-stdin");
private static final Symbol INTER_STDOUT = Symbol.get("inter-stdout");
private static final Symbol INTER_STDERR = Symbol.get("inter-stderr");
private static final Parser parser = new Parser();
private static final Context commonContext = new Context(null, Interpreter.class.getClassLoader(), false);
private static final Interpreter bootstrap;
public static Expression parse(String string) {
return Interpreter.parser.parse(string);
}
public static Expression parse(InputStream stream) {
return Interpreter.parser.parse(stream);
}
public static Expression parse(Reader reader) {
return Interpreter.parser.parse(reader);
}
public static List<Expression> parseAll(String string) {
return Interpreter.parser.parseAll(string);
}
public static List<Expression> parseAll(InputStream stream) {
return Interpreter.parser.parseAll(stream);
}
private static List<Expression> parseAll(Reader reader) {
return Interpreter.parser.parseAll(reader);
}
private static void commonBind(Symbol symbol, Object object) {
commonContext.bind(symbol, object);
}
private static void commonUnbind(Symbol symbol) {
commonContext.unbind(symbol);
}
private final Context context;
private static void preload(String symb, String name) {
Symbol symbol = Symbol.get(symb);
if (commonContext.isBound(symbol)) {
throw new ConfigurationException("Already bound " + symbol + " to " +
commonContext.lookup(symbol));
}
commonBind(symbol, new Loader(symbol, name));
}
private static Function load(String name) {
try {
Class<?> functionClass = commonContext.getClassLoader().loadClass(name);
Constructor<?>[] conses = functionClass.getConstructors();
if (conses.length == 0) {
throw new IllegalStateException("Found class " + functionClass + " with no constructors!");
}
if (conses.length > 1) {
throw new IllegalArgumentException("Cannot choose between constructors " +
Arrays.toString(conses) + ", trying to instantiate " +
functionClass);
}
Constructor<?> cons = conses[0];
Class<?>[] parTypes = cons.getParameterTypes();
if (parTypes.length != 1) {
throw new InternalRuntimeException("Got function " + functionClass +
" without single-argument constructor");
}
Object[] args = new Object[]{commonContext};
return (Function) cons.newInstance(args);
}
catch (ClassNotFoundException e) {
throw new InternalRuntimeException("Could not find " + name + ", got " + e, e);
}
catch (InstantiationException e) {
throw new InternalRuntimeException("Could not instantiate " + name + ", got " + e, e);
}
catch (IllegalAccessException e) {
throw new InternalRuntimeException("Could not access constructor of " + name + ", got " + e, e);
}
catch (InvocationTargetException e) {
throw new InternalRuntimeException("Failed to invokek constructor of " + name + ", got " + e, e);
}
}
private static final class Loader extends AbstractFunction {
private final Symbol symbol;
private final String classname;
private Loader(Symbol symbol, String classname) {
super(symbol + "-Loader", true, 0, commonContext);
this.symbol = symbol;
this.classname = classname;
commonBind(this.symbol, this);
}
private Function loadInternal() {
Function fun = load(this.classname);
commonUnbind(this.symbol);
commonBind(this.symbol, fun);
return fun;
}
@Override
public Object apply(Context context, Expression[] nodes)
throws Throwable {
return loadInternal().apply(context, nodes);
}
@Override
public boolean isVararg() {
return loadInternal().isVararg();
}
@Override
public int getArgumentCount() {
return loadInternal().getArgumentCount();
}
@Override
public String getDocumentationString() {
return loadInternal().getDocumentationString();
}
@Override
public Context getContext() {
return loadInternal().getContext();
}
}
private static void loadFunctions() {
for (int i = 0; i < Functions.MAP.length; i++) {
String[] spec = Functions.MAP[i];
String classname = "vanadis.lang.piji.fun." + spec[0];
preload(spec[1], classname);
}
}
private static void loadLibraries() {
try {
String res = "library.pji";
URL url = commonContext.getClassLoader().getResource(res);
if (url == null) {
log.warn("Could not find url " + res);
return;
}
InputStream library = url.openStream();
if (library == null) {
log.warn("Could not open resources " + url);
return;
}
bootstrap.evalInternal
(parseAll(new InputStreamReader(library)),
commonContext);
} catch (FileNotFoundException e) {
throw new ConfigurationException("Could not find library: " + e, e);
} catch (ParseException e) {
throw new ConfigurationException("Had problem parsing library: " + e, e);
} catch (IOException e) {
throw new ConfigurationException("Had problem loading library: " + e, e);
} catch (Throwable e) {
throw new ConfigurationException("Had problem executing library code: " + e, e);
}
}
static {
try {
bootstrap = new Interpreter(Interpreter.class.getClassLoader());
loadFunctions();
loadLibraries();
}
catch (ConfigurationException e) {
throw new PijiRuntimeException("Could not configure piji, got " + e, e);
}
}
public Interpreter(ClassLoader classLoader) {
Context topContext = new Context(commonContext);
topContext.bind(Interpreter.INTER_STDIN, System.in);
topContext.bind(Interpreter.INTER_STDOUT, System.out);
topContext.bind(Interpreter.INTER_STDERR, System.err);
topContext.bind(Interpreter.INTERPRETER, this);
this.context = new Context(topContext, classLoader, false);
}
public Context getContext() {
return this.context;
}
public Result evalResult(String string) {
return evalResult(string, this.context);
}
Result evalResult(String string, Context context) {
return evalResult(new StringReader(string), context);
}
public Result evalResult(InputStream reader) {
return evalResult(reader, this.context);
}
Result evalResult(InputStream reader, Context context) {
return evalResult(new InputStreamReader(reader), context);
}
public Result evalResult(Reader reader) {
return evalResult(reader, this.context);
}
Result evalResult(Reader reader, Context context) {
return evalInternal(parseAll(reader), context);
}
public Result evalResult(Expression expr) {
return this.evalInternal(expr, this.context);
}
Result evalResult(Expression expr, Context context) {
return this.evalInternal(expr, context);
}
private Result evalInternal(Expression expr, Context ctx) {
return this.evalInternal(Collections.singletonList(expr), ctx);
}
private Result evalInternal(List<Expression> exprs, Context ctx) {
if (ctx == null) {
throw new NullPointerException(this + " got null context for evaluating " + exprs);
}
if (exprs == null || exprs.isEmpty()) {
return null;
}
Result result = null;
Expression expr = null;
for (Expression e : exprs) {
expr = e;
if (expr != null) {
Object obj;
long startTime = 0;
long evalTime;
try {
startTime = System.currentTimeMillis();
obj = expr.evaluate(ctx);
evalTime = System.currentTimeMillis() - startTime;
if (obj == Context.NULL) {
obj = null;
}
result = Result.ok(expr, obj, evalTime);
}
catch (EvaluationException exc) {
throw exc;
}
catch (Throwable t) {
evalTime = System.currentTimeMillis() - startTime;
return Result.fail(expr, t, evalTime);
}
}
}
if (result == null) {
throw new IllegalStateException(this + " got illegal null result from " + expr);
}
return result;
}
public Object eval(String string) {
return this.eval(string, this.context);
}
Object eval(String string, Context context) {
return unwrap(this.evalResult(string, context));
}
public Object eval(InputStream stream) {
return eval(stream, this.context);
}
Object eval(InputStream stream, Context context) {
return unwrap(this.evalResult(stream, context));
}
public Object eval(Reader reader) {
return eval(reader, this.context);
}
Object eval(Reader reader, Context context) {
return unwrap(this.evalResult(reader, context));
}
public Object eval(Expression expr) {
return eval(expr, this.context);
}
Object eval(Expression expr, Context context) {
return unwrap(this.evalResult(expr, context));
}
private static Object unwrap(Result res) {
if (res.isOK()) {
return res.getTypedValue();
} else {
throw new RuntimeException(res.getThrowable());
}
}
@Override
public String toString() {
return "Interpreter[" + this.context + "]";
}
}
|
package xiaomage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @Author: wy
* @Date: 2019/4/27 20:50
* @Description:
*/
public class ThreadExeOrderQuestion {
public static void main(String[] args) throws Exception {
// joinTest();
// System.out.println("**************");
// loopTest();
System.out.println("**************");
waitTest();
// System.out.println("**************");
// singleThreadPoolTest();
}
// 单线程池实现
private static void singleThreadPoolTest(){
Thread t1 = new Thread(ThreadExeOrderQuestion::action, "1");
Thread t2 = new Thread(ThreadExeOrderQuestion::action, "2");
Thread t3 = new Thread(ThreadExeOrderQuestion::action, "3");
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(t1);
executorService.execute(t2);
executorService.execute(t3);
}
// 使用wait实现
private static void waitTest() throws Exception{
Thread t1 = new Thread(ThreadExeOrderQuestion::action, "1");
Thread t2 = new Thread(ThreadExeOrderQuestion::action, "2");
Thread t3 = new Thread(ThreadExeOrderQuestion::action, "3");
startAndWait(t1);
startAndWait(t2);
startAndWait(t3);
}
private static void startAndWait(Thread thread) throws Exception{
if(Thread.State.NEW.equals(thread.getState())){
thread.start();
}
while(thread.isAlive()){
synchronized(thread){
thread.wait(1000L);
}
}
}
// 使用状态.循环等待的方法
private static void loopTest() throws InterruptedException {
Thread t1 = new Thread(ThreadExeOrderQuestion::action, "1");
Thread t2 = new Thread(ThreadExeOrderQuestion::action, "2");
Thread t3 = new Thread(ThreadExeOrderQuestion::action, "3");
t1.start();
while (t1.isAlive()) {
}
t2.start();
while (t2.isAlive()) {
}
t3.start();
while (t3.isAlive()) {
}
}
// 使用join 控制线程顺序
private static void joinTest() throws InterruptedException {
Thread t1 = new Thread(ThreadExeOrderQuestion::action, "1");
Thread t2 = new Thread(ThreadExeOrderQuestion::action, "2");
Thread t3 = new Thread(ThreadExeOrderQuestion::action, "3");
t1.start();
// 让主线程等待子线程运行结束后再继续运行
t1.join();
t2.start();
t2.join();
t3.start();
t3.join();
}
private static void action() {
System.out.printf("线程[%s] 正在执行\n", Thread.currentThread().getName());
}
}
|
package com.commercetools.pspadapter.payone.domain.payone;
import com.commercetools.pspadapter.payone.domain.payone.exceptions.PayoneException;
import org.apache.http.message.BasicNameValuePair;
import org.junit.Before;
import org.junit.Test;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.ThrowableAssert.catchThrowable;
public class PayonePostServiceImplTest {
public static final String PAYONE_SERVER_API_URL = "http://some.url.org/payone";
private PayonePostServiceImpl payonePostService;
@Before
public void setup() throws PayoneException {
payonePostService = PayonePostServiceImpl.of(PAYONE_SERVER_API_URL);
}
@Test
public void shouldThrowConfigurationExceptionIfUrlIsEmptyOnInitialization() {
final Throwable throwable = catchThrowable(() -> PayonePostServiceImpl.of(""));
assertThat(throwable)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The server api url must not be null or empty.");
}
@Test
public void shouldThrowConfigurationExceptionIfUrlIsNullOnInitialization() {
final Throwable throwable = catchThrowable(() -> PayonePostServiceImpl.of(null));
assertThat(throwable)
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("The server api url must not be null or empty.");
}
@Test
public void shouldInitServiceWithCorrectUrl() {
assertThat(payonePostService.getServerAPIURL()).isEqualTo(PAYONE_SERVER_API_URL);
}
@Test
public void shouldBuildMapFromServerResponse() throws UnsupportedEncodingException {
String serverResponse = "paramA=a\nredirecturl=https://www.redirect.de/xxx\nstatus=SUCCESSFUL";
Map<String, String> result = payonePostService.buildMapFromResultParams(serverResponse);
assertThat(result).isNotEmpty();
assertThat(result).hasSize(3);
assertThat(result).containsEntry("paramA", "a");
assertThat(result).containsEntry("redirecturl", "https://www.redirect.de/xxx");
assertThat(result).containsEntry("status", "SUCCESSFUL");
}
@Test
public void shouldReturnEmptyMap() throws UnsupportedEncodingException {
String serverResponse = "=x=";
Map<String, String> result = payonePostService.buildMapFromResultParams(serverResponse);
assertThat(result).isEmpty();
}
@Test
public void getObjectMapWithExpandedLists() {
assertThat(payonePostService.getNameValuePairsWithExpandedLists(Collections.emptyMap())).hasSize(0);
final List<BasicNameValuePair> simple = payonePostService.getNameValuePairsWithExpandedLists(Collections.singletonMap(
"foo", "bar"));
assertThat(simple).hasSize(1);
assertThat(simple).contains(new BasicNameValuePair("foo", "bar"));
// for now only string/numeric values are tested
final HashMap<String, Object> requestParams = new HashMap<>();
requestParams.put("foo", "bar");
requestParams.put("woot", "wootValue");
requestParams.put("list1", Arrays.asList(1, 2, 3));
requestParams.put("a", 42);
requestParams.put("empty", "");
requestParams.put("boolTrue", true);
requestParams.put("boolFalse", false);
requestParams.put("listString", new LinkedList<>(Arrays.asList("ein", "zwei", "drei")));
requestParams.put("listDoubles", asList(3.14, 2.71, 9.81));
final List<BasicNameValuePair> withExpandedLists =
payonePostService.getNameValuePairsWithExpandedLists(requestParams);
assertThat(withExpandedLists).containsExactlyInAnyOrder(
new BasicNameValuePair("foo", "bar"),
new BasicNameValuePair("woot", "wootValue"),
new BasicNameValuePair("a", "42"),
new BasicNameValuePair("empty", ""),
new BasicNameValuePair("boolTrue", "true"),
new BasicNameValuePair("boolFalse", "false"),
new BasicNameValuePair("list1[1]", "1"),
new BasicNameValuePair("list1[2]", "2"),
new BasicNameValuePair("list1[3]", "3"),
new BasicNameValuePair("listString[1]", "ein"),
new BasicNameValuePair("listString[2]", "zwei"),
new BasicNameValuePair("listString[3]", "drei"),
new BasicNameValuePair("listDoubles[1]", "3.14"),
new BasicNameValuePair("listDoubles[2]", "2.71"),
new BasicNameValuePair("listDoubles[3]", "9.81"));
requestParams.clear();
requestParams.put("foo", new ArrayList<>());
requestParams.put("bar", new LinkedList<>());
final List<BasicNameValuePair> withEmptyLists = payonePostService.getNameValuePairsWithExpandedLists(
requestParams);
assertThat(withEmptyLists).containsExactlyInAnyOrder(
new BasicNameValuePair("foo[]", ""),
new BasicNameValuePair("bar[]", ""));
}
}
|
package hack.anonymouse.app.data;
public class Data {
public static boolean PUBLIC_STORY = false;
private Data() {
}
}
|
package com.ld.model_user.activity;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.ld.baselibrary.arouter.ARouterPath;
import com.ld.model_user.R;
/**
* @author: liangduo
* @date: 2020/7/22 8:54 PM
*/
@Route(path = ARouterPath.UserActivity)
public class UserActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
findViewById(R.id.user_btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
|
public class RiverSquare extends Square{
private final int COST = 200;
public RiverSquare(String name, int position) {
super(name, position);
}
@Override
public boolean isOwned() {
return false;
}
public void execute(Player player) {
player.deductMaterials(getCOST());
System.out.println(StdIO.printSquareLandedOn(player, this.getName()));
System.out.println(StdIO.printRiverSquare(player, getCOST(), this.getName()));
}
public int getCOST() {
return this.COST;
}
}
|
package com.example.repository;
import java.util.Collection;
import java.util.Optional;
/**
*
* @author Binnur Kurt <binnur.kurt@gmail.com>
*/
public interface GenericRepository<E,K> {
Optional<E> findOne(K key);
Collection<E> findAll();
E add(E entity);
E update(E entity);
Optional<E> remove(K key);
}
|
package com.vilio.plms.dao;
import com.vilio.plms.pojo.Customer;
import java.util.List;
import java.util.Map;
/**
* 类名: CustomerDao<br>
* 功能:借款人Dao<br>
* 版本: 1.0<br>
* 日期: 2017年6月21日<br>
* 作者: wangxf<br>
* 版权:vilio<br>
* 说明:<br>
*/
public interface CustomerDao {
//查询借款人信息
public Customer qryCustomer(Customer customer);
//新增
public void insert(Map param);
List<Map> getCustomerInfoByApplyCode(Map param);
}
|
package com.lv.textviewdemos;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.daasuu.cat.CountAnimationTextView;
import com.hanks.htextview.HTextView;
import com.robinhood.ticker.TickerUtils;
import com.robinhood.ticker.TickerView;
import org.fabiomsr.moneytextview.MoneyTextView;
public class MainActivity extends AppCompatActivity {
private HTextView mTextHTextView;
private MoneyTextView mTextMoneyTextView;
private CountAnimationTextView mCountAnimationTextView;
private TickerView mTickerView;
private CustomTextView mTestCustomTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
mTextHTextView.animateText("HTextView new simple string");
mTickerView.setText("$789");
mTextHTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mTextMoneyTextView.setAmount(156);
mCountAnimationTextView.countAnimation(0, 99999);
mTickerView.setText("$123456");
}
});
}
private void initView() {
mTextHTextView = (HTextView) findViewById(R.id.text_HTextView);
mTextMoneyTextView = (MoneyTextView) findViewById(R.id.text_MoneyTextView);
mCountAnimationTextView = (CountAnimationTextView) findViewById(R.id.count_animation_textView);
mTickerView = (TickerView) findViewById(R.id.tickerView);
mTickerView.setCharacterList(TickerUtils.getDefaultListForUSCurrency());
mTickerView.setAnimationDuration(500);
mTestCustomTextView = (CustomTextView) findViewById(R.id.test_CustomTextView);
mTestCustomTextView.setSelected(true);
}
}
|
package com.example.tartanuk.layoutcolores1;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.tartanuk.layoutcolores1.R;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Variables
final ImageButton imageButton1 = (ImageButton) findViewById(R.id.imageButton1);
final ImageButton imageButton2 = (ImageButton) findViewById(R.id.imageButton2);
final ImageButton imageButton3 = (ImageButton) findViewById(R.id.imageButton3);
final Button button1 = (Button) findViewById(R.id.button1);
final TextView textView1 = (TextView) findViewById(R.id.textview1);
imageButton1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
textView1.setBackgroundColor(Color.RED);
}
});
imageButton2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
textView1.setBackgroundColor(Color.GREEN);
}
});
imageButton3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
textView1.setBackgroundColor(Color.BLUE);
}
});
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
textView1.setBackgroundColor(Color.TRANSPARENT);
}
});
}
}
|
package com.cssweb.android.trade.stock;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.cssweb.android.base.CssBaseActivity;
import com.cssweb.android.common.CssLog;
import com.cssweb.android.common.Global;
import com.cssweb.android.connect.ConnPool;
import com.cssweb.android.main.R;
import com.cssweb.android.trade.util.TradeUtil;
public class AssetQuery extends CssBaseActivity {
private static final String DEBUG_TAG = "AssetQuery";
private LinearLayout assetLayout;
private TextView rmbTextView;
private TextView gbTextView;
private TextView dollersTextView;
private TextView yue;
private TextView keyong;
private TextView zichan;
private TextView cankaoshizhi;
private TextView yingkui;
private Map<String, Map<String, String>> fundMap = null;
private double rmbyk = 0l;
private double myyk = 0l;
private double gbyk = 0l;
private double rmbsz = 0l;
private double mysz = 0l;
private double gbsz = 0l;
private Thread thread = null;
private JSONObject positionData = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.zr_trade_asset_list);
initTitle(R.drawable.njzq_title_left_back, 0, "账户资产");
String[] toolbarNames = { "", "", "", "", "", "刷新" };
initToolBar(toolbarNames, Global.BAR_TAG);
setBtnStatus();
initPopupWindow();
assetLayout = (LinearLayout) findViewById(R.id.asset_bg);
rmbTextView = (TextView) findViewById(R.id.rmb);
gbTextView = (TextView) findViewById(R.id.gb);
dollersTextView = (TextView) findViewById(R.id.dollers);
rmbTextView.setOnClickListener(listener);
gbTextView.setOnClickListener(listener);
dollersTextView.setOnClickListener(listener);
yue = (TextView) findViewById(R.id.yue);
keyong = (TextView) findViewById(R.id.keyong);
zichan = (TextView) findViewById(R.id.zichan);
cankaoshizhi = (TextView) findViewById(R.id.cankaoshizhi);
yingkui = (TextView) findViewById(R.id.yingkui);
// listView = (ListView)findViewById(R.id.zr_rt_listview);
showProgress();
}
private View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
Map<String, String> map = null;
int len = 2;
if(v.getId() == R.id.rmb){
assetLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.zr_asset_rmb));
if(fundMap==null || fundMap.size()<=0){
setFundText(len);
return;
}
map = fundMap.get("RMB");
yingkui.setText(TradeUtil.formatNum(rmbyk+"", len));
cankaoshizhi.setText(TradeUtil.formatNum(rmbsz+"", len));
}else if(v.getId() == R.id.gb){
assetLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.zr_asset_gb));
if(fundMap==null || fundMap.size()<=0){
setFundText(len);
return;
}
map = fundMap.get("HKD");
yingkui.setText(TradeUtil.formatNum(gbyk+"", len));
cankaoshizhi.setText(TradeUtil.formatNum(gbsz+"", len));
}else if(v.getId() == R.id.dollers){
assetLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.zr_asset_dollers));
len =3;
if(fundMap==null || fundMap.size()<=0){
setFundText(len);
return;
}
map = fundMap.get("USD");
yingkui.setText(TradeUtil.formatNum(myyk+"", len));
cankaoshizhi.setText(TradeUtil.formatNum(mysz+"", len));
}
if(map!=null){
yue.setText(TradeUtil.formatNum(map.get("FID_ZHYE"), len));
keyong.setText(TradeUtil.formatNum(map.get("FID_KYZJ"), len));
zichan.setText(TradeUtil.formatNum(map.get("FID_ZZC"), len));
}else{
setFundText(len);
}
}
};
private void setFundText(int length){
if(length==2){
yue.setText("0.00");
keyong.setText("0.00");
zichan.setText("0.00");
cankaoshizhi.setText("0.00");
yingkui.setText("0.00");
}else if(length==3){
yue.setText("0.000");
keyong.setText("0.000");
zichan.setText("0.000");
cankaoshizhi.setText("0.000");
yingkui.setText("0.000");
}
}
protected void toolBarClick(int tag, View v) {
switch (tag) {
case 5:
showProgress();
break;
default:
cancelThread();
break;
}
}
protected void cancelThread() {
if(thread!=null) {
thread.interrupt();
}
mHandler.removeCallbacks(r);
hiddenProgressToolBar();
}
protected void onPause() {
mHandler.removeCallbacks(r);
super.onPause();
}
protected void initTitle(int resid1, int resid2, String str) {
super.initTitle(resid1, resid2, str);
changeTitleBg();
}
@Override
protected void init(int type) {
r = new Runnable() {
public void run() {
try {
StringBuffer bf = new StringBuffer();
bf.append("FID_EXFLG=1");
quoteData = ConnPool.sendReq("GET_FUNDS", "303002", bf.toString());
String res = TradeUtil.checkResult(quoteData);
if(res==null) {
positionData = ConnPool.sendReq("GET_POSITION", "304101", bf.toString());
res = TradeUtil.checkResult(positionData);
if (res==null) {
JSONArray jsonArr = positionData.getJSONArray("item");
double rmbyk1 = 0l;
double myyk1 = 0l;
double gbyk1 = 0l;
double rmbsz1 = 0l;
double mysz1 = 0l;
double gbsz1 = 0l;
for(int i=0; i<jsonArr.length()-1; i++){
JSONObject jsonobj = jsonArr.getJSONObject(i);
String bz = jsonobj.getString("FID_BZ");
double yk = Double.parseDouble(jsonobj.getString("FID_TBFDYK"));
double sz = Double.parseDouble(jsonobj.getString("FID_ZXSZ"));
if("RMB".equals(bz)){
rmbyk1 += yk;
rmbsz1 += sz;
}else if("HKD".equals(bz)){
gbyk1+= yk;
gbsz1+=sz;
}else if("USD".equals(bz)){
myyk1+=yk;
mysz1+=sz;
}
}
quoteData.put("rmbyk", rmbyk1);
quoteData.put("gbyk", gbyk1);
quoteData.put("myyk", myyk1);
quoteData.put("rmbsz", rmbsz1);
quoteData.put("gbsz", gbsz1);
quoteData.put("mysz", mysz1);
JSONArray jarr = (JSONArray) quoteData.getJSONArray("item");
fundMap = new HashMap<String, Map<String,String>>();
for(int i=0; i<jarr.length()-1; i++){
JSONObject jsonobj = jarr.getJSONObject(i);
Map<String, String> map = new HashMap<String, String>();
map.put("FID_ZHYE", jsonobj.getString("FID_ZHYE"));//余额
map.put("FID_KYZJ", jsonobj.getString("FID_KYZJ"));//可用
map.put("FID_ZZC", jsonobj.getString("FID_ZZC"));//资产
fundMap.put(jsonobj.getString("FID_BZ"), map);
}
rmbyk = Double.parseDouble(quoteData.getString("rmbyk"));
myyk = Double.parseDouble(quoteData.getString("myyk"));
gbyk = Double.parseDouble(quoteData.getString("gbyk"));
rmbsz = Double.parseDouble(quoteData.getString("rmbsz"));
gbsz = Double.parseDouble(quoteData.getString("gbsz"));
mysz = Double.parseDouble(quoteData.getString("mysz"));
}
}
} catch (JSONException e) {
e.printStackTrace();
CssLog.e(DEBUG_TAG, e.toString());
}
mHandler.sendEmptyMessage(0);
}
};
thread = new Thread(r);
thread.start();
}
@Override
protected void handlerData() {
try {
String res = TradeUtil.checkResult(quoteData);
if (res != null) {
if (res.equals("-1")){
toast("网络连接失败!");
}
else {
toast(res);
}
hiddenProgress();
return;
}
res = TradeUtil.checkResult(positionData);
if (res != null) {
if (res.equals("-1")){
toast("网络连接失败!");
}
else {
toast(res);
}
hiddenProgress();
return;
}
assetLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.zr_asset_rmb));
if(fundMap==null || fundMap.size()<=0){
setFundText(2);
return;
}
Map<String, String> m1 = fundMap.get("RMB");
if(m1!=null){
yue.setText(TradeUtil.formatNum(m1.get("FID_ZHYE"), 2));
keyong.setText(TradeUtil.formatNum(m1.get("FID_KYZJ"), 2));
zichan.setText(TradeUtil.formatNum(m1.get("FID_ZZC"), 2));
cankaoshizhi.setText(TradeUtil.formatNum(rmbsz+"", 2));
yingkui.setText(TradeUtil.formatNum(rmbyk+"", 2));
}else{
setFundText(2);
}
} catch (JSONException e) {
e.printStackTrace();
CssLog.e(DEBUG_TAG, e.toString());
}
hiddenProgress();
}
private void setBtnStatus(){
setToolBar(0, false, R.color.zr_dimgray);
setToolBar(1, false, R.color.zr_dimgray);
setToolBar(2, false, R.color.zr_dimgray);
setToolBar(3, false, R.color.zr_dimgray);
setToolBar(4, false, R.color.zr_dimgray);
}
}
|
package com.company.collections;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
CustomArrayList<Integer> customArrayList = new CustomArrayList<>();
customArrayList.add(10);
customArrayList.add(20);
customArrayList.add(30);
customArrayList.add(40);
for (int i = 0; i < customArrayList.size(); i++){
System.out.println(customArrayList.get(i));
}
customArrayList.remove(1);
System.out.println();
for (int i = 0; i < customArrayList.size(); i++){
System.out.println(customArrayList.get(i));
}
}
}
|
package com.hackaton.compgenblockdocs.repository;
import com.hackaton.compgenblockdocs.model.DocumentUserModel;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface DocumentUserRepository extends MongoRepository<DocumentUserModel, String> {
}
|
package com.dongluhitec.iotweb.repository;
import com.dongluhitec.iotweb.bean.CommandRes;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CommandResRepository extends CrudRepository<CommandRes, Long> {
Page<CommandRes> findAll(Specification<CommandRes> specification, Pageable page);
List<CommandRes> findByDeviceId(String deviceId);
}
|
package com.mikronia.pixpaint.component;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Objects;
import javax.swing.JPanel;
import com.mikronia.pixpaint.image.ImageBackupManager;
import com.mikronia.pixpaint.image.Image;
import com.mikronia.pixpaint.image.ImageCodec;
import com.mikronia.pixpaint.application.Properties;
import com.mikronia.pixpaint.mouse.MouseButton;
import com.mikronia.pixpaint.painting.Painter;
import com.mikronia.pixpaint.tooling.Tool;
import com.mikronia.pixpaint.utilities.extensions.ColorChannel;
import com.mikronia.pixpaint.utilities.extensions.ColorKt;
import com.mikronia.pixpaint.utilities.extensions.MouseEventKt;
/**
* PixPaint canvas
*
* @version 1.1
* @since 1.0.0
*
* @author Thaynan M. Silva
*/
public class Canvas extends JPanel implements MouseListener, MouseMotionListener, MouseWheelListener {
private static final long serialVersionUID = 1L;
private static final int ZOOM_MINIMUM = 1;
private static final int ZOOM_MAXIMUM = 30;
/////////////////////////
private ArrayList<PixCanvasEventListener> eventListeners = new ArrayList<>();
private Image image;
private Painter painter;
private Tool tool;
/////////////////////////
private boolean transparent = false;
private boolean imageCreated = false;
private boolean imageEdited = false;
private boolean imageLoaded = false;
/////////////////////////
private Point mousePressedPosition = null;
private Point mouseOverlaidPixel = new Point();
private Point imagePosition = new Point();
private MouseButton mouseButton = MouseButton.None;
private int pixelSize = 2;
public Canvas() {
super(true);
this.setFocusable(true);
this.requestFocus();
this.addMouseListener(this);
this.addMouseWheelListener(this);
this.addMouseMotionListener(this);
this.painter = new Painter(this);
}
/////////////////////////
public void createImage(int width, int height, boolean transparent) {
this.image = new Image(width, height, transparent);
this.transparent = transparent;
this.imageCreated = true;
this.centralizeImage();
this.fireEventChange("canvasImageCreated");
}
public void loadImage(ImageCodec codec, InputStream stream) {
this.resetCanvas();
this.image = (Image) codec.readImage(stream);
this.imageLoaded = true;
this.centralizeImage();
this.fireEventChange("canvasImageLoaded");
}
public void saveImage(ImageCodec codec, OutputStream out) {
if (!isCanvasDrawable()) return;
codec.writeImage(image, out);
this.imageEdited = false;
this.fireEventChange("canvasImageSaved");
}
public void resizeImage(int newWidth, int newHeight) {
if (!this.isCanvasDrawable()) {
return;
}
var newImage = new Image(newWidth, newHeight, this.transparent);
var graphics = newImage.createGraphics();
graphics.drawImage(this.image, 0, 0, this);
graphics.dispose();
this.image = newImage;
this.imageEdited = true;
this.fireEventChange("canvasImageResized");
}
public void resetCanvas() {
this.backupImage();
this.transparent = false;
this.imageCreated = false;
this.imageLoaded = false;
this.imageEdited = false;
this.tool = null;
this.image = null;
this.fireEventChange("canvasReset");
}
public void centralizeImage() {
if (this.isCanvasDrawable()) {
this.imagePosition.x = (this.getWidth() - (this.image.getWidth() * this.pixelSize)) / 2;
this.imagePosition.y = (this.getHeight() - (this.image.getWidth() * this.pixelSize)) / 2;
this.fireEventChange(null);
}
}
/////////////////////////
public void addCanvasEventListener(PixCanvasEventListener listener) {
Objects.requireNonNull(listener, "listener == null");
this.eventListeners.add(listener);
}
public void removeCanvasEventListener(PixCanvasEventListener listener) {
Objects.requireNonNull(listener, "listener == null");
this.eventListeners.remove(listener);
}
/////////////////////////
public void setImagePosition(Point imagePosition) {
this.imagePosition = imagePosition;
this.fireEventChange(null);
}
public void setImage(Image image) {
this.image = image;
this.imageEdited = true;
this.backupImage();
}
public void setTool(Tool tool) {
this.tool = tool;
if (tool != null) {
tool.onSelected();
}
}
/////////////////////////
public boolean isCanvasImageCreated() {
return this.imageCreated;
}
public boolean isCanvasImageLoaded() {
return this.imageLoaded;
}
public boolean isCanvasImageEdited() {
return this.imageEdited;
}
public boolean isCanvasDrawable() {
return this.imageCreated || this.imageLoaded;
}
public boolean isMouseOnImage() {
var mousePosition = super.getMousePosition();
if (mousePosition != null) {
return this.getImageBounds().
contains(mousePosition);
}
return false;
}
/////////////////////////
public Point getPixelMousePosition() {
return new Point(this.mouseOverlaidPixel);
}
public Rectangle getImageBounds() {
if (!this.isCanvasDrawable())
return new Rectangle();
return new Rectangle(this.imagePosition.x, this.imagePosition.y,
this.image.getWidth() * this.pixelSize,
this.image.getHeight() * this.pixelSize);
}
public Point getImagePosition() {
return new Point(this.imagePosition);
}
public Dimension getImageSize() {
if (this.image == null) {
return null;
}
return new Dimension(this.image.getWidth(),
this.image.getHeight());
}
public Image getImage() {
return this.image;
}
public Painter getPainter() {
return this.painter;
}
public Tool getTool() {
return this.tool;
}
public int getPixelSize() {
return this.pixelSize;
}
/////////////////////////
@Override
public void paint(Graphics baseGraphics) {
super.paint(baseGraphics);
Graphics2D graphics = (Graphics2D) baseGraphics;
if (this.image != null) {
int xx = this.imagePosition.x;
int yy = this.imagePosition.y;
int ww = this.image.getWidth() * this.pixelSize;
int hh = this.image.getHeight() * this.pixelSize;
graphics.drawRect(xx, yy, ww - 1, hh - 1);
graphics.drawImage(this.image, xx, yy, ww, hh, this);
drawCurrentToolElements(graphics);
drawCanvasGrid(graphics);
}
drawDisabledOverlay(graphics);
}
private void drawCanvasGrid(Graphics2D graphics) {
if (Properties.getGridActive()) {
int gridWidth = Properties.getGridWidth();
int gridHeight = Properties.getGridHeight();
int totalLinesX = this.image.getWidth() / gridWidth;
int totalLinesY = this.image.getHeight() / gridHeight;
int cellWidth = (this.image.getWidth() / totalLinesX) * this.pixelSize;
int cellHeight = (this.image.getHeight() / totalLinesY) * this.pixelSize;
int zoomedImageWidth = this.image.getWidth() * this.pixelSize;
int zoomedImageHeight = this.image.getHeight() * this.pixelSize;
graphics.setXORMode(Color.white);
graphics.setColor(Color.black);
// draw vertical lines
for (int x = 1; x < totalLinesX; x++) {
int xx = x * cellWidth;
graphics.drawLine(this.imagePosition.x + xx, this.imagePosition.y,
this.imagePosition.x + xx, this.imagePosition.y + zoomedImageHeight - 1);
}
// draw horizontal lines
for (int y = 1; y < totalLinesY; y++) {
int yy = y * cellHeight;
graphics.drawLine(this.imagePosition.x, this.imagePosition.y + yy,
this.imagePosition.x + zoomedImageWidth - 1, this.imagePosition.y + yy);
}
graphics.dispose();
}
}
private void drawCurrentToolElements(Graphics2D graphics) {
if (isEnabled() && this.tool != null) {
this.tool.paint(this, graphics);
}
}
private void drawDisabledOverlay(Graphics2D graphics) {
if (!isEnabled()) {
graphics.setColor(ColorKt.getLevel(getBackground(), 0.3f, ColorChannel.Alpha));
graphics.fillRect(0, 0, getWidth(), getHeight());
}
}
/////////////////////////
private void updateMousePosition(MouseEvent e) {
if (isMouseOnImage()) {
this.mouseOverlaidPixel.x = (e.getX() - this.imagePosition.x) / this.pixelSize;
this.mouseOverlaidPixel.y = (e.getY() - this.imagePosition.y) / this.pixelSize;
this.fireEventChange(null);
}
}
private void useTool() {
if (this.mouseButton == MouseButton.Middle)
return;
if (this.tool != null && isCanvasDrawable() && isMouseOnImage()) {
this.tool.drawCanvas(this, mouseButton);
this.fireEventChange("canvasToolUsed");
this.backupImage();
}
}
private void backupImage() {
if (this.image != null) {
ImageBackupManager.backupImage(this.image);
this.fireEventChange("canvasBackedUp");
}
}
/////////////////////////
@Override
public void mousePressed(MouseEvent e) {
if (!isEnabled()) {
return;
}
this.mouseButton = MouseEventKt.getMouseButton(e);
if (MouseEventKt.getMouseButton(e) == MouseButton.Middle) {
this.mousePressedPosition = e.getPoint();
this.fireEventChange(null);
} else {
useTool();
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (!isEnabled()) return;
if (MouseEventKt.getMouseButton(e) == MouseButton.Middle) {
this.mousePressedPosition = null;
this.fireEventChange(null);
} else {
this.mouseButton = MouseButton.None;
}
this.fireEventChange(null);
}
@Override
public void mouseDragged(MouseEvent e) {
if (!isEnabled()) {
return;
}
if (this.mousePressedPosition != null) {
var currentPosition = e.getPoint();
int diffX = currentPosition.x - this.mousePressedPosition.x;
int diffY = currentPosition.y - this.mousePressedPosition.y;
this.mousePressedPosition = currentPosition;
this.imagePosition.x += diffX;
this.imagePosition.y += diffY;
this.fireEventChange(null);
}
if (isMouseOnImage()) {
updateMousePosition(e);
useTool();
}
}
@Override
public void mouseMoved(MouseEvent e) {
if (!isEnabled()) {
return;
}
updateMousePosition(e);
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
if (!isEnabled()) {
return;
}
this.pixelSize += e.getPreciseWheelRotation() < 0 ? 1 : -1;
if (this.pixelSize - 1 < ZOOM_MINIMUM)
this.pixelSize = ZOOM_MINIMUM;
if (this.pixelSize + 1 > ZOOM_MAXIMUM)
this.pixelSize = ZOOM_MAXIMUM;
fireEventChange("canvasZoomChanged");
}
/////////////////////////
private void fireEventChange(String event) {
for (var listener : this.eventListeners) {
if (event != null) {
switch (event) {
case "canvasImageCreated":
listener.onCanvasImageCreated(this);
break;
case "canvasImageLoaded":
listener.onCanvasImageLoaded(this);
break;
case "canvasImageSaved":
listener.onCanvasImageSaved(this);
break;
case "canvasImageResized":
listener.onCanvasImageResized(this);
break;
case "canvasZoomChanged":
listener.onCanvasZoomChanged(this);
break;
case "canvasReset":
listener.onCanvasReset(this);
break;
case "canvasBackedUp":
listener.onCanvasBackedUp(this);
break;
case "canvasToolUsed":
listener.onCanvasToolUsed(this);
break;
default:
break;
}
}
listener.onCanvasUpdate(this);
}
this.repaint();
}
/////////////////////////
/**
* PixPaint canvas event listener
*
* @since PixPaint 1.0.9
* @version 1.0
*
* @author Thaynan M. Silva
*/
public interface PixCanvasEventListener {
default void onCanvasImageCreated(Canvas canvas) {}
default void onCanvasImageLoaded(Canvas canvas) {}
default void onCanvasImageSaved(Canvas canvas) {}
default void onCanvasImageResized(Canvas canvas) {}
default void onCanvasBackedUp(Canvas canvas) {}
default void onCanvasReset(Canvas canvas) {}
default void onCanvasZoomChanged(Canvas canvas) {}
default void onCanvasToolUsed(Canvas canvas) {}
default void onCanvasUpdate(Canvas canvas) {}
}
/////////////////////////
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
}
|
package com.example.model;
import java.io.Serializable;
public class ThongBao implements Serializable {
private String user;
private String title;
private String messege;
private String date;
public ThongBao(String user, String title, String messege, String date) {
this.user = user;
this.title = title;
this.messege = messege;
this.date = date;
}
public ThongBao() {
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getMessege() {
return messege;
}
public void setMessege(String messege) {
this.messege = messege;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
|
package com.fatosajvazi;
public class Main {
public static void main(String[] args) {
// write your code here
// int switchValue = 3;
//
// switch (switchValue){
// case 1:
// System.out.println("Value was 1");
// break;
// case 2:
// System.out.println("Value was 2");
// break;
// default:
// System.out.println("Value was not 1 or 2");
// break;
// }
char character = 'F';
switch (character){
case 'A': case 'B': case 'C': case 'D': case 'E':
System.out.println(character + " found");
break;
default:
System.out.println("None of the requested characters was found");
break;
}
}
}
|
package com.fleet.chat.turing;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TuringApplicationTests {
}
|
package com.example.radio.Activity;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.app.DatePickerDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.WindowManager;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.radio.Adapter.SpinnerAdapterA;
import com.example.radio.Model.RegisterModel;
import com.example.radio.R;
import com.example.radio.databinding.ActivitySignUpBinding;
import com.example.radio.utils.PhoneTextFormatter;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import de.hdodenhof.circleimageview.CircleImageView;
public class SignUpActivity extends AppCompatActivity implements MultiplePermissionsListener {
ActivitySignUpBinding activitySignup2Binding;
String emailPattern, regexStr;
static String mselector;
private DatabaseReference databaseReference;
private FirebaseAuth mAuth;
String imageUri ="";
Spinner spinner, spinner2;
boolean verifyCheck = false;
AlertDialog dialog5;
String uid = null;
String ischecked = "0";
CircleImageView profile_img;
Calendar myCalendar;
EditText userEdittext, userAdharCard;
RadioGroup rg;
RadioButton radiohr, radioemp;
FirebaseStorage storage;
StorageReference storageRef;
TextView textView, textview2;
String chechedstatus = "0";
private static final Pattern PASSWORD_PATTERN =
Pattern.compile("^" +
"(?=.*[@#$%^&+=])" + // at least 1 special character
"(?=\\S+$)" + // no white spaces
".{4,}" + // at least 4 characters
"$");
String imageurl2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activitySignup2Binding= ActivitySignUpBinding.inflate(getLayoutInflater());
setContentView(activitySignup2Binding.getRoot());
profile_img = findViewById(R.id.imageview_account_profile);
emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";
regexStr = "^[0-9]$";
rg = findViewById(R.id.rbg);
spinner = findViewById(R.id.editTextTextPersonName7);
spinner2 = findViewById(R.id.editTextTextPersonbloodgroup);
radiohr = findViewById(R.id.radiobuttomHr);
radioemp = findViewById(R.id.radiobuttonemp);
textView = findViewById(R.id.errortxt);
textview2 = findViewById(R.id.errortxt2);
userEdittext = findViewById(R.id.editTextTextPersonName6);
userEdittext.addTextChangedListener(new PhoneTextFormatter(userEdittext, " ##### #####"));
userAdharCard = findViewById(R.id.editTextTextPersonAharCard);
userAdharCard.addTextChangedListener(new PhoneTextFormatter(userAdharCard, " #### #### ####"));
String[] courses = new String[]{"Designation", "Junior", "Senior", "Trainee"};
String blodGroup[] = new String[]{"Blood group", "A+", "A-", "B+", "B-", "O+", "O-", "AB+", "AB-"};
databaseReference = FirebaseDatabase.getInstance().getReference().child("user");
mAuth = FirebaseAuth.getInstance();
myCalendar = Calendar.getInstance();
activitySignup2Binding.editTextTextPersonName7.setAdapter(new SpinnerAdapterA(this, R.layout.custom_layout, courses));
activitySignup2Binding.editTextTextPersonbloodgroup.setAdapter(new SpinnerAdapterA(this, R.layout.custom_layout, blodGroup));
RadioButton value = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
mselector = value.getText().toString();
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radiobuttonemp:
mselector = radioemp.getText().toString();
break;
case R.id.radiobuttomHr:
mselector = radiohr.getText().toString();
}
}
});
activitySignup2Binding.logintextview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(SignUpActivity.this, LoginNewActivity.class));
}
});
DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel();
}
};
DatePickerDialog.OnDateSetListener date1 = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stu
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel1();
}
};
activitySignup2Binding.spinner2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DatePickerDialog dialog = new DatePickerDialog(SignUpActivity.this, R.style.MySpinnerDatePickerStyle, date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH));
dialog.getDatePicker().setMaxDate(System.currentTimeMillis());
dialog.show();
}
});
activitySignup2Binding.editTextTextPersonName7.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
activitySignup2Binding.editTextTextPersonDate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DatePickerDialog datePickerDialog = new DatePickerDialog(SignUpActivity.this, R.style.MySpinnerDatePickerStyle, date1, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis());
datePickerDialog.show();
}
});
activitySignup2Binding.floatingactionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Dexter.withContext(SignUpActivity.this)
.withPermissions(
Manifest.permission.CAMERA,
Manifest.permission.READ_CONTACTS,
Manifest.permission.RECORD_AUDIO
).withListener(new MultiplePermissionsListener() {
@Override
public void onPermissionsChecked(MultiplePermissionsReport report) {/* ... */}
@Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {/* ... */}
}).check();
Intent gallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
gallery.setType("image/*");
//gallery.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(gallery, "Select Picture"), 200);
// startActivityForResult(gallery,200);
}
});
activitySignup2Binding.signupTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sotreFirebaseData();
}
});
}
private void sotreFirebaseData() {
String mobilenumber = activitySignup2Binding.editTextTextPersonName6.getText().toString();
String addharcard = activitySignup2Binding.editTextTextPersonAharCard.getText().toString();
String username = activitySignup2Binding.editTextTextPersonName.getText().toString();
String password1 = activitySignup2Binding.textINputLayout.getEditText().getText().toString();
String useremail = activitySignup2Binding.userEmail.getText().toString();
String userdesignation = activitySignup2Binding.editTextTextPersonName7.getSelectedItem().toString();
String userdateofjoin = activitySignup2Binding.spinner2.getText().toString();
String userdob = activitySignup2Binding.editTextTextPersonDate.getText().toString();
String useraddress = activitySignup2Binding.editTextTextPersonAddress.getText().toString();
String bloodgrp = activitySignup2Binding.editTextTextPersonbloodgroup.getSelectedItem().toString();
String password = activitySignup2Binding.textINputLayout.getEditText().getText().toString().trim();
String confpassword = activitySignup2Binding.conforomTextinputLayout.getEditText().getText().toString().trim();
String company_email = activitySignup2Binding.editTextTextCompanyEmail.getText().toString().trim();
int selectedItemOfMySpinner = spinner.getSelectedItemPosition();
String actualPositionOfMySpinner = (String) spinner.getItemAtPosition(selectedItemOfMySpinner);
if (profile_img == null) {
Toast.makeText(this, "Please Select Image", Toast.LENGTH_SHORT).show();
} else if (activitySignup2Binding.editTextTextPersonName.getText().toString().isEmpty()) {
activitySignup2Binding.editTextTextPersonName.setError("Filled Required");
} else if (activitySignup2Binding.userEmail.getText().toString().isEmpty()) {
activitySignup2Binding.userEmail.setError("Filled Required");
activitySignup2Binding.userEmail.requestFocus();
} else if (!activitySignup2Binding.userEmail.getText().toString().trim().matches(emailPattern)) {
activitySignup2Binding.userEmail.setError("Enter Valid Email");
activitySignup2Binding.userEmail.requestFocus();
} else if (activitySignup2Binding.textINputLayout.getEditText().getText().toString().isEmpty()) {
activitySignup2Binding.EditTextName1.setError("Filled required");
activitySignup2Binding.EditTextName1.requestFocus();
} else if (activitySignup2Binding.conforomTextinputLayout.getEditText().getText().toString().isEmpty()) {
activitySignup2Binding.conforomTextinputLayout.setPasswordVisibilityToggleEnabled(false);
activitySignup2Binding.confPasswordEditTextView.setError("Filled required");
activitySignup2Binding.confPasswordEditTextView.requestFocus();
} else if (!PASSWORD_PATTERN.matcher(activitySignup2Binding.textINputLayout.getEditText().getText().toString()).matches()) {
activitySignup2Binding.EditTextName1.setError("at least 1 special character");
activitySignup2Binding.EditTextName1.requestFocus();
} else if (!password.equals(confpassword)) {
activitySignup2Binding.conforomTextinputLayout.setPasswordVisibilityToggleEnabled(false);
activitySignup2Binding.confPasswordEditTextView.setError("Password Not Match");
activitySignup2Binding.confPasswordEditTextView.requestFocus();
} else if (mobilenumber.isEmpty()) {
activitySignup2Binding.editTextTextPersonName6.setError("Filled required");
activitySignup2Binding.editTextTextPersonName6.requestFocus();
} else if (mobilenumber.length() < 12 || mobilenumber.length() > 13 || mobilenumber.matches(regexStr)) {
activitySignup2Binding.editTextTextPersonName6.setError("Enter valid phone number");
activitySignup2Binding.editTextTextPersonName6.requestFocus();
} else if (spinner.getSelectedItem().toString().trim().equals("Designation")) {
// Toast.makeText(this, "designation", Toast.LENGTH_SHORT).show();
// textView.setVisibility(View.VISIBLE);
textView.setError("Filled Requied");
textView.requestFocus();
// View selectedView = spinner.getSelectedView();
// if (selectedView != null && selectedView instanceof TextView) {
// TextView selectedTextView = (TextView) selectedView;
//
// // String errorString = selectedTextView.getResources().getString(mErrorStringResource);
// selectedTextView.setError("errorString");
//
//
// }
} else if (activitySignup2Binding.spinner2.getText().toString().isEmpty()) {
activitySignup2Binding.spinner2.setError("Filled required");
activitySignup2Binding.spinner2.requestFocus();
} else if (activitySignup2Binding.editTextTextPersonDate.getText().toString().isEmpty()) {
activitySignup2Binding.editTextTextPersonDate.setError("Filled required");
activitySignup2Binding.editTextTextPersonDate.requestFocus();
} else if (activitySignup2Binding.editTextTextPersonAddress.getText().toString().isEmpty()) {
activitySignup2Binding.editTextTextPersonAddress.setError("Filled required");
activitySignup2Binding.editTextTextPersonAddress.requestFocus();
} else if (addharcard.isEmpty()) {
activitySignup2Binding.editTextTextPersonAharCard.setError("Filled required");
activitySignup2Binding.editTextTextPersonAharCard.requestFocus();
} else if (addharcard.length() < 15 || mobilenumber.length() > 16) {
activitySignup2Binding.editTextTextPersonAharCard.setError("Enter valid Adharcard number");
activitySignup2Binding.editTextTextPersonAharCard.requestFocus();
} else if (spinner2.getSelectedItem().toString().trim().equals("Blood group")) {
textview2.setVisibility(View.VISIBLE);
textview2.setError("Filled Requied");
textview2.requestFocus();
//
// View selectedView = spinner2.getSelectedView();
//
// TextView selectedTextView = (TextView) selectedView;
// Toast.makeText(this, "please blood Group select", Toast.LENGTH_SHORT).show();
// selectedTextView.setError("Error blood group");
} else if (activitySignup2Binding.editTextTextCompanyEmail.getText().toString().trim().isEmpty()) {
activitySignup2Binding.editTextTextCompanyEmail.setError("Filled required");
activitySignup2Binding.editTextTextCompanyEmail.requestFocus();
} else if (activitySignup2Binding.editTextTextCompanyEmail.getText().toString().isEmpty()) {
activitySignup2Binding.editTextTextCompanyEmail.setError("Enter Company Email");
activitySignup2Binding.editTextTextCompanyEmail.requestFocus();
} else if (!activitySignup2Binding.editTextTextCompanyEmail.getText().toString().trim().matches(emailPattern)) {
activitySignup2Binding.editTextTextCompanyEmail.setError("Enter Company valid Email");
activitySignup2Binding.editTextTextCompanyEmail.requestFocus();
} else {
mAuth.createUserWithEmailAndPassword(company_email, password1).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
AlertDialog.Builder builder3 = new AlertDialog.Builder(SignUpActivity.this);
dialog5 = builder3.create();
View view4 = getLayoutInflater().inflate(R.layout.spinner_dialoge, null, false);
ProgressBar progressBar23 = view4.findViewById(R.id.progressbar43);
progressBar23.setVisibility(View.VISIBLE);
dialog5.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog5.setView(view4);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
dialog5.show();
uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
StorageReference storageRef = FirebaseStorage.getInstance().getReference("Images");
StorageReference ref = storageRef.child(System.currentTimeMillis() + "." + getExtension(imageUri));
ref.putFile(Uri.parse(imageUri)).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> firebaseUri = taskSnapshot.getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
imageurl2 = uri.toString();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
}
});
}
});
RegisterModel model = new RegisterModel(uid, username, useremail, password, mobilenumber, userdesignation, userdateofjoin,
userdob, useraddress, addharcard, bloodgrp, company_email, imageurl2, chechedstatus, ischecked, verifyCheck);
model.setMselected(mselector);
databaseReference.child(uid).setValue(model).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
dialog5.dismiss();
mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
// FirebaseStorage storage = FirebaseStorage.getInstance();
// StorageReference storageRef = storage.getReference().child("userchild");
// storageRef.child("Img").putFile(Uri.parse(imageUri)).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
// @Override
// public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//
// Toast.makeText(SignupActivity2.this, "successs", Toast.LENGTH_SHORT).show();
// }
// });
AlertDialog.Builder builder2 = new AlertDialog.Builder(SignUpActivity.this);
AlertDialog dialog1 = builder2.create();
dialog1.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
View view2 = getLayoutInflater().inflate(R.layout.alertdialog, null);
dialog1.setView(view2);
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
// WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
////
TextView btn = view2.findViewById(R.id.Button12);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
startActivity(new Intent(SignUpActivity.this, LogActivity.class));
dialog1.dismiss();
}
});
dialog1.show();
} else {
Toast.makeText(SignUpActivity.this, "" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
} else {
Toast.makeText(SignUpActivity.this, "" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
} else {
Toast.makeText(SignUpActivity.this, "user already sigg up ", Toast.LENGTH_SHORT).show();
}
}
});
}
}
private String getString(String s) {
return "Fileed require";
}
private void updateLabel1() {
String myFormat = "dd /MM /yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
activitySignup2Binding.editTextTextPersonDate.setText(sdf.format(myCalendar.getTime()));
}
private void updateLabel() {
String myFormat = "dd /MM /yyyy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
activitySignup2Binding.spinner2.setText(sdf.format(myCalendar.getTime()));
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 200 && resultCode == RESULT_OK && data != null) {
imageUri = String.valueOf(data.getData());
if (imageUri != null) {
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.parse(imageUri));
profile_img.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
} else {
profile_img = null;
}
}
}
private String getExtension(String filePath) {
ContentResolver cr = getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(cr.getType(Uri.parse(filePath)));
}
@Override
public void onPermissionsChecked(MultiplePermissionsReport multiplePermissionsReport) {
}
@Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> list, PermissionToken permissionToken) {
}
private void setSpinnerError(Spinner spinner, String error) {
View selectedView = spinner.getSelectedView();
if (selectedView != null && selectedView instanceof TextView) {
spinner.requestFocus();
TextView selectedTextView = (TextView) selectedView;
selectedTextView.setError("error"); // any name of the error will do
selectedTextView.setTextColor(Color.RED); //text color in which you want your error message to be displayed
selectedTextView.setText(error); // actual error message
spinner.performClick(); // to open the spinner list if error is found.
}
}
}
|
package workstarter.repository;
import workstarter.domain.CompanyAdmin;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.*;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Optional;
/**
* Spring Data JPA repository for the CompanyAdmin entity.
*/
@SuppressWarnings("unused")
public interface CompanyAdminRepository extends JpaRepository<CompanyAdmin,Long> {
Optional<CompanyAdmin> findOneByActivationKey(String activationKey);
List<CompanyAdmin> findAllByActivatedIsFalseAndCreatedDateBefore(ZonedDateTime dateTime);
Optional<CompanyAdmin> findOneByResetKey(String resetKey);
Optional<CompanyAdmin> findOneByEmail(String email);
Optional<CompanyAdmin> findOneByLogin(String login);
@EntityGraph(attributePaths = "authorities")
CompanyAdmin findOneWithAuthoritiesById(Long id);
@EntityGraph(attributePaths = "authorities")
Optional<CompanyAdmin> findOneWithAuthoritiesByLogin(String login);
Page<CompanyAdmin> findAllByLoginNot(Pageable pageable, String login);
}
|
package il.ac.huji.todolist;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.json.JSONObject;
import com.parse.FindCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.PushService;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class TodoDAL {
TodoDB DBAccess;
public TodoDB getDBAccess()
{
return this.DBAccess;
}
//ParseObject todoObg;
public TodoDAL(Context context)
{
DBAccess = new TodoDB(context);
//deleteDatabase();
Parse.initialize(context, context.getResources().getString(R.string.parseApplication), context.getResources().getString(R.string.clientKey));
PushService.subscribe(context, "", TodoListManagerActivity.class);
PushService.setDefaultPushCallback(context, TodoListManagerActivity.class);
ParseUser.enableAutomaticUser();
//this.todoObg = new ParseObject("todo");
//Parse init
}
public boolean insert(ITodoItem todoItem)
{
if(todoItem == null || todoItem.getTitle() == null)
{
return false;
}
/*
boolean update = true;
if (update)
{
update(todoItem);
return true;
}
*/
SQLiteDatabase dbWritter = DBAccess.getWritableDatabase();
ContentValues todo = new ContentValues();
todo.put("title", todoItem.getTitle());
if(todoItem.getDueDate() != null)
{
todo.put("due", todoItem.getDueDate().getTime());
}
else
{
todo.putNull("due");
}
dbWritter.insert("todo", null, todo);
ParseObject parseObj = new ParseObject("todo");
parseObj.put("title", todoItem.getTitle());
if(todoItem.getDueDate() != null)
{
parseObj.put("due", todoItem.getDueDate().getTime());
}
else
{
parseObj.put("due", JSONObject.NULL);
}
parseObj.saveInBackground();
//all();
return true;
}
public boolean update(ITodoItem todoItem)
{
SQLiteDatabase dbWritter = DBAccess.getWritableDatabase();
ContentValues content = new ContentValues();
content.put("due", todoItem.getDueDate().getTime());
dbWritter.update("todo",content, "title = \""+todoItem.getTitle()+"\"", null);
ParseQuery query = new ParseQuery("todo");
final long date = todoItem.getDueDate().getTime();
query.whereEqualTo("title", todoItem.getTitle());
query.findInBackground(new FindCallback() {
@Override
public void done(List<ParseObject> itemList, ParseException e) {
if (e != null) {
return;
}
if (itemList.size() == 0)
{
return;
}
itemList.get(0).put("due", date);
itemList.get(0).saveInBackground();
}
});
return true;
}
public boolean delete(ITodoItem todoItem)
{
ParseQuery query = new ParseQuery("todo");
query.whereEqualTo("title", todoItem.getTitle());
query.findInBackground(new FindCallback() {
@Override
public void done(List<ParseObject> itemList, ParseException e) {
if (e != null || itemList.size() == 0) {
return;
}
if (itemList.size() == 0)
{
return;
}
itemList.get(0).deleteInBackground();
}
});
SQLiteDatabase dbWritter = DBAccess.getWritableDatabase();
dbWritter.delete("todo", "title = \""+todoItem.getTitle()+"\"", null);
all();
return true;
}
public List<ITodoItem> all()
{
SQLiteDatabase dbReader = DBAccess.getReadableDatabase();
List<ITodoItem> allDBitems = new ArrayList<ITodoItem>();
Cursor cursor = dbReader.query("todo", new String[] {"title", "due" }, null, null, null, null, null);
if (!cursor.moveToFirst()){
return allDBitems;
}
do
{
long date = cursor.getLong(cursor.getColumnIndex("due"));
String title = cursor.getString(cursor.getColumnIndex("title"));
allDBitems.add(new ToDoItem(title, new Date(date)));
}
while(cursor.moveToNext());
/*
for (ITodoItem td : allDBitems){
System.out.println(td.getTitle());
}
*/
return allDBitems;
}
public void deleteDatabase() {
SQLiteDatabase db = this.DBAccess.getWritableDatabase();
db.delete("todo", "1", new String[] {});
Log.d("Database stuff", "Database table succesfully deleted");
db.close();
}
}
|
package com.passing.spring.service;
import java.util.List;
import com.passing.hibernate.beans.TbEnFrequency;
public interface AutoCompleteService {
/**
* @param searchStr search string
* @return
*/
public List<String> searchForAutoComplete(String searchStr);
}
|
package com.example.kaptcha.controller;
import com.example.kaptcha.config.KaptchaConfig;
import com.example.kaptcha.config.SessionConstant;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.sun.xml.internal.ws.resources.HttpserverMessages;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Objects;
@Controller
public class CaptchaController {
@Autowired
private DefaultKaptcha defaultKaptcha;
@ResponseBody
@RequestMapping(value = "/getCode")
public void getCaptchaImage(HttpServletRequest request, HttpServletResponse response){
//将kaptcha生成的验证码 保存到session中, 下次客户端传过来的时候做验证码对比
String createdCode = this.defaultKaptcha.createText();
HttpSession session = request.getSession();
session.setAttribute(SessionConstant.IMAGE_CODE, createdCode);
//生成的字符串验证码生成图片验证码
BufferedImage createdImage = this.defaultKaptcha.createImage(createdCode);
//将生成的图片验证码 转换成ByteArrayOutputStream
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//写入图片
try {
ImageIO.write(createdImage, "jpg", byteArrayOutputStream);
}catch (IOException e){
System.out.println("图片写入byteArrayOutputStream失败");
}
//从outputstream中获取二进制图片数据
byte[] createdImageBytes = byteArrayOutputStream.toByteArray();
//使用response输出二进制数据 设置输出类型为image/jpeg类型
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
try {
ServletOutputStream servletOutputStream = response.getOutputStream();
servletOutputStream.write(createdImageBytes);
servletOutputStream.flush();
servletOutputStream.close();
}catch (IOException e){
System.out.println("servletOutpuStream写二进制失败");
}
}
/**
* 验证验证码是否一致
*/
@ResponseBody
@GetMapping(value = "/validateCode")
public String validateCode(HttpServletRequest request, String code){
String rightCode = (String) request.getSession().getAttribute(SessionConstant.IMAGE_CODE);
System.out.println("rightCode = " + rightCode + " code = " + code);
//每次调用验证api后移除session当中的验证码
request.getSession().removeAttribute(SessionConstant.IMAGE_CODE);
if (Objects.deepEquals(code, rightCode)){
return "验证码正确";
}else {
return "验证码错误";
}
}
}
|
package com.nsp.test.fanxing;
import org.junit.Test;
public enum TestEnumMethod
{
SAMPLE1
{
String getInfo()
{
return "sample1";
}
},
SAMPLE2
{
String getInfo()
{
return "sample2";
}
};
abstract String getInfo();
@Test
public void testMethod() {
for (TestEnumMethod testEnumMethod : TestEnumMethod.values()) {
System.out.println(testEnumMethod.getInfo());
}
}
}
|
execute(des, src, registers, memory) {
String source;
if ( src.isRegister() ) {
source = registers.get(src).substring(16);
} else if ( src.isMemory() ) {
source = memory.read(src, 64);
}
BigInteger b1 = new BigInteger(source.substring(8), 16);
Converter con1 = new Converter(b1.intValue() + "");
String r1 = con1.toDoublePrecisionHex();
BigInteger b2 = new BigInteger(source.substring(0, 8), 16);
Converter con2 = new Converter(b2.intValue() + "");
String r2 = con2.toDoublePrecisionHex();
registers.set(des, r2 + r1);
}
|
package org.vow.actos.domain.note;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.vow.actos.domain.annotation.Annotation;
import org.vow.actos.domain.tag.Tag;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import static javax.persistence.GenerationType.IDENTITY;
@Getter
@Setter
@NoArgsConstructor
@Entity
@Table(name = "note")
public class Note {
@Id
@GeneratedValue(strategy = IDENTITY)
private Long id;
private String title;
private String content;
@OneToMany(mappedBy = "note"
// , cascade = CascadeType.ALL, orphanRemoval = true
)
private Collection<Annotation> annotations = new ArrayList<>();
@ManyToMany(
// cascade = CascadeType.ALL
)
private Collection<Tag> tags = new ArrayList<>();
public Note(String title, String content) {
this.title = title;
this.content = content;
}
public static Builder note() {
return new Builder();
}
public static class Builder {
private String title;
private String content;
private List<Tag> tags = new ArrayList<>();
private List<Annotation> annotations= new ArrayList<>();
public Builder title(String title) {
this.title = title;
return this;
}
public Builder content(String content) {
this.content = content;
return this;
}
public Builder tag(Tag tag) {
this.tags.add(tag);
return this;
}
public Builder annotation(Annotation annotation) {
this.annotations.add(annotation);
return this;
}
public Note build() {
Note note = new Note();
note.setTitle(title);
note.setContent(content);
note.setTags(tags);
note.setAnnotations(annotations);
return note;
}
}
}
|
package com.company;
public class PizzaMenu extends BasicPizza{
public PizzaMenu() {
super("Pizza of the day", "Always Thin", "Napolitana ", "mixed ", 14.5);
super.addPizzaAddition1("Coke",0.0);
super.addPizzaAddition2("Cookie",0.0);
}
@Override
public void addPizzaAddition1(String name, double price) {
System.out.println("No addition possible for this menu");
}
@Override
public void addPizzaAddition2(String name, double price) {
System.out.println("No addition possible for this menu");
}
@Override
public void addPizzaAddition3(String name, double price) {
System.out.println("No addition possible for this menu");
}
@Override
public void addPizzaAddition4(String name, double price) {
System.out.println("No addition possible for this menu");
}
@Override
public double itemizePizza() {
return super.itemizePizza();
}
}
|
package com.ibeiliao.pay.api.dto.response.balance;
import com.ibeiliao.pay.api.ApiCode;
import com.ibeiliao.pay.api.ApiResultBase;
/**
* 统计收入情况
* @author linyi 2016/7/22.
*/
public class StatSchoolIncomeResponse extends ApiResultBase {
private static final long serialVersionUID = 1L;
/**
* 学校ID
*/
private long schoolId;
/**
* 收入情况,单位:分,不包含退款的金额
*/
private long income;
/**
* 退款情况,单位:分
*/
private long refund;
public StatSchoolIncomeResponse() {}
public StatSchoolIncomeResponse(long schoolId, long income, long refund) {
super(ApiCode.SUCCESS, "success");
this.schoolId = schoolId;
this.income = income;
this.refund = refund;
}
public long getSchoolId() {
return schoolId;
}
public void setSchoolId(long schoolId) {
this.schoolId = schoolId;
}
public long getIncome() {
return income;
}
public void setIncome(long income) {
this.income = income;
}
public long getRefund() {
return refund;
}
public void setRefund(long refund) {
this.refund = refund;
}
}
|
package lab4Zad1;
public class CaesarCipher {
private static final int SHIFT_LENGTH = 3;
private static final int ALPHABET_LENGTH = 26;
private static char[] alphabet( ){
char[] alphabet = new char[ALPHABET_LENGTH];
char iter = 'A';
for(int i = 0; i < ALPHABET_LENGTH; i++)
alphabet[i] = iter++;
return alphabet;
}
public static void encrypt(String value){
char[] alphabet = alphabet( );
char[] resultString = value.toCharArray();
int index;
for(int i = 0; i < resultString.length; i++){
index = (resultString[i] - 'A' + SHIFT_LENGTH)
% ALPHABET_LENGTH;
resultString[i] = alphabet[index];
}
String result = new String(resultString);
System.out.println(result);
}
public static void decrypt(String value){
char[] alphabet = alphabet( );
char[] resultString = value.toCharArray();
int index;
for(int i = 0; i < resultString.length; i++){
index = ((resultString[i] - 'A') - SHIFT_LENGTH
+ ALPHABET_LENGTH ) % ALPHABET_LENGTH;
resultString[i] = alphabet[index];
}
String result = new String(resultString);
System.out.println(result);
}
}
|
package com.ibeiliao.pay.account.impl.dao;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.ibeiliao.pay.datasource.MyBatisDao;
import com.ibeiliao.pay.account.impl.entity.SchoolBankAccountTransLogPO;
/**
* t_school_bank_account_trans_log 表的操作接口
*
* @author jingyesi 2016-08-08
*/
@MyBatisDao
public interface SchoolBankAccountTransLogDao {
/**
* 保存数据
*
* @param po 要保存的对象
*/
void insert(SchoolBankAccountTransLogPO po);
/**
* 修改数据,以主键更新
*
* @param po - 要更新的数据
* @return 更新的行数
*/
int update(SchoolBankAccountTransLogPO po);
/**
* 根据主键读取记录
*/
SchoolBankAccountTransLogPO get(@Param("logId") long logId);
}
|
package enamel;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
/**
* Write a description of class GpioControllerContainer here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class GpioControllerContainer
{
final GpioController gpio = GpioFactory.getInstance();
public GpioController getGPIO() {
return gpio;
}
}
|
package by.it.example.helpers;
import by.it.example.beans.Weather;
public class TemperatureExtractor {
private TemperatureExtractor() {
}
public static double getCelsius(Weather weather) {
double kelvin = weather.getTemperature();
return kelvin - 273.15;
}
public static double getKelvins(Weather weather) {
return weather.getTemperature();
}
public static double getFahrenheit(Weather weather) {
return 32 + 9.0 / 5.0 * getCelsius(weather);
}
}
|
package com.kodilla.stream;
import com.kodilla.stream.beautifier.PoemBeautifier;
import com.kodilla.stream.book.Book;
import com.kodilla.stream.book.BookDirectory;
import com.kodilla.stream.forumuser.Forum;
import com.kodilla.stream.forumuser.ForumUser;
import com.kodilla.stream.iterate.NumbersGenerator;
import com.kodilla.stream.lambda.ExecuteSaySomething;
import com.kodilla.stream.lambda.Executor;
import com.kodilla.stream.lambda.ExpressionExecutor;
import com.kodilla.stream.lambda.Processor;
import com.kodilla.stream.person.People;
import com.kodilla.stream.reference.FunctionalCalculator;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import static java.time.LocalDate.now;
public class StreamMain {
public static void main(String[] args) {
//Processor processor = new Processor();
/*
ExecuteSaySomething executeSaySomething = new ExecuteSaySomething();
processor.execute(executeSaySomething);
*/
/*
Executor codeToExecute = () -> System.out.println("This is an example text.");
processor.execute(codeToExecute);
*/
/*
processor.execute(() -> System.out.println("This is an example text."));
ExpressionExecutor expressionExecutor = new ExpressionExecutor();
System.out.println("Calculating expressions with lambdas");
expressionExecutor.executeExpression(3, 4, (a, b) -> a + b);
expressionExecutor.executeExpression(3, 4, (a, b) -> a - b);
expressionExecutor.executeExpression(3, 4, (a, b) -> a * b);
expressionExecutor.executeExpression(3, 4, (a, b) -> a / b);
System.out.println("Calculating expressions with method references");
expressionExecutor.executeExpression(3, 4, FunctionalCalculator::addAToB);
expressionExecutor.executeExpression(3, 4, FunctionalCalculator::subBFromA);
expressionExecutor.executeExpression(3, 4, FunctionalCalculator::multiplyAByB);
expressionExecutor.executeExpression(3, 4, FunctionalCalculator::divideAByB);
PoemBeautifier poemToBeautify = new PoemBeautifier();
String poemByJakubSajkowski = "\nJakub Sajkowski - Facebook\n" +
"\n" +
"Pierwszy listopada, oglądam portrety trumienne\n" +
"na Facebooku. Chłopak, z którym nigdy nie rozmawiałem,\n" +
"wysyła mi wiadomość, twierdzi, że jesteśmy znajomymi.\n" +
"To trochę tak, jakbym znał go z nekrologu –\n" +
"\n" +
"teoretycznie jest szansa, że na naszych pogrzebach pojawią się te same osoby.\n" +
"Mamy czterdziestu dwóch wspólnych, te same czterdzieści dwa genotypy\n" +
"\n" +
"zakręcą się wokół nas, jakbyśmy byli genetycznymi bliźniakami.\n" +
"Można by zmieszać krew, namalować martwą naturę,\n" +
"wszyscy się zachwycą, nie będzie rozmów. Tylko harmonijny,\n" +
"jednostajny szczebiot,\n" +
"\n" +
"jak karabin maszynowy,\n" +
"nic nie wyłowisz oprócz łusek.";
String uppercasedPoem = poemToBeautify.beautify(poemByJakubSajkowski, text -> poemByJakubSajkowski.toUpperCase());
System.out.println(uppercasedPoem);
String underscoredPoem = poemToBeautify.beautify(poemByJakubSajkowski, text -> poemByJakubSajkowski.replace(" ", "_"));
System.out.println(underscoredPoem);
System.out.println("Using Stream to generate even numbers from 1 to 20");
NumbersGenerator.generateEven(20);
*/
/*
People.getList().stream()
.map(s -> s.toUpperCase())
.filter(s -> s.length() > 11)
.map(s -> s.substring(0, s.indexOf(' ') + 2) + ".")
.filter(s -> s.substring(0, 1).equals("M"))
.forEach(s -> System.out.println(s));
*/
//BookDirectory theBookDirectory = new BookDirectory();
/*
Map<String, Book> theResultListOfBooks = theBookDirectory.getList().stream()
.filter(book -> book.getYearOfPublication() > 2005)
.collect(Collectors.toMap(Book::getSignature, Book -> Book));
System.out.println("# elements: " + theResultListOfBooks.size());
theResultListOfBooks.entrySet().stream()
.map(entry -> entry.getKey() + ": " + entry.getValue())
.forEach(System.out::println);
*/
/*
String theResultStringOfBooks = theBookDirectory.getList().stream()
.filter(book -> book.getYearOfPublication() > 2005)
.map(Book::toString)
.collect(Collectors.joining(",\n","<<",">>"));
System.out.println(theResultStringOfBooks);
*/
Forum forum = new Forum();
Map<Integer, ForumUser> adultMansWhoCreatedPostsOnForum = forum.getUserList().stream()
.filter(forumUser -> forumUser.getGender() == 'M')
.filter(forumUser -> forumUser.getDateOfBirth().plusYears(19).plusDays(364).isBefore(now()))
.filter(forumUser -> forumUser.getNumberOfPosts() > 0)
.collect(Collectors.toMap(ForumUser::getForumUserID, ForumUser -> ForumUser));
System.out.println("Number of forum users who are mans in age of 20 or older and posted at least one post: " + adultMansWhoCreatedPostsOnForum.size());
adultMansWhoCreatedPostsOnForum.entrySet().stream()
.map(entry -> entry.getKey() + ": " + entry.getValue())
.forEach(System.out::println);
}
}
|
public class pancake_sort {
public static void sort(List<Integer> numbers) {
for(int currentSize = numbers.size(); currentSize > 1; currentSize--) {
int largestIndex = findMaxNum(numbers, currentSize);
if(largestIndex != currentSize-1) {
flip(numbers, largestIndex);
flip(numbers, currentSize-1);
}
}
print(numbers);
}
private static void flip(List<Integer> numbers, int end) {
int temp, start = 0;
while (start < end)
{
temp = numbers.get(start);
numbers.set(start, numbers.get(end));
numbers.set(end, temp);
start++;
end--;
}
}
private static int findMaxNum(List<Integer> numbers, int index) {
int largestIndex = 0;
int largest = 0;
for(int m = 0; m < index; m++) {
if(numbers.get(m) > largest) {
largest = numbers.get(m);
largestIndex = m;
}
}
return largestIndex;
}
private static void print(List<Integer> numbers) {
for(int num: numbers) {
System.out.println(num);
}
}
}
|
package com.uzabase.schema;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="rss")
public class Rss {
@XmlElement(name="channel")
private List<Feed> channel;
public Rss(){}
public List<Feed> getChannel() {
return channel;
}
}
|
package com.hason.dtp.account.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
/**
* Hello, 测试
*
* @author Huanghs
* @since 2.0
* @date 2017/10/17
*/
@RestController
public class HelloController {
@RequestMapping("/hello")
public Object hello() {
return "Hi, " + LocalDateTime.now();
}
}
|
package ru.krasview.kvlib.widget;
import java.util.Map;
import ru.krasview.kvlib.indep.consts.TagConsts;
import ru.krasview.kvlib.indep.consts.TypeConsts;
import ru.krasview.kvlib.interfaces.Factory;
import ru.krasview.kvlib.widget.lists.*;
import android.content.Context;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
public class NavigationViewFactory implements Factory {
private Context c;
public NavigationViewFactory(){
}
@Override
public View getView(Map<String, Object> map, Context context){
c = context;
View view = null;
String type = (String)map.get(TagConsts.TYPE);
// Log.d("Navigation", "type: " + type);
if(type == null) {view = get_null();
}else if(type.equals(TypeConsts.MAIN)) {view = new MainList(c);
}else if(type.equals(TypeConsts.TV)) {view = new TVList(c);
}else if(type.equals(TypeConsts.FAVORITE_TV)) {view = new TVFavoriteList(c);
}else if(type.equals(TypeConsts.MY_ALL)) {view = new UserShowList(c);
}else if(type.equals("my_view")) {view = new UserShowList(c,(String)map.get("section"));
}else if(type.equals(TypeConsts.DESCRIPTION)) {view = new Serial(c, map);
}else if(type.equals("series")) {view = new SeasonList(c, map);
}else if(type.equals("anime")) {view = new SeasonList(c, map);
}else if(type.equals("movie")) {view = new MovieList(c, map);
}else if(type.equals("season_list")) {view = new SeasonList(c, map);
}else if(type.equals(TypeConsts.ALL_SERIES)) {view = new AllSeriesList(c, map);
}else if(type.equals(TypeConsts.SEASON)) {view = new OneSeasonSeriesList(c, map);
}else if(type.equals(TypeConsts.ALL_SHOW)) {view = new AllShowList(c);
}else if(type.equals(TypeConsts.ALL_ANIME)) {view = new AllAnimeList(c);
}else if(type.equals(TypeConsts.ALPHABET_SHOW)) {view = new AlfabetShowList(c);
}else if(type.equals(TypeConsts.ALPHABET_ANIME)){view = new AlfabetAnimeList(c);
}else if(type.equals(TypeConsts.LETTER_SHOW)) {view = new LetterShowList(c, map);
}else if(type.equals(TypeConsts.LETTER_ANIME)) {view = new LetterAnimeList(c, map);
}else if(type.equals(TypeConsts.SEARCH_SHOW)) {view = new SearchShowList(c);
}else if(type.equals(TypeConsts.SEARCH_ANIME)) {view = new SearchAnimeList(c);
}else if(type.equals(TypeConsts.NEW_SERIES)) {view = new NewSeriesList(c, map);
}else if(type.equals(TypeConsts.TV_RECORD)) {view = new TVRecordList(c);
}else if(type.equals(TypeConsts.FAVORITE_TV_RECORD))
{view = new TVFavoriteRecordList(c);
}else if(type.equals(TypeConsts.DATE_LIST)) {view = new DateList(c, map);
}else if(type.equals(TypeConsts.RECORD_LIST)) {view = new RecordList(c, map);
}else if(type.equals(TypeConsts.MOVIE)) {view = new AllMovieList(c, map);
}else if(type.equals(TypeConsts.ALL_MOVIE)) {view = new AllMovieList(c, map);
}else if(type.equals("alfabet_movie")) {view = new AlfabetMovieList(c);
}else if(type.equals("letter_movie")) {view = new LetterMovieList(c, map);
}else if(type.equals("search_movie")) {view = new SearchMovieList(c);
}else if(type.equals("faves")) {view = new FavesList(c, map);
}else if(type.equals(TypeConsts.GENRES)) {view = new AllGenreShowList(c,map);
}else if(type.contains("/genre")) {view = new GenreShowList(c,map);
}else {view = get_unknown(type);
}
if(implementsInterface(view, List.class)){
((List)view).setFactory(this);
((List)view).setOnItemClickListener(new KVItemClickListener(((List)view)));
}
return view;
}
@SuppressWarnings("rawtypes")
private static boolean implementsInterface(Object object, Class inter){
if(inter.isInstance(object)){
return true;
}else{
return false;
}
}
private View get_unknown(String type ){
TextView text = new TextView(c);
text.setText("тип " + type);
text.setTextSize(30);
text.setGravity(Gravity.CENTER);
return text;
//return null;
}
private static View get_null(){
return null;
}
}
|
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.sql.Types;
import java.util.List;
import java.util.Map;
@RestController
public class DruidController {
@Autowired
JdbcTemplate jdbc;
//修改数据
@RequestMapping(value ="/update")
public void update(){
String sql = "UPDATE user SET password = '333' WHERE name = '张三'";
jdbc.update(sql);
}
//添加数据
@RequestMapping(value = "/add")
public void add(){
String sql = "insert into user(name,mobile,password,address) values('张一',1212131223,'12213','江苏省')";
jdbc.update(sql);
}
//查询数据
@RequestMapping(value = "/query")
public List<Map<String,Object>> queryNameListMap(){
String sql = "select * from user";
return this.jdbc.queryForList(sql);
}
//删除数据
@RequestMapping(value = "/delete")
public int deleteUser(String name){
String sql = "delete from user where name = ?";
Object[] args = {name};
int[] argType = {Types.VARCHAR};
return this.jdbc.update(sql,args,argType);
}
}
|
//Josué Alexis Ramírez Pérez A00513622 ITIC 5ª Semestre
/*
* 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 potenciarecursividad;
import java.util.Scanner;
/**
*
* @author josuealexis96
*/
public class PotenciaRecursividad {
public static void main(String[] args) {
int n, p, m, aux2, aux3 = 0;//Se declaran las variables que se usaran
int aux = 0;
Scanner sc = new Scanner (System.in);//Pregunta
//al usuario que número de escalones que quiere bajar
System.out.print("¿Qué número quieres elevar a una potencia? ");
n = sc.nextInt();//Se guarda el resultado en la variable n
aux2 = n;
System.out.print("¿A que potencia quieres elevar el número? ");
p = sc.nextInt();//Se guarda el resultado en la variable p
System.out.println(Potencia.potenciarecursividad(n, p, aux, aux2, aux3));//Se imprime
//el metodo de la clase potencia
}
}
|
package com.sixmac.service.impl;
import com.sixmac.controller.api.PayCallBackApi;
import com.sixmac.controller.common.CommonController;
import com.sixmac.core.Constant;
import com.sixmac.core.bean.Result;
import com.sixmac.dao.*;
import com.sixmac.entity.*;
import com.sixmac.entity.vo.WatchBallVo;
import com.sixmac.service.*;
import com.sixmac.utils.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Administrator on 2016/5/19 0019 上午 11:54.
*/
@Service
public class ReserveServiceImpl implements ReserveService {
@Autowired
private ReserveDao reserveDao;
@Autowired
private UserReserveDao userReserveDao;
@Autowired
private UserDao userDao;
@Autowired
private TeamRaceDao teamRaceDao;
@Autowired
private TeamMemberDao teamMemberDao;
@Autowired
private InsuranceDao insuranceDao;
@Autowired
private OrderDao orderDao;
@Autowired
private MessageOrderBallDao messageOrderBallDao;
@Autowired
private SysExperienceDao sysExperienceDao;
@Autowired
private SysCredibilityDao sysCredibilityDao;
@Autowired
private VipLevelDao vipLevelDao;
@Autowired
private TeamDao teamDao;
@Autowired
private MessageRecordDao messageRecordDao;
@PersistenceContext
private EntityManager em;
@Override
public List<Reserve> findAll() {
return reserveDao.findAll();
}
@Override
public Page<Reserve> find(int pageNum, int pageSize) {
return reserveDao.findAll(new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id"));
}
@Override
public Page<Reserve> find(int pageNum) {
return find(pageNum, Constant.PAGE_DEF_SZIE);
}
@Override
public Reserve getById(Long id) {
return reserveDao.findOne(id);
}
@Override
public Reserve deleteById(Long id) {
Reserve booking = getById(id);
reserveDao.delete(booking);
return booking;
}
@Override
public Reserve create(Reserve booking) {
return reserveDao.save(booking);
}
@Override
public Reserve update(Reserve booking) {
return reserveDao.save(booking);
}
@Override
@Transactional
public void deleteAll(Long[] ids) {
for (Long id : ids) {
deleteById(id);
}
}
@Override
public List<Reserve> findByUserId(Long userId) {
return reserveDao.findByUserId(userId);
}
@Override
public Page<Reserve> page(final Integer timelimit, final Integer type, final Long areaId, Integer pageNum, Integer pageSize) {
PageRequest pageRequest = new PageRequest(pageNum - 1, pageSize, Sort.Direction.DESC, "id");
Page<Reserve> page = reserveDao.findAll(new Specification<Reserve>() {
@Override
public Predicate toPredicate(Root<Reserve> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Predicate result = null;
List<Predicate> predicateList = new ArrayList<Predicate>();
if(timelimit != null) {
long beforeDate = DateUtils.dateAddDay(timelimit * -1).getTime();
predicateList.add(cb.between(root.get("startTime").as(Long.class),beforeDate,System.currentTimeMillis()));
}
if (type != null) {
Predicate pre = cb.equal(root.get("matchType").as(Integer.class), type);
predicateList.add(pre);
}
if (areaId != null) {
Predicate pre = cb.equal(root.get("stadium").get("areaId").as(Integer.class), areaId);
predicateList.add(pre);
}
Predicate pre = cb.equal(root.get("payStatus").as(Integer.class), 1);
predicateList.add(pre);
Predicate pre2 = cb.equal(root.get("reserveType").as(Integer.class), 0);
predicateList.add(pre2);
if (predicateList.size() > 0) {
result = cb.and(predicateList.toArray(new Predicate[]{}));
}
if (result != null) {
query.where(result);
}
return query.getGroupRestriction();
}
}, pageRequest);
return page;
}
@Override
public List<Reserve> findNew() {
String params = "0,1";
Query query = em.createQuery("SELECT r from Reserve r where r.status in (" + params +") and r.reserveType = 0 order by r.id desc",Reserve.class);
query.setMaxResults(1);
List<Reserve> reserveList = query.getResultList();
return reserveList;
}
@Override
public void order(HttpServletResponse response, Long reserveId, Long userId, Long toUserId) {
MessageOrderBall messageOrderBall = new MessageOrderBall();
messageOrderBall.setStatus(0);
messageOrderBall.setUser(userDao.findOne(userId));
messageOrderBall.setToUser(userDao.findOne(userId));
messageOrderBall.setReserve(reserveDao.findOne(reserveId));
messageOrderBallDao.save(messageOrderBall);
// 新增好友约球消息记录
MessageRecord messageRecord = new MessageRecord();
messageRecord.setUserId(toUserId);
messageRecord.setStatus(0);
messageRecord.setMessageId(messageOrderBall.getId());
// 类型(0:好友约球)
messageRecord.setType(0);
messageRecordDao.save(messageRecord);
}
@Override
public Map<String, Object> raceList(HttpServletResponse response, Long playerId) {
Map<String, Object> map = new HashMap<String, Object>();
List<Team> teams = new ArrayList<Team>();
List<TeamMember> teamMemberList = teamMemberDao.findByUserId(playerId);
User user = null;
for (TeamMember teamMember : teamMemberList) {
user = userDao.findOne((teamMember.getUserId()));
if (StringUtils.isNotBlank(user.getAvater())) {
user.setAvater(ConfigUtil.getString("upload.url") + user.getAvater());
}
teams.add(teamDao.findOne(teamMember.getTeamId()));
}
String teamIds = "";
StringBuffer buffer = new StringBuffer("");
for (Team team : teams) {
//根据球队列表查询球队赛事
// select * from t_race r where r.host_id in(1,2,3) or r.visitingid in (1,2,3)
buffer.append(team.getId() + ",");
}
teamIds = buffer.toString().substring(0, buffer.length() - 1);
// 查询主队赛事
String sql = "select a from TeamRace a where a.homeTeam.id in (" + teamIds + ") and a.status = 1";
Query query = em.createQuery(sql);
List<TeamRace> list = (List<TeamRace>) query.getResultList();
//List<TeamRace> list = teamRaceDao.findByHomeTeamId(teamIds);
List<WatchBallVo> watchBallVos = new ArrayList<WatchBallVo>();
for (TeamRace teamRace : list) {
WatchBallVo watchBallVo1 = new WatchBallVo();
if (teamRace.getHomeTeam().getLeaderUser().getId() == playerId) {
watchBallVo1.setMobile(teamRace.getVisitingTeam().getLeaderUser().getMobile());
}
watchBallVo1.setId(teamRace.getId());
watchBallVo1.setStadiumName(teamRace.getAddress());
watchBallVo1.setStartTime(teamRace.getStartTime());
watchBallVo1.setCreateDate(teamRace.getCreateDate());
watchBallVo1.setHomeTeamName(teamRace.getHomeTeam().getName());
if (StringUtils.isNotBlank(teamRace.getHomeTeam().getAvater())) {
watchBallVo1.setHomeTeamAvater(ConfigUtil.getString("upload.url") + teamRace.getHomeTeam().getAvater());
}
watchBallVo1.setvTeamName(teamRace.getVisitingTeam().getName());
if (StringUtils.isNotBlank(teamRace.getVisitingTeam().getAvater())) {
watchBallVo1.setvTeamAvater(ConfigUtil.getString("upload.url") + teamRace.getVisitingTeam().getAvater());
}
watchBallVo1.setStatus(teamRace.getStatus());
watchBallVos.add(watchBallVo1);
}
// 查询客队队赛事
String sql1 = "select a from TeamRace a where a.visitingTeam.id in (" + teamIds + ") and a.status = 1";
Query query1 = em.createQuery(sql1);
List<TeamRace> listrace = (List<TeamRace>) query1.getResultList();
//List<TeamRace> listrace = teamRaceService.findByVisitingId(teamIds);
List<WatchBallVo> watchBallVoList = new ArrayList<WatchBallVo>();
for (TeamRace teamRace : listrace) {
WatchBallVo watchBallVo2 = new WatchBallVo();
if (teamRace.getVisitingTeam().getLeaderUser().getId() == playerId) {
watchBallVo2.setMobile(teamRace.getHomeTeam().getLeaderUser().getMobile());
}
watchBallVo2.setId(teamRace.getId());
watchBallVo2.setStadiumName(teamRace.getAddress());
watchBallVo2.setStartTime(teamRace.getStartTime());
watchBallVo2.setHomeTeamName(teamRace.getHomeTeam().getName());
watchBallVo2.setCreateDate(teamRace.getCreateDate());
if (StringUtils.isNotBlank(teamRace.getHomeTeam().getAvater())) {
watchBallVo2.setHomeTeamAvater(ConfigUtil.getString("upload.url") + teamRace.getHomeTeam().getAvater());
}
watchBallVo2.setvTeamName(teamRace.getVisitingTeam().getName());
if (StringUtils.isNotBlank(teamRace.getVisitingTeam().getAvater())) {
watchBallVo2.setvTeamAvater(ConfigUtil.getString("upload.url") + teamRace.getVisitingTeam().getAvater());
}
watchBallVo2.setStatus(teamRace.getStatus());
if (watchBallVos.getClass().equals(watchBallVo2)) return map;
watchBallVoList.add(watchBallVo2);
}
map.put("watchBallVos", watchBallVos);
map.put("watchBallVoList", watchBallVoList);
try {
System.out.println(JsonUtil.obj2Json(map));
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
@Override
public Order pay(HttpServletResponse response, Long reserveId, Long userId, Long messageId, Double money) {
Reserve reserve = reserveDao.findOne(reserveId);
Order order = null;
if (reserve.getType() == 0) {
if (reserve.getJoinCount() < reserve.getMatchType() * 2) {
Insurance insurance = new Insurance();
//球场已经全额付款的
if (reserve.getPayment() == 0) {
UserReserve userReserve = new UserReserve();
userReserve.setUser(userDao.findOne(userId));
// userReserve.setReserveId(reserveId);
userReserve.setReserve(reserve);
userReserve.setStatus(0);
userReserveDao.save(userReserve);
MessageRecord messageRecord = new MessageRecord();
messageRecord.setUserId(reserve.getUser().getId());
messageRecord.setStatus(0);
messageRecord.setMessageId(userReserve.getId());
messageRecord.setType(1);
messageRecordDao.save(messageRecord);
if (messageId != null) {
MessageOrderBall messageOrderBall = messageOrderBallDao.findOne(messageId);
if (messageRecord != null) {
messageRecord.setStatus(1);
messageRecordDao.save(messageRecord);
}
}
WebUtil.printApi(response, new Result(true));
}
//球场AA付款
if (reserve.getPayment() == 1) {
insurance.setMoney(reserve.getInsurance().getPrice());
money = reserve.getPrice() / reserve.getMatchType();
String sn = CommonUtils.generateSn(); // 订单号
order = new Order();
order.setUser(userDao.findOne(userId));
order.setReserve(reserve);
/*order.setStadium(reserve.getStadium());
order.setSite(reserve.getSite());*/
order.setPrice(money);
order.setAction(1);
order.setSn(sn);
order.setMessageId(messageId);
orderDao.save(order);
// 当前没有支付接口,因此状态直接为已支付
//PayCallBackApi.changeOrderStatus(orderService, order.getSn(), null, response);
}
insurance.setUserId(userId);
insurance.setReserveId(reserve.getId());
insuranceDao.save(insurance);
}
}else if (reserve.getType() == 1){
UserReserve userReserve = new UserReserve();
userReserve.setUser(userDao.findOne(userId));
// userReserve.setReserveId(reserveId);
userReserve.setReserve(reserve);
userReserve.setStatus(0);
userReserveDao.save(userReserve);
MessageRecord messageRecord = new MessageRecord();
messageRecord.setUserId(reserve.getUser().getId());
messageRecord.setStatus(0);
messageRecord.setMessageId(userReserve.getId());
messageRecord.setType(1);
messageRecordDao.save(messageRecord);
if (messageId != null) {
MessageOrderBall messageOrderBall = messageOrderBallDao.findOne(messageId);
if (messageRecord != null) {
messageRecord.setStatus(1);
messageRecordDao.save(messageRecord);
}
}
WebUtil.printApi(response, new Result(true));
}
return order;
}
}
|
/*
* 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 cloudserver;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
/**
*
* @author Smith
*/
public class Administrator extends Thread
{
private Socket _s ;
public Administrator(Socket s)
{
this._s = s;
}
@Override
public void run()
{
DataInputStream inputs = null;
DataOutputStream outs = null;
try
{
inputs = new DataInputStream(_s.getInputStream());
outs = new DataOutputStream(_s.getOutputStream());
while(true)
{
String[] cmd = inputs.readUTF().split(" ");
switch(cmd[0])
{
case "list":
outs.writeUTF(CloudServer.userTable.printToApp());
break;
}
}
} catch (IOException ex)
{
System.out.println(ex.toString());
}
finally
{
try
{
inputs.close();
outs.close();
} catch (IOException ex)
{
}
}
}
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred;
import java.io.*;
import java.net.URI;
import java.util.*;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;
import org.apache.hadoop.io.WritableUtils;
import org.apache.hadoop.mapred.lib.HashPartitioner;
import org.apache.hadoop.mapreduce.server.jobtracker.JTConfig;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.hadoop.fs.*;
/**
* A set of utilities to validate the <b>sort</b> of the map-reduce framework.
* This utility program has 2 main parts:
* 1. Checking the records' statistics
* a) Validates the no. of bytes and records in sort's input & output.
* b) Validates the xor of the md5's of each key/value pair.
* c) Ensures same key/value is present in both input and output.
* 2. Check individual records to ensure each record is present in both
* the input and the output of the sort (expensive on large data-sets).
*
* To run: bin/hadoop jar build/hadoop-examples.jar sortvalidate
* [-m <i>maps</i>] [-r <i>reduces</i>] [-deep]
* -sortInput <i>sort-in-dir</i> -sortOutput <i>sort-out-dir</i>
*/
public class SortValidator extends Configured implements Tool {
static private final IntWritable sortInput = new IntWritable(1);
static private final IntWritable sortOutput = new IntWritable(2);
static public String SORT_REDUCES =
"mapreduce.sortvalidator.sort.reduce.tasks";
static public String MAPS_PER_HOST = "mapreduce.sortvalidator.mapsperhost";
static public String REDUCES_PER_HOST =
"mapreduce.sortvalidator.reducesperhost";
static void printUsage() {
System.err.println("sortvalidate [-m <maps>] [-r <reduces>] [-deep] " +
"-sortInput <sort-input-dir> -sortOutput <sort-output-dir>");
System.exit(1);
}
static private IntWritable deduceInputFile(JobConf job) {
Path[] inputPaths = FileInputFormat.getInputPaths(job);
Path inputFile = new Path(job.get(JobContext.MAP_INPUT_FILE));
// value == one for sort-input; value == two for sort-output
return (inputFile.getParent().equals(inputPaths[0])) ?
sortInput : sortOutput;
}
static private byte[] pair(BytesWritable a, BytesWritable b) {
byte[] pairData = new byte[a.getLength()+ b.getLength()];
System.arraycopy(a.getBytes(), 0, pairData, 0, a.getLength());
System.arraycopy(b.getBytes(), 0, pairData, a.getLength(), b.getLength());
return pairData;
}
private static final PathFilter sortPathsFilter = new PathFilter() {
public boolean accept(Path path) {
return (path.getName().startsWith("part-"));
}
};
/**
* A simple map-reduce job which checks consistency of the
* MapReduce framework's sort by checking:
* a) Records are sorted correctly
* b) Keys are partitioned correctly
* c) The input and output have same no. of bytes and records.
* d) The input and output have the correct 'checksum' by xor'ing
* the md5 of each record.
*
*/
public static class RecordStatsChecker {
/**
* Generic way to get <b>raw</b> data from a {@link Writable}.
*/
static class Raw {
/**
* Get raw data bytes from a {@link Writable}
* @param writable {@link Writable} object from whom to get the raw data
* @return raw data of the writable
*/
public byte[] getRawBytes(Writable writable) {
return writable.toString().getBytes();
}
/**
* Get number of raw data bytes of the {@link Writable}
* @param writable {@link Writable} object from whom to get the raw data
* length
* @return number of raw data bytes
*/
public int getRawBytesLength(Writable writable) {
return writable.toString().getBytes().length;
}
}
/**
* Specialization of {@link Raw} for {@link BytesWritable}.
*/
static class RawBytesWritable extends Raw {
public byte[] getRawBytes(Writable bw) {
return ((BytesWritable)bw).getBytes();
}
public int getRawBytesLength(Writable bw) {
return ((BytesWritable)bw).getLength();
}
}
/**
* Specialization of {@link Raw} for {@link Text}.
*/
static class RawText extends Raw {
public byte[] getRawBytes(Writable text) {
return ((Text)text).getBytes();
}
public int getRawBytesLength(Writable text) {
return ((Text)text).getLength();
}
}
private static Raw createRaw(Class rawClass) {
if (rawClass == Text.class) {
return new RawText();
} else if (rawClass == BytesWritable.class) {
System.err.println("Returning " + RawBytesWritable.class);
return new RawBytesWritable();
}
return new Raw();
}
public static class RecordStatsWritable implements Writable {
private long bytes = 0;
private long records = 0;
private int checksum = 0;
public RecordStatsWritable() {}
public RecordStatsWritable(long bytes, long records, int checksum) {
this.bytes = bytes;
this.records = records;
this.checksum = checksum;
}
public void write(DataOutput out) throws IOException {
WritableUtils.writeVLong(out, bytes);
WritableUtils.writeVLong(out, records);
WritableUtils.writeVInt(out, checksum);
}
public void readFields(DataInput in) throws IOException {
bytes = WritableUtils.readVLong(in);
records = WritableUtils.readVLong(in);
checksum = WritableUtils.readVInt(in);
}
public long getBytes() { return bytes; }
public long getRecords() { return records; }
public int getChecksum() { return checksum; }
}
public static class Map extends MapReduceBase
implements Mapper<WritableComparable, Writable,
IntWritable, RecordStatsWritable> {
private IntWritable key = null;
private WritableComparable prevKey = null;
private Class<? extends WritableComparable> keyClass;
private Partitioner<WritableComparable, Writable> partitioner = null;
private int partition = -1;
private int noSortReducers = -1;
private long recordId = -1;
private Raw rawKey;
private Raw rawValue;
public void configure(JobConf job) {
// 'key' == sortInput for sort-input; key == sortOutput for sort-output
key = deduceInputFile(job);
if (key == sortOutput) {
partitioner = new HashPartitioner<WritableComparable, Writable>();
// Figure the 'current' partition and no. of reduces of the 'sort'
try {
URI inputURI = new URI(job.get(JobContext.MAP_INPUT_FILE));
String inputFile = inputURI.getPath();
// part file is of the form part-r-xxxxx
partition = Integer.valueOf(inputFile.substring(
inputFile.lastIndexOf("part") + 7)).intValue();
noSortReducers = job.getInt(SORT_REDUCES, -1);
} catch (Exception e) {
System.err.println("Caught: " + e);
System.exit(-1);
}
}
}
@SuppressWarnings("unchecked")
public void map(WritableComparable key, Writable value,
OutputCollector<IntWritable, RecordStatsWritable> output,
Reporter reporter) throws IOException {
// Set up rawKey and rawValue on the first call to 'map'
if (recordId == -1) {
rawKey = createRaw(key.getClass());
rawValue = createRaw(value.getClass());
}
++recordId;
if (this.key == sortOutput) {
// Check if keys are 'sorted' if this
// record is from sort's output
if (prevKey == null) {
prevKey = key;
keyClass = prevKey.getClass();
} else {
// Sanity check
if (keyClass != key.getClass()) {
throw new IOException("Type mismatch in key: expected " +
keyClass.getName() + ", received " +
key.getClass().getName());
}
// Check if they were sorted correctly
if (prevKey.compareTo(key) > 0) {
throw new IOException("The 'map-reduce' framework wrongly" +
" classifed (" + prevKey + ") > (" +
key + ") "+ "for record# " + recordId);
}
prevKey = key;
}
// Check if the sorted output is 'partitioned' right
int keyPartition =
partitioner.getPartition(key, value, noSortReducers);
if (partition != keyPartition) {
throw new IOException("Partitions do not match for record# " +
recordId + " ! - '" + partition + "' v/s '" +
keyPartition + "'");
}
}
// Construct the record-stats and output (this.key, record-stats)
byte[] keyBytes = rawKey.getRawBytes(key);
int keyBytesLen = rawKey.getRawBytesLength(key);
byte[] valueBytes = rawValue.getRawBytes(value);
int valueBytesLen = rawValue.getRawBytesLength(value);
int keyValueChecksum =
(WritableComparator.hashBytes(keyBytes, keyBytesLen) ^
WritableComparator.hashBytes(valueBytes, valueBytesLen));
output.collect(this.key,
new RecordStatsWritable((keyBytesLen+valueBytesLen),
1, keyValueChecksum)
);
}
}
public static class Reduce extends MapReduceBase
implements Reducer<IntWritable, RecordStatsWritable,
IntWritable, RecordStatsWritable> {
public void reduce(IntWritable key, Iterator<RecordStatsWritable> values,
OutputCollector<IntWritable,
RecordStatsWritable> output,
Reporter reporter) throws IOException {
long bytes = 0;
long records = 0;
int xor = 0;
while (values.hasNext()) {
RecordStatsWritable stats = values.next();
bytes += stats.getBytes();
records += stats.getRecords();
xor ^= stats.getChecksum();
}
output.collect(key, new RecordStatsWritable(bytes, records, xor));
}
}
public static class NonSplitableSequenceFileInputFormat
extends SequenceFileInputFormat {
protected boolean isSplitable(FileSystem fs, Path filename) {
return false;
}
}
static void checkRecords(Configuration defaults,
Path sortInput, Path sortOutput) throws IOException {
FileSystem inputfs = sortInput.getFileSystem(defaults);
FileSystem outputfs = sortOutput.getFileSystem(defaults);
FileSystem defaultfs = FileSystem.get(defaults);
JobConf jobConf = new JobConf(defaults, RecordStatsChecker.class);
jobConf.setJobName("sortvalidate-recordstats-checker");
int noSortReduceTasks =
outputfs.listStatus(sortOutput, sortPathsFilter).length;
jobConf.setInt(SORT_REDUCES, noSortReduceTasks);
int noSortInputpaths = inputfs.listStatus(sortInput).length;
jobConf.setInputFormat(NonSplitableSequenceFileInputFormat.class);
jobConf.setOutputFormat(SequenceFileOutputFormat.class);
jobConf.setOutputKeyClass(IntWritable.class);
jobConf.setOutputValueClass(RecordStatsChecker.RecordStatsWritable.class);
jobConf.setMapperClass(Map.class);
jobConf.setCombinerClass(Reduce.class);
jobConf.setReducerClass(Reduce.class);
jobConf.setNumMapTasks(noSortReduceTasks);
jobConf.setNumReduceTasks(1);
FileInputFormat.setInputPaths(jobConf, sortInput);
FileInputFormat.addInputPath(jobConf, sortOutput);
Path outputPath = new Path("/tmp/sortvalidate/recordstatschecker");
if (defaultfs.exists(outputPath)) {
defaultfs.delete(outputPath, true);
}
FileOutputFormat.setOutputPath(jobConf, outputPath);
// Uncomment to run locally in a single process
//job_conf.set(JTConfig.JT, "local");
Path[] inputPaths = FileInputFormat.getInputPaths(jobConf);
System.out.println("\nSortValidator.RecordStatsChecker: Validate sort " +
"from " + inputPaths[0] + " (" +
noSortInputpaths + " files), " +
inputPaths[1] + " (" +
noSortReduceTasks +
" files) into " +
FileOutputFormat.getOutputPath(jobConf) +
" with 1 reducer.");
Date startTime = new Date();
System.out.println("Job started: " + startTime);
JobClient.runJob(jobConf);
Date end_time = new Date();
System.out.println("Job ended: " + end_time);
System.out.println("The job took " +
(end_time.getTime() - startTime.getTime()) /1000 + " seconds.");
// Check to ensure that the statistics of the
// framework's sort-input and sort-output match
SequenceFile.Reader stats = new SequenceFile.Reader(defaultfs,
new Path(outputPath, "part-00000"), defaults);
IntWritable k1 = new IntWritable();
IntWritable k2 = new IntWritable();
RecordStatsWritable v1 = new RecordStatsWritable();
RecordStatsWritable v2 = new RecordStatsWritable();
if (!stats.next(k1, v1)) {
throw new IOException("Failed to read record #1 from reduce's output");
}
if (!stats.next(k2, v2)) {
throw new IOException("Failed to read record #2 from reduce's output");
}
if ((v1.getBytes() != v2.getBytes()) || (v1.getRecords() != v2.getRecords()) ||
v1.getChecksum() != v2.getChecksum()) {
throw new IOException("(" +
v1.getBytes() + ", " + v1.getRecords() + ", " + v1.getChecksum() + ") v/s (" +
v2.getBytes() + ", " + v2.getRecords() + ", " + v2.getChecksum() + ")");
}
}
}
/**
* A simple map-reduce task to check if the input and the output
* of the framework's sort is consistent by ensuring each record
* is present in both the input and the output.
*
*/
public static class RecordChecker {
public static class Map extends MapReduceBase
implements Mapper<BytesWritable, BytesWritable,
BytesWritable, IntWritable> {
private IntWritable value = null;
public void configure(JobConf job) {
// value == one for sort-input; value == two for sort-output
value = deduceInputFile(job);
}
public void map(BytesWritable key,
BytesWritable value,
OutputCollector<BytesWritable, IntWritable> output,
Reporter reporter) throws IOException {
// newKey = (key, value)
BytesWritable keyValue = new BytesWritable(pair(key, value));
// output (newKey, value)
output.collect(keyValue, this.value);
}
}
public static class Reduce extends MapReduceBase
implements Reducer<BytesWritable, IntWritable,
BytesWritable, IntWritable> {
public void reduce(BytesWritable key, Iterator<IntWritable> values,
OutputCollector<BytesWritable, IntWritable> output,
Reporter reporter) throws IOException {
int ones = 0;
int twos = 0;
while (values.hasNext()) {
IntWritable count = values.next();
if (count.equals(sortInput)) {
++ones;
} else if (count.equals(sortOutput)) {
++twos;
} else {
throw new IOException("Invalid 'value' of " + count.get() +
" for (key,value): " + key.toString());
}
}
// Check to ensure there are equal no. of ones and twos
if (ones != twos) {
throw new IOException("Illegal ('one', 'two'): (" + ones + ", " + twos +
") for (key, value): " + key.toString());
}
}
}
static void checkRecords(Configuration defaults, int noMaps, int noReduces,
Path sortInput, Path sortOutput) throws IOException {
JobConf jobConf = new JobConf(defaults, RecordChecker.class);
jobConf.setJobName("sortvalidate-record-checker");
jobConf.setInputFormat(SequenceFileInputFormat.class);
jobConf.setOutputFormat(SequenceFileOutputFormat.class);
jobConf.setOutputKeyClass(BytesWritable.class);
jobConf.setOutputValueClass(IntWritable.class);
jobConf.setMapperClass(Map.class);
jobConf.setReducerClass(Reduce.class);
JobClient client = new JobClient(jobConf);
ClusterStatus cluster = client.getClusterStatus();
if (noMaps == -1) {
noMaps = cluster.getTaskTrackers() *
jobConf.getInt(MAPS_PER_HOST, 10);
}
if (noReduces == -1) {
noReduces = (int) (cluster.getMaxReduceTasks() * 0.9);
String sortReduces = jobConf.get(REDUCES_PER_HOST);
if (sortReduces != null) {
noReduces = cluster.getTaskTrackers() *
Integer.parseInt(sortReduces);
}
}
jobConf.setNumMapTasks(noMaps);
jobConf.setNumReduceTasks(noReduces);
FileInputFormat.setInputPaths(jobConf, sortInput);
FileInputFormat.addInputPath(jobConf, sortOutput);
Path outputPath = new Path("/tmp/sortvalidate/recordchecker");
FileSystem fs = FileSystem.get(defaults);
if (fs.exists(outputPath)) {
fs.delete(outputPath, true);
}
FileOutputFormat.setOutputPath(jobConf, outputPath);
// Uncomment to run locally in a single process
//job_conf.set(JTConfig.JT, "local");
Path[] inputPaths = FileInputFormat.getInputPaths(jobConf);
System.out.println("\nSortValidator.RecordChecker: Running on " +
cluster.getTaskTrackers() +
" nodes to validate sort from " +
inputPaths[0] + ", " +
inputPaths[1] + " into " +
FileOutputFormat.getOutputPath(jobConf) +
" with " + noReduces + " reduces.");
Date startTime = new Date();
System.out.println("Job started: " + startTime);
JobClient.runJob(jobConf);
Date end_time = new Date();
System.out.println("Job ended: " + end_time);
System.out.println("The job took " +
(end_time.getTime() - startTime.getTime()) /1000 + " seconds.");
}
}
/**
* The main driver for sort-validator program.
* Invoke this method to submit the map/reduce job.
* @throws IOException When there is communication problems with the
* job tracker.
*/
public int run(String[] args) throws Exception {
Configuration defaults = getConf();
int noMaps = -1, noReduces = -1;
Path sortInput = null, sortOutput = null;
boolean deepTest = false;
for(int i=0; i < args.length; ++i) {
try {
if ("-m".equals(args[i])) {
noMaps = Integer.parseInt(args[++i]);
} else if ("-r".equals(args[i])) {
noReduces = Integer.parseInt(args[++i]);
} else if ("-sortInput".equals(args[i])){
sortInput = new Path(args[++i]);
} else if ("-sortOutput".equals(args[i])){
sortOutput = new Path(args[++i]);
} else if ("-deep".equals(args[i])) {
deepTest = true;
} else {
printUsage();
return -1;
}
} catch (NumberFormatException except) {
System.err.println("ERROR: Integer expected instead of " + args[i]);
printUsage();
return -1;
} catch (ArrayIndexOutOfBoundsException except) {
System.err.println("ERROR: Required parameter missing from " +
args[i-1]);
printUsage();
return -1;
}
}
// Sanity check
if (sortInput == null || sortOutput == null) {
printUsage();
return -2;
}
// Check if the records are consistent and sorted correctly
RecordStatsChecker.checkRecords(defaults, sortInput, sortOutput);
// Check if the same records are present in sort's inputs & outputs
if (deepTest) {
RecordChecker.checkRecords(defaults, noMaps, noReduces, sortInput,
sortOutput);
}
System.out.println("\nSUCCESS! Validated the MapReduce framework's 'sort'" +
" successfully.");
return 0;
}
public static void main(String[] args) throws Exception {
int res = ToolRunner.run(new Configuration(), new SortValidator(), args);
System.exit(res);
}
}
|
// ______________________________________________________
// Generated by sql2java - http://sql2java.sourceforge.net/
// jdbc driver used at code generation time: com.mysql.jdbc.Driver
//
// Please help us improve this tool by reporting:
// - problems and suggestions to
// http://sourceforge.net/tracker/?group_id=54687
// - feedbacks and ideas on
// http://sourceforge.net/forum/forum.php?forum_id=182208
// ______________________________________________________
package legaltime.model;
import java.io.Serializable;
import java.util.Map;
import java.util.HashMap;
import legaltime.model.GeneratedBean;
import org.apache.commons.lang.builder.CompareToBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
/**
* SysCodeBean is a mapping of sys_code Table.
* @author sql2java
*/
public class SysCodeBean
implements Serializable, GeneratedBean
{
private static final long serialVersionUID = 6068219802986224705L;
private java.util.Date lastUpdate;
private boolean lastUpdateIsModified = false;
private boolean lastUpdateIsInitialized = false;
private String systemOrUser;
private boolean systemOrUserIsModified = false;
private boolean systemOrUserIsInitialized = false;
private String description;
private boolean descriptionIsModified = false;
private boolean descriptionIsInitialized = false;
private String codeId;
private boolean codeIdIsModified = false;
private boolean codeIdIsInitialized = false;
private String codeType;
private boolean codeTypeIsModified = false;
private boolean codeTypeIsInitialized = false;
private Integer sysCodeId;
private boolean sysCodeIdIsModified = false;
private boolean sysCodeIdIsInitialized = false;
private boolean _isNew = true;
/**
* Prefered methods to create a SysCodeBean is via the createSysCodeBean method in SysCodeManager or
* via the factory class SysCodeFactory create method
*/
protected SysCodeBean()
{
}
/**
* Getter method for lastUpdate.
* <br>
* Meta Data Information (in progress):
* <ul>
* <li>full name: sys_code.last_update</li>
* <li>column size: 19</li>
* <li>jdbc type returned by the driver: Types.TIMESTAMP</li>
* </ul>
*
* @return the value of lastUpdate
*/
public java.util.Date getLastUpdate()
{
return lastUpdate;
}
/**
* Setter method for lastUpdate.
* <br>
* The new value is set only if compareTo() says it is different,
* or if one of either the new value or the current value is null.
* In case the new value is different, it is set and the field is marked as 'modified'.
*
* @param newVal the new value to be assigned to lastUpdate
*/
public void setLastUpdate(java.util.Date newVal)
{
if ((newVal != null && lastUpdate != null && (newVal.compareTo(lastUpdate) == 0)) ||
(newVal == null && lastUpdate == null && lastUpdateIsInitialized)) {
return;
}
lastUpdate = newVal;
lastUpdateIsModified = true;
lastUpdateIsInitialized = true;
}
/**
* Setter method for lastUpdate.
* <br>
* Convenient for those who do not want to deal with Objects for primary types.
*
* @param newVal the new value to be assigned to lastUpdate
*/
public void setLastUpdate(long newVal)
{
setLastUpdate(new java.util.Date(newVal));
}
/**
* Determines if the lastUpdate has been modified.
*
* @return true if the field has been modified, false if the field has not been modified
*/
public boolean isLastUpdateModified()
{
return lastUpdateIsModified;
}
/**
* Determines if the lastUpdate has been initialized.
* <br>
* It is useful to determine if a field is null on purpose or just because it has not been initialized.
*
* @return true if the field has been initialized, false otherwise
*/
public boolean isLastUpdateInitialized()
{
return lastUpdateIsInitialized;
}
/**
* Getter method for systemOrUser.
* <br>
* Meta Data Information (in progress):
* <ul>
* <li>full name: sys_code.system_or_user</li>
* <li>column size: 20</li>
* <li>jdbc type returned by the driver: Types.VARCHAR</li>
* </ul>
*
* @return the value of systemOrUser
*/
public String getSystemOrUser()
{
return systemOrUser;
}
/**
* Setter method for systemOrUser.
* <br>
* The new value is set only if compareTo() says it is different,
* or if one of either the new value or the current value is null.
* In case the new value is different, it is set and the field is marked as 'modified'.
*
* @param newVal the new value to be assigned to systemOrUser
*/
public void setSystemOrUser(String newVal)
{
if ((newVal != null && systemOrUser != null && (newVal.compareTo(systemOrUser) == 0)) ||
(newVal == null && systemOrUser == null && systemOrUserIsInitialized)) {
return;
}
systemOrUser = newVal;
systemOrUserIsModified = true;
systemOrUserIsInitialized = true;
}
/**
* Determines if the systemOrUser has been modified.
*
* @return true if the field has been modified, false if the field has not been modified
*/
public boolean isSystemOrUserModified()
{
return systemOrUserIsModified;
}
/**
* Determines if the systemOrUser has been initialized.
* <br>
* It is useful to determine if a field is null on purpose or just because it has not been initialized.
*
* @return true if the field has been initialized, false otherwise
*/
public boolean isSystemOrUserInitialized()
{
return systemOrUserIsInitialized;
}
/**
* Getter method for description.
* <br>
* Meta Data Information (in progress):
* <ul>
* <li>full name: sys_code.description</li>
* <li>column size: 255</li>
* <li>jdbc type returned by the driver: Types.VARCHAR</li>
* </ul>
*
* @return the value of description
*/
public String getDescription()
{
return description;
}
/**
* Setter method for description.
* <br>
* The new value is set only if compareTo() says it is different,
* or if one of either the new value or the current value is null.
* In case the new value is different, it is set and the field is marked as 'modified'.
*
* @param newVal the new value to be assigned to description
*/
public void setDescription(String newVal)
{
if ((newVal != null && description != null && (newVal.compareTo(description) == 0)) ||
(newVal == null && description == null && descriptionIsInitialized)) {
return;
}
description = newVal;
descriptionIsModified = true;
descriptionIsInitialized = true;
}
/**
* Determines if the description has been modified.
*
* @return true if the field has been modified, false if the field has not been modified
*/
public boolean isDescriptionModified()
{
return descriptionIsModified;
}
/**
* Determines if the description has been initialized.
* <br>
* It is useful to determine if a field is null on purpose or just because it has not been initialized.
*
* @return true if the field has been initialized, false otherwise
*/
public boolean isDescriptionInitialized()
{
return descriptionIsInitialized;
}
/**
* Getter method for codeId.
* <br>
* Meta Data Information (in progress):
* <ul>
* <li>full name: sys_code.code_id</li>
* <li>column size: 5</li>
* <li>jdbc type returned by the driver: Types.VARCHAR</li>
* </ul>
*
* @return the value of codeId
*/
public String getCodeId()
{
return codeId;
}
/**
* Setter method for codeId.
* <br>
* The new value is set only if compareTo() says it is different,
* or if one of either the new value or the current value is null.
* In case the new value is different, it is set and the field is marked as 'modified'.
*
* @param newVal the new value to be assigned to codeId
*/
public void setCodeId(String newVal)
{
if ((newVal != null && codeId != null && (newVal.compareTo(codeId) == 0)) ||
(newVal == null && codeId == null && codeIdIsInitialized)) {
return;
}
codeId = newVal;
codeIdIsModified = true;
codeIdIsInitialized = true;
}
/**
* Determines if the codeId has been modified.
*
* @return true if the field has been modified, false if the field has not been modified
*/
public boolean isCodeIdModified()
{
return codeIdIsModified;
}
/**
* Determines if the codeId has been initialized.
* <br>
* It is useful to determine if a field is null on purpose or just because it has not been initialized.
*
* @return true if the field has been initialized, false otherwise
*/
public boolean isCodeIdInitialized()
{
return codeIdIsInitialized;
}
/**
* Getter method for codeType.
* <br>
* Meta Data Information (in progress):
* <ul>
* <li>full name: sys_code.code_type</li>
* <li>column size: 5</li>
* <li>jdbc type returned by the driver: Types.VARCHAR</li>
* </ul>
*
* @return the value of codeType
*/
public String getCodeType()
{
return codeType;
}
/**
* Setter method for codeType.
* <br>
* The new value is set only if compareTo() says it is different,
* or if one of either the new value or the current value is null.
* In case the new value is different, it is set and the field is marked as 'modified'.
*
* @param newVal the new value to be assigned to codeType
*/
public void setCodeType(String newVal)
{
if ((newVal != null && codeType != null && (newVal.compareTo(codeType) == 0)) ||
(newVal == null && codeType == null && codeTypeIsInitialized)) {
return;
}
codeType = newVal;
codeTypeIsModified = true;
codeTypeIsInitialized = true;
}
/**
* Determines if the codeType has been modified.
*
* @return true if the field has been modified, false if the field has not been modified
*/
public boolean isCodeTypeModified()
{
return codeTypeIsModified;
}
/**
* Determines if the codeType has been initialized.
* <br>
* It is useful to determine if a field is null on purpose or just because it has not been initialized.
*
* @return true if the field has been initialized, false otherwise
*/
public boolean isCodeTypeInitialized()
{
return codeTypeIsInitialized;
}
/**
* Getter method for sysCodeId.
* <br>
* PRIMARY KEY.<br>
* Meta Data Information (in progress):
* <ul>
* <li>full name: sys_code.sys_code_id</li>
* <li>column size: 10</li>
* <li>jdbc type returned by the driver: Types.INTEGER</li>
* </ul>
*
* @return the value of sysCodeId
*/
public Integer getSysCodeId()
{
return sysCodeId;
}
/**
* Setter method for sysCodeId.
* <br>
* The new value is set only if compareTo() says it is different,
* or if one of either the new value or the current value is null.
* In case the new value is different, it is set and the field is marked as 'modified'.
*
* @param newVal the new value to be assigned to sysCodeId
*/
public void setSysCodeId(Integer newVal)
{
if ((newVal != null && sysCodeId != null && (newVal.compareTo(sysCodeId) == 0)) ||
(newVal == null && sysCodeId == null && sysCodeIdIsInitialized)) {
return;
}
sysCodeId = newVal;
sysCodeIdIsModified = true;
sysCodeIdIsInitialized = true;
}
/**
* Setter method for sysCodeId.
* <br>
* Convenient for those who do not want to deal with Objects for primary types.
*
* @param newVal the new value to be assigned to sysCodeId
*/
public void setSysCodeId(int newVal)
{
setSysCodeId(new Integer(newVal));
}
/**
* Determines if the sysCodeId has been modified.
*
* @return true if the field has been modified, false if the field has not been modified
*/
public boolean isSysCodeIdModified()
{
return sysCodeIdIsModified;
}
/**
* Determines if the sysCodeId has been initialized.
* <br>
* It is useful to determine if a field is null on purpose or just because it has not been initialized.
*
* @return true if the field has been initialized, false otherwise
*/
public boolean isSysCodeIdInitialized()
{
return sysCodeIdIsInitialized;
}
/**
* Determines if the current object is new.
*
* @return true if the current object is new, false if the object is not new
*/
public boolean isNew()
{
return _isNew;
}
/**
* Specifies to the object if it has been set as new.
*
* @param isNew the boolean value to be assigned to the isNew field
*/
public void isNew(boolean isNew)
{
this._isNew = isNew;
}
/**
* Determines if the object has been modified since the last time this method was called.
* <br>
* We can also determine if this object has ever been modified since its creation.
*
* @return true if the object has been modified, false if the object has not been modified
*/
public boolean isModified()
{
return lastUpdateIsModified || systemOrUserIsModified || descriptionIsModified || codeIdIsModified || codeTypeIsModified || sysCodeIdIsModified ;
}
/**
* Resets the object modification status to 'not modified'.
*/
public void resetIsModified()
{
lastUpdateIsModified = false;
systemOrUserIsModified = false;
descriptionIsModified = false;
codeIdIsModified = false;
codeTypeIsModified = false;
sysCodeIdIsModified = false;
}
/**
* Copies the passed bean into the current bean.
*
* @param bean the bean to copy into the current bean
*/
public void copy(SysCodeBean bean)
{
setLastUpdate(bean.getLastUpdate());
setSystemOrUser(bean.getSystemOrUser());
setDescription(bean.getDescription());
setCodeId(bean.getCodeId());
setCodeType(bean.getCodeType());
setSysCodeId(bean.getSysCodeId());
}
/**
* return a dictionnary of the object
*/
public Map getDictionnary()
{
Map dictionnary = new HashMap();
dictionnary.put("last_update", getLastUpdate() == null ? "" : getLastUpdate().toString());
dictionnary.put("system_or_user", getSystemOrUser() == null ? "" : getSystemOrUser().toString());
dictionnary.put("description", getDescription() == null ? "" : getDescription().toString());
dictionnary.put("code_id", getCodeId() == null ? "" : getCodeId().toString());
dictionnary.put("code_type", getCodeType() == null ? "" : getCodeType().toString());
dictionnary.put("sys_code_id", getSysCodeId() == null ? "" : getSysCodeId().toString());
return dictionnary;
}
/**
* return a dictionnary of the pk columns
*/
public Map getPkDictionnary()
{
Map dictionnary = new HashMap();
dictionnary.put("sys_code_id", getSysCodeId() == null ? "" : getSysCodeId().toString());
return dictionnary;
}
/**
* return a the value string representation of the given field
*/
public String getValue(String column)
{
if (null == column || "".equals(column)) {
return "";
} else if ("last_update".equalsIgnoreCase(column) || "lastUpdate".equalsIgnoreCase(column)) {
return getLastUpdate() == null ? "" : getLastUpdate().toString();
} else if ("system_or_user".equalsIgnoreCase(column) || "systemOrUser".equalsIgnoreCase(column)) {
return getSystemOrUser() == null ? "" : getSystemOrUser().toString();
} else if ("description".equalsIgnoreCase(column) || "description".equalsIgnoreCase(column)) {
return getDescription() == null ? "" : getDescription().toString();
} else if ("code_id".equalsIgnoreCase(column) || "codeId".equalsIgnoreCase(column)) {
return getCodeId() == null ? "" : getCodeId().toString();
} else if ("code_type".equalsIgnoreCase(column) || "codeType".equalsIgnoreCase(column)) {
return getCodeType() == null ? "" : getCodeType().toString();
} else if ("sys_code_id".equalsIgnoreCase(column) || "sysCodeId".equalsIgnoreCase(column)) {
return getSysCodeId() == null ? "" : getSysCodeId().toString();
}
return "";
}
/**
* @see java.lang.Object#equals(Object)
*/
public boolean equals(Object object)
{
if (!(object instanceof SysCodeBean)) {
return false;
}
SysCodeBean obj = (SysCodeBean) object;
return new EqualsBuilder()
.append(getLastUpdate(), obj.getLastUpdate())
.append(getSystemOrUser(), obj.getSystemOrUser())
.append(getDescription(), obj.getDescription())
.append(getCodeId(), obj.getCodeId())
.append(getCodeType(), obj.getCodeType())
.append(getSysCodeId(), obj.getSysCodeId())
.isEquals();
}
/**
* @see java.lang.Object#hashCode()
*/
public int hashCode()
{
return new HashCodeBuilder(-82280557, -700257973)
.append(getLastUpdate())
.append(getSystemOrUser())
.append(getDescription())
.append(getCodeId())
.append(getCodeType())
.append(getSysCodeId())
.toHashCode();
}
/**
* @see java.lang.Object#toString()
*/
public String toString()
{
return toString(ToStringStyle.MULTI_LINE_STYLE);
}
/**
* you can use the following styles:
* <li>ToStringStyle.DEFAULT_STYLE</li>
* <li>ToStringStyle.MULTI_LINE_STYLE</li>
* <li>ToStringStyle.NO_FIELD_NAMES_STYLE</li>
* <li>ToStringStyle.SHORT_PREFIX_STYLE</li>
* <li>ToStringStyle.SIMPLE_STYLE</li>
*/
public String toString(ToStringStyle style) {
return new ToStringBuilder(this, style)
.append("last_update", getLastUpdate())
.append("system_or_user", getSystemOrUser())
.append("description", getDescription())
.append("code_id", getCodeId())
.append("code_type", getCodeType())
.append("sys_code_id", getSysCodeId())
.toString();
}
public int compareTo(Object object)
{
SysCodeBean obj = (SysCodeBean) object;
return new CompareToBuilder()
.append(getLastUpdate(), obj.getLastUpdate())
.append(getSystemOrUser(), obj.getSystemOrUser())
.append(getDescription(), obj.getDescription())
.append(getCodeId(), obj.getCodeId())
.append(getCodeType(), obj.getCodeType())
.append(getSysCodeId(), obj.getSysCodeId())
.toComparison();
}
}
|
package listaExercicios7;
public class Empregado extends Pessoa
{
private int codigoSetor;
private double salarioBase;
private double imposto;
// Getters and Setters:
public int getCodigoSetor()
{
return codigoSetor;
}
public void setCodigoSetor(int codigoSetor)
{
this.codigoSetor = codigoSetor;
}
public double getSalarioBase()
{
return salarioBase;
}
public void setSalarioBase(double salarioBase)
{
this.salarioBase = salarioBase;
}
public double getImpost()
{
return imposto;
}
public void setImpost(double imposto)
{
this.imposto = imposto;
}
//Construtor:
public Empregado(String nome, int codigoSetor)
{
super(nome);
this.codigoSetor = codigoSetor;
}
//Métodos:
public double calcularSalario()
{
double salarioLiquido;
salarioLiquido = salarioBase - (salarioBase*imposto/100);
return salarioLiquido;
}
}
|
package testcase.emb;
import es.utils.mapper.Mapper;
import es.utils.mapper.exception.MappingException;
import es.utils.mapper.factory.builder.DefaultOutput;
import es.utils.mapper.factory.builder.EMBuilder;
import es.utils.mapper.factory.builder.To;
import es.utils.mapper.impl.object.ClassMapper;
import from.ClassMapperFromTest;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import to.ClassMapperToTest;
import static org.assertj.core.api.Assertions.assertThat;
public class EMB_DefaultOutputStep {
private Mapper mapper;
private ClassMapper<ClassMapperFromTest,ClassMapperToTest> mapping;
private DefaultOutput<ClassMapperFromTest,String,String,ClassMapperToTest> prev;
@BeforeEach
public void beforeEach() throws MappingException {
mapper = new Mapper();
mapping = mapper.addForClass(ClassMapperFromTest.class,ClassMapperToTest.class);
prev = EMBuilder.using(mapper,mapping).from("name",ClassMapperFromTest::getNameFrom);
}
@Test
public void shouldCreate_BuilderStep_DefaultInput_DefaultInput_Object() {
To<ClassMapperFromTest,String,String,ClassMapperToTest> step = prev.defaultOutput("No name");
assertThat(step).isNotNull()
.isInstanceOf(To.class)
.isExactlyInstanceOf(EMBuilder.class)
.hasAllNullFieldsOrPropertiesExcept("mapper","mapping","getter","defaultOutput");
}
@Test
public void shouldCreate_BuilderStep_DefaultInput_DefaultInput_Class() {
mapper.config().addDefaultValueSupplier(String.class, ()->"{no value}");
To<ClassMapperFromTest,String,String,ClassMapperToTest> step = prev.defaultOutputFor(String.class);
assertThat(step).isNotNull()
.isInstanceOf(To.class)
.isExactlyInstanceOf(EMBuilder.class)
.hasAllNullFieldsOrPropertiesExcept("mapper","mapping","getter","defaultOutput");
}
}
|
package com.graphql.test.exception;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import graphql.ErrorType;
import graphql.GraphQLError;
import graphql.language.SourceLocation;
public class PostNotFoundException extends RuntimeException implements GraphQLError {
private Integer postId;
public PostNotFoundException(Integer postId) {
this.postId = postId;
}
@Override
public String getMessage() {
return "Post with ID " + postId + " could not be found";
}
@Override
public List<SourceLocation> getLocations() {
return null;
}
@Override
public Map<String, Object> getExtensions() {
return Collections.singletonMap("postId", postId);
}
@Override
public ErrorType getErrorType() {
return ErrorType.DataFetchingException;
}
}
|
package to;
public class ImplTo {
public static final int staticFinal = 97;
public static int _static = 97;
public final int _final = 97;
public To complexValue;
}
|
package gui;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import modelo.Orden;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class VerOrdenes extends JFrame {
private JPanel contentPane;
private Principal p;
private JList<Orden> list;
private DefaultListModel<Orden> listModel;
/**
* Cosntructor de VerOrdenes
* @param p Ventana principal
*/
public VerOrdenes(Principal p) {
super("Lista Ordenes");
this.p=p;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
list = new JList<Orden>();
list.setBounds(29, 61, 383, 152);
contentPane.add(list);
listModel = new DefaultListModel<>();
for (int i=0; i<this.p.getOrdenes().size(); i++)
listModel.addElement(this.p.getOrdenes().get(i));
list.setModel(listModel);
JLabel lblOrdenes = new JLabel("Ordenes:");
lblOrdenes.setBounds(29, 24, 72, 14);
contentPane.add(lblOrdenes);
JButton btnBorrarOrden = new JButton("Borrar Orden");
btnBorrarOrden.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(list.getSelectedIndex()==-1){
JOptionPane.showMessageDialog(null, "Error. Elige una orden a borrar.", "Error borrando", JOptionPane.ERROR_MESSAGE);
}
else{
p.getOrdenes().remove(list.getSelectedValue()); //elimino la orden de la lista de órdenes
listModel.remove(list.getSelectedIndex());
list.setModel(listModel);
}
}
});
btnBorrarOrden.setBounds(300, 227, 112, 23);
contentPane.add(btnBorrarOrden);
JButton btnRecibida = new JButton("Recibida");
btnRecibida.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(list.getSelectedIndex()==-1){
JOptionPane.showMessageDialog(null, "Error. Elige una orden a marcar como entregada.", "Error entrega", JOptionPane.ERROR_MESSAGE);
}
else{
Orden orden = list.getSelectedValue();
orden.setEntregado(true);
list.updateUI();
}
}
});
btnRecibida.setBounds(153, 227, 112, 23);
contentPane.add(btnRecibida);
JLabel lblNombre = new JLabel("Nombre");
lblNombre.setBounds(39, 49, 46, 14);
contentPane.add(lblNombre);
JLabel lblDireccin = new JLabel("Direcci\u00F3n");
lblDireccin.setBounds(126, 49, 46, 14);
contentPane.add(lblDireccin);
JLabel lblTelfono = new JLabel("Tel\u00E9fono");
lblTelfono.setBounds(219, 49, 46, 14);
contentPane.add(lblTelfono);
JLabel lblPrecio = new JLabel("Precio");
lblPrecio.setBounds(297, 49, 46, 14);
contentPane.add(lblPrecio);
JLabel lblEntregado = new JLabel("Entregado");
lblEntregado.setBounds(340, 49, 72, 14);
contentPane.add(lblEntregado);
JButton btnVolver = new JButton("Volver");
btnVolver.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
VerOrdenes.this.setVisible(false);
VerOrdenes.this.p.setVisible(true);
}
});
btnVolver.setBounds(39, 227, 89, 23);
contentPane.add(btnVolver);
}
}
|
package de.jmda9.core.util.jpa;
import javax.lang.model.element.VariableElement;
public class EntityRelationInfoOneToManyUnidirectional extends
EntityRelationInfoUnidirectional
{
public EntityRelationInfoOneToManyUnidirectional(
VariableElement declaredField)
{
super(EntityRelation.OneToManyUnidirectional, declaredField);
}
}
|
package com.tencent.mm.xlog.app;
public final class a {
public static String uZO = "wechatxlog";
}
|
package com.tencent.mm.ui.conversation.a;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.bg.d;
import com.tencent.mm.model.au;
import com.tencent.mm.model.bc;
import com.tencent.mm.model.c;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.ui.base.s;
class k$2 implements OnClickListener {
final /* synthetic */ int bpX;
final /* synthetic */ int tiP;
final /* synthetic */ k usq;
k$2(k kVar, int i, int i2) {
this.usq = kVar;
this.bpX = i;
this.tiP = i2;
}
public final void onClick(View view) {
bc.Ig().ba(this.bpX, this.tiP);
Context context = (Context) this.usq.qJS.get();
if (context != null) {
au.HU();
if (c.isSDCardAvailable()) {
Intent intent = new Intent();
intent.putExtra("intent_set_avatar", true);
intent.putExtra("KEnterFromBanner", true);
d.b(context, "setting", ".ui.setting.SettingsPersonalInfoUI", intent);
h.mEJ.h(11002, new Object[]{Integer.valueOf(4), Integer.valueOf(1)});
return;
}
s.gH(context);
}
}
}
|
package com.thread.pool.frameWork;
import com.thread.pool.base.CallableTemplate;
import com.thread.pool.base.ICurrentThreadPool;
import com.thread.pool.threadPool.ConcurrentThreadPool;
import java.util.List;
import java.util.concurrent.ExecutionException;
/**
* @desc CallableTaskFrameWork是ICallableTaskFrameWork 的实现类,
* 在submitsAll实现方法中,通过调用线程池对象IConcurrentThreadPool接口的invokeAll方法来发起多线程的调用,
* 这里注意一个,在submitAll实现方法中,
* 我手动的调用了初始化线程池的方法concurrentThreadPool.initConcurrentThreadPool(),
* 在真实的项目上,应该在应用启动的时候就调用该方法来初始化线程池
*/
/**
* @author zhangbingquan
* @desc CallableTaskFrameWork是ICallableTaskFrameWork 的实现类
* @time 2019-09-12 22:19
*/
public class CallableTaskFrameWork implements ICallableFrameWork {
private ICurrentThreadPool currentThreadPool = new ConcurrentThreadPool();
@Override
public <V> List<V> submitAll(List<? extends CallableTemplate<V>> tasks) throws InterruptedException, ExecutionException {
currentThreadPool.initConcurrentThreadPool();
return currentThreadPool.invokeAll(tasks);
}
public void closeAll() {
currentThreadPool.closeConcurrentThreadPool();
}
}
|
package ru.rikabc.servlets;
import org.springframework.context.ApplicationContext;
import ru.rikabc.repositories.ProductRepository;
import javax.servlet.ServletConfig;
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 java.io.IOException;
/**
* @Author Roman Khayrullin on 17.04.2018
* @Version 1.0
*/
@WebServlet("/delete")
public class DeleteProductServlet extends HttpServlet {
private ProductRepository repository;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
ApplicationContext applicationContext = (ApplicationContext) config.getServletContext()
.getAttribute("springContext");
repository = applicationContext.getBean(ProductRepository.class);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String idString = req.getParameter("id");
int id = Integer.parseInt(idString);
repository.delete(id);
resp.sendRedirect(req.getContextPath() + "/product");
}
}
|
/**
*
*/
/**
* @author z003uuvm
*
*/
package resto.com.app.services;
|
package text.an.com.sunning_ks.bean;
import java.util.ArrayList;
/**
* Created by lenovo on 2016/11/7.
*/
public class MyBean {
public MyResult result;
public class MyResult {
public ArrayList<MyData> data;
}
public class MyData{
public String content;
public String updatetime;
}
}
|
/*
* 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 busqueda;
import busquedaAutor.ListaProductos;
/**
*
* @author crist_000
*/
public class BusquedaAutor {
public static ListaProductos buscar(java.lang.String autor) {
busquedaAutor.BusquedaAutor_Service service = new busquedaAutor.BusquedaAutor_Service();
busquedaAutor.BusquedaAutor port = service.getBusquedaAutorPort();
return port.buscar(autor);
}
}
|
package com.dlq.json;
import com.dlq.pojo.Person;
import com.google.gson.reflect.TypeToken;
import java.util.Map;
/**
*@program: Java_Web
*@description:
*@author: Hasee
*@create: 2021-01-19 19:34
*/
public class PersonMapType extends TypeToken<Map<Integer, Person>> {
}
|
package com.cnk.travelogix.custom.mappingtable.maintain;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
*
* The settings to enable reference-based pagination of search results in response. Several operation requests are necessary to retrieve the complete results.
*
*
* <p>Java class for SearchFilterWindow complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="SearchFilterWindow">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="windowSize" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="fromUniqueId" type="{http://schema.ws.highdeal.com/}String256" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SearchFilterWindow", propOrder = {
"windowSize",
"fromUniqueId"
})
public class SearchFilterWindow {
protected Integer windowSize;
protected String fromUniqueId;
/**
* Gets the value of the windowSize property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getWindowSize() {
return windowSize;
}
/**
* Sets the value of the windowSize property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setWindowSize(Integer value) {
this.windowSize = value;
}
/**
* Gets the value of the fromUniqueId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFromUniqueId() {
return fromUniqueId;
}
/**
* Sets the value of the fromUniqueId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFromUniqueId(String value) {
this.fromUniqueId = value;
}
}
|
package com.example.lib2;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
/**
* Created by ljq on 2019/5/10
*/
public class Lib2Activity extends AppCompatActivity {
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lib2);
}
}
|
package com.github.ganity.oauth2.shiro;
import com.github.ganity.oauth2.AuthzCallback;
import com.github.ganity.oauth2.OAuth2AccessToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import java.util.Map;
public class ShiroAuthzCallback implements AuthzCallback {
@Override
public void callback(OAuth2AccessToken accessToken, Map<String, String> principal) {
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(principal.get(PRINCIPAL), principal.get(PRINCIPAL).toCharArray());
token.setRememberMe(false);
try {
if (subject.isAuthenticated()) {
subject.logout();
}
subject.login(token);
Session session = subject.getSession();
session.setAttribute(AUTH_ACCESS_TOKEN, accessToken);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public OAuth2AccessToken logout() {
Subject subject = SecurityUtils.getSubject();
try {
Session session = subject.getSession();
OAuth2AccessToken accessToken = (OAuth2AccessToken)session.getAttribute(AUTH_ACCESS_TOKEN);
if (subject.isAuthenticated()) {
subject.logout();
}
return accessToken;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
|
package mfh.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
public class DBFacility implements ConnectionProvider {
Connection conn=null;
Statement stmt=null;
String sql="";
public Connection connectionDB()
{
try{
Class.forName(driverName);
conn = DriverManager.getConnection(dbConnectionURL+databaseName,dbUserName,dbUserPassword);
return conn;
}
catch(Exception e)
{
System.out.println("Problem in connectionDB: "+e);
}
return conn;
}
public boolean valid(String uname, String upassword)
{
sql= "SELECT userName, userPassword FROM "+dbUserTable+"" +
" WHERE userName='"+uname+"' AND userPassword='"+upassword+"'";
conn= connectionDB();
System.out.println("Connection Successful... ");
boolean isUser,isPassword;
isUser=isPassword=false;
try {
stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery(sql);
ResultSetMetaData rsmtdata=rs.getMetaData();
String values[] = new String[2];
int columnNumber =rsmtdata.getColumnCount();
int count=0;
while(rs.next())
{
for(int i=1;i<=columnNumber;++i)
{
String cValue=values[count]=rs.getString(i);
if(cValue.equals(uname))
{
isUser=true;
}
else if(cValue.equals(upassword))
{
isPassword=true;
}
count++;
}
}
if(isUser&&isPassword)
{
System.out.println("True");
return true;
}
else
{
System.out.println("False");
return false;
}
} catch (SQLException e) {
System.out.println("Problem in query result method..."+e);
}
return false;
}
public void closeConn()
{
try {
if(!conn.isClosed())
{
stmt.close();
conn.close();
System.out.println("Connection Successfully Closed.");
}
else
{
System.out.println("Connection Already Closed.");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package cims.command;
import cims.Caretaker;
public class UndoCommand implements Command {
private Caretaker c;
public UndoCommand(Caretaker c) {
super();
this.c = c;
}
@Override
public void execute() {
// TODO Auto-generated method stub
undo();
}
@Override
public void undo() {
// TODO Auto-generated method stub
if (c.getUndoList().size() > 0) {
c.getRedoList().push(c.getUndoList().pop());
if (c.getRedoList().peek().contains("Added")) {
c.getRedoProducts().push(c.getUndoProducts().pop());
} else {
c.getRedoStatus().push(c.getUndoStatus().pop());
int productID = c.getRedoStatus().peek().getCoffeeProduct().getProductID();
for (int i = c.getUndoStatus().size() - 1; i >= 0; i--) {
if (c.getUndoStatus().get(i).getCoffeeProduct().getProductID() == productID) {
c.getUndoStatus().get(i).restore();
break;
}
}
}
System.out.println("undo completed.");
} else {
System.out.println("undo failed. (Undo list is empty)");
}
}
@Override
public void redo() {
// TODO Auto-generated method stub
}
}
|
package esipe.fr.tpconcurrence.repositories;
import esipe.fr.tpconcurrence.entities.Lock;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.Optional;
public interface LockRepository extends MongoRepository<Lock,String> {
public Optional<Lock> findByLockId(String lockId);
}
|
package com.qunchuang.carmall.graphql.query;
import cn.wzvtcsoft.bosdomain.enums.BosEnum;
import cn.wzvtcsoft.bosdomain.util.EntityEnumUtil;
import com.qunchuang.carmall.graphql.IGraphQlTypeMapper;
import com.qunchuang.carmall.graphql.query.dataprivilege.PrivilegeConstraint;
import com.qunchuang.carmall.graphql.query.dataprivilege.PrivilegeConstraintUtil;
import com.qunchuang.carmall.graphql.query.enums.OrderByDirection;
import com.qunchuang.carmall.graphql.query.enums.QueryFilterCombinator;
import com.qunchuang.carmall.graphql.query.enums.QueryFilterOperator;
import com.qunchuang.carmall.graphql.query.enums.QueryForWhatEnum;
import graphql.language.*;
import graphql.schema.*;
import org.hibernate.query.criteria.internal.path.SingularAttributePath;
import org.springframework.beans.ConfigurablePropertyAccessor;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.context.SecurityContextHolder;
import javax.persistence.EntityGraph;
import javax.persistence.EntityManager;
import javax.persistence.Subgraph;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.*;
import javax.persistence.metamodel.Attribute;
import javax.persistence.metamodel.EntityType;
import javax.persistence.metamodel.PluralAttribute;
import javax.persistence.metamodel.SingularAttribute;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class JpaDataFetcher implements DataFetcher {
protected EntityManager entityManager;
protected EntityType<?> entityType;
protected IGraphQlTypeMapper graphQlTypeMapper;
public JpaDataFetcher(EntityManager entityManager, EntityType<?> entityType, IGraphQlTypeMapper graphQlTypeMapper) {
this.entityManager = entityManager;
this.entityType = entityType;
this.graphQlTypeMapper = graphQlTypeMapper;
}
@Override
public final Object get(DataFetchingEnvironment environment) {
QueryFilter queryFilter = extractQueryFilter(environment, environment.getFields().iterator().next());
//检查权限 构造数据过滤 查询时才需要
if (this.getClass().isAssignableFrom(JpaDataFetcher.class) || this.getClass().isAssignableFrom(CollectionJpaDataFetcher.class)) {
queryFilter = checkPermission(queryFilter);
}
Object result = this.getResult(environment, queryFilter);
return result;
}
/**
* 获取 entity 中的 QueryFilter 的约束
*/
private QueryFilter checkPermission(QueryFilter queryFilter) {
Class<?> clz = this.entityType.getJavaType();
for (Method method : clz.getDeclaredMethods()) {
if (method.isAnnotationPresent(PrivilegeConstraint.class)) {
QueryFilter result = null;
try {
result = (QueryFilter) method.invoke(clz.newInstance());
PrivilegeConstraintUtil.merge(queryFilter, result);
} catch (Exception e) {
//构建约束失败 抛出异常
// TODO: 2019/2/19 后续需要寻找 抛出合适异常 直接修改http response stauts
if (SecurityContextHolder.getContext().getAuthentication() == null || (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof String)){
//未登录 (匿名用户)
throw new BadCredentialsException("");
}else {
throw new AccessDeniedException("");
}
}
}
}
return queryFilter;
}
protected QueryFilter extractQueryFilter(DataFetchingEnvironment environment, Field field) {
return null;
}
public Object getResult(DataFetchingEnvironment environment, QueryFilter filter) {
TypedQuery typedQuery = getQuery(environment, environment.getFields().iterator().next(), filter, QueryForWhatEnum.NORMAL, null);
return typedQuery.getResultList().stream().findAny().orElse(null);
}
/**
* 遍历选中的字段集合,把entityGraph准备好
*/
private void travelFieldSelection(CriteriaBuilder cb, Path root, SelectionSet selectionSet, List<Argument> arguments, List<Order> orders, EntityGraph entityGraph, Subgraph subgraph, QueryForWhatEnum queryForWhat) {
if (selectionSet != null) {
selectionSet.getSelections().forEach(selection -> {
if (selection instanceof Field) {
Field selectedField = (Field) selection;
String selectedFieldName = selectedField.getName();
// "__typename" is part of the graphql introspection spec and has to be ignored by jpa
if (!"__typename".equals(selectedFieldName) && !"parent".equals(selectedFieldName)) {
Path fieldPath = root.get(selectedField.getName());
// Process the orderBy clause
// TODO 排序如果出现在第二层会有一些问题,似乎没法影响到,似乎在指明one2many下分录的排序规则时,会碰到问题,可能跟entry以set形式出现有关系。many2one应该不会。
if (QueryForWhatEnum.JUSTFORCOUNTBYDISTINCTID != queryForWhat) {//如果是只用来查询符合条件的总数,则不用添加roderby
Optional<Argument> orderByArgument = selectedField.getArguments().stream().filter(it -> OrderByDirection.ORDER_BY.equals(it.getName())).findFirst();
if (orderByArgument.isPresent()) {
if (OrderByDirection.DESC.name().equals(((EnumValue) orderByArgument.get().getValue()).getName())) {
orders.add(cb.desc(fieldPath));
} else {
orders.add(cb.asc(fieldPath));
}
}
}
//如果这个root是embeddable的话,则直接返回了。
if (root instanceof SingularAttributePath && ((SingularAttributePath) root).getAttribute().getPersistentAttributeType() == Attribute.PersistentAttributeType.EMBEDDED) {
return;
}
//TODO 可以考虑去掉的过滤功能,只保留(id:'xxxx')和(number:'yyyy')这两种,因为我们现在是用QFilter了,除非我们重新构建一个比QFilter更好的查询方法。
arguments.addAll(selectedField.getArguments().stream()
.filter(it -> !OrderByDirection.ORDER_BY.equals(it.getName()))
.filter(it -> "id".equals(it.getName()) || "number".equals(it.getName()))
.map(it -> new Argument(selectedFieldName + "." + it.getName(), it.getValue()))
.collect(Collectors.toList()));
Path root2 = joinIfNecessary((From) root, selectedFieldName);
Subgraph subgraph2 = null;
if (root2 == null) {//单纯的属性
return;
} else if (root2 == root) {//embeddable属性
root2 = root2.get(selectedFieldName);
} else if (root2 != root && (QueryForWhatEnum.NORMAL == queryForWhat)) {//join时的属性
if (entityGraph != null) {
subgraph2 = entityGraph.addSubgraph(selectedField.getName());
} else {
subgraph2 = subgraph.addSubgraph(selectedField.getName());
}
}
//Attribute selectedFieldAttribute = JpaDataFetcher.this.entityManager.getMetamodel().entity(root.getJavaType()).getAttribute(selectedFieldName);
//如果还有下一层,且不为embedable属性,则需要递归。
if (
//(selectedFieldAttribute.getPersistentAttributeType() != Attribute.PersistentAttributeType.EMBEDDED) &&
((Field) selection).getSelectionSet() != null) {
travelFieldSelection(cb, root2, ((Field) selection).getSelectionSet(), arguments, orders, null, subgraph2, queryForWhat);
}
}
}
});
}
}
/**
* @param field -选择内容
* @param queryFilter - 过滤条件
* @param queryforWhat - 是否仅仅为了查询符合条件的对象个数。如果有collection的join,则抛弃掉不管。
* @param paginator -当 justforselectcount为false时,这个paginator可以起分页的作用,同样,分页对collection的join无效
*/
protected TypedQuery getQuery(DataFetchingEnvironment environment, Field field, QueryFilter queryFilter, QueryForWhatEnum queryforWhat, Paginator paginator) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery query = (QueryForWhatEnum.JUSTFORCOUNTBYDISTINCTID == queryforWhat) ? cb.createQuery(Long.class) : (QueryForWhatEnum.JUSTFORIDSINTHEPAGE == queryforWhat) ? cb.createQuery() : cb.createQuery((Class) entityType.getJavaType());
Root root = query.from(entityType);
SelectionSet selectionSet = field.getSelectionSet();
List<Argument> arguments = new ArrayList<>();
List<Order> orders = new ArrayList<>();
EntityGraph graph = entityManager.createEntityGraph(entityType.getJavaType());
List<Predicate> predicates = new ArrayList<>();
// Loop through all of the fields being requested
//迭代的形式以便组成一条语句
travelFieldSelection(cb, root, selectionSet, arguments, orders, graph, null, queryforWhat);
Predicate predicatebyfilter = getPredicate(cb, root, environment, queryFilter);
if (predicatebyfilter != null) {
predicates.add(predicatebyfilter);
}
//最终将所有的非orderby形式的argument转化成predicate,并转成where子句.
arguments.addAll(field.getArguments());
final Root roottemp = root;
predicates.addAll(arguments.stream()
.filter(it -> "id".equals(it.getName()) || "number".equals(it.getName()))
.map(it -> getPredicate(cb, roottemp, environment, it)).collect(Collectors.toList()));
if (QueryForWhatEnum.JUSTFORCOUNTBYDISTINCTID == queryforWhat) {
SingularAttribute idAttribute = entityType.getId(Object.class);
query.select(cb.countDistinct(root.get(idAttribute.getName())));
} else if (QueryForWhatEnum.JUSTFORIDSINTHEPAGE == queryforWhat) {
query.select(root.get("id").alias("id"));
}
query.where(predicates.toArray(new Predicate[predicates.size()]));
if (QueryForWhatEnum.JUSTFORCOUNTBYDISTINCTID != queryforWhat) {
query.orderBy(orders);
}
TypedQuery result = entityManager.createQuery(query.distinct(true));
if (QueryForWhatEnum.NORMAL == queryforWhat) {
if (paginator != null) {
result.setMaxResults(paginator.getSize());
result.setFirstResult((paginator.getPage() - 1) * paginator.getSize());
}
}
//将EntityGraph加入
return result.setHint("javax.persistence.fetchgraph", graph);
}
private Predicate getPredicate(CriteriaBuilder cb, Root root, DataFetchingEnvironment environment, QueryFilter queryFilter) {
Predicate result = null;
if (queryFilter == null) {
return result;
}
String k = queryFilter.getKey();
List<String> parts = Arrays.asList(k.split("\\."));
Path path = root;
boolean isEmbeddable = false;
for (String part : parts) {
if (isEmbeddable) {
path = path.get(part);
} else {
From temp = joinIfNecessary((From) path, part);
//如果没变动,说明到顶了,该属性为简单类型,拿到路径。
if (temp == null) {
path = path.get(part);
} else if (temp == path) {//表明是embeddable属性
isEmbeddable = true;
path = path.get(part);
} else {
path = temp;
}
}
//如果(From)path不能转换,则说明queryfilter的k写错了。因为如果含有.那必须是形如roleItems.role.id这样的除最后一段外均为关系(可以作为From)的path
}
String v = queryFilter.getValue();
QueryFilterOperator qfo = queryFilter.getOperator();
QueryFilterCombinator qfc = queryFilter.getCombinator();
Object value;
//TODO 需要进一步扩展,考虑添加更多QFilter操作符
switch (qfo) {
case LIKE:
value = convertFilterValue(path.getJavaType(), v);
result = cb.like(path, (String) value);
break;
case IN:
List<Object> inList = Stream.of(v.split(",")).map(s -> (s.startsWith("'") && s.endsWith("'") ? s.substring(1, s.length() - 1) : s)).collect(Collectors.toList());
for (int i = 0; i < inList.size(); i++) {
inList.set(i, convertFilterValue(path.getJavaType(), (String) inList.get(i)));
}
result = path.in(inList);
break;
case ISNULL:
result = cb.isNull(path);
break;
case EQUEAL:
value = convertFilterValue(path.getJavaType(), v);
result = cb.equal(path, value);
;
break;
case LESSTHAN:
value = convertFilterValue(path.getJavaType(), v);
result = cb.lessThan(path, String.valueOf(value));
break;
case GREATTHAN:
value = convertFilterValue(path.getJavaType(), v);
result = cb.greaterThan(path, String.valueOf(value));
break;
case NOTLESSTHAN:
value = convertFilterValue(path.getJavaType(), v);
result = cb.greaterThanOrEqualTo(path, String.valueOf(value));
break;
case NOTGREATTHAN:
value = convertFilterValue(path.getJavaType(), v);
result = cb.lessThanOrEqualTo(path, String.valueOf(value));
break;
default:
break;
}
//操作符没有,则直接返回
if (qfc == null) {
return result;
}
Predicate next = getPredicate(cb, root, environment, queryFilter.getNext());
//如果下一个predicate本身为空,则也直接返回
if (next == null) {
return result;
}
switch (queryFilter.getCombinator()) {
case AND:
return cb.and(result, next);
case OR:
return cb.or(result, next);
default:
break;
// case NOT:
}
return result;
}
private Object convertFilterValue(Class javaType, String v) {
return (javaType == boolean.class || javaType == Boolean.class) ? Boolean.valueOf(v) :
(javaType == int.class || javaType == Integer.class) ? Integer.valueOf(v) :
(javaType == long.class || javaType == Long.class) ? Long.valueOf(v) :
(BosEnum.class.isAssignableFrom(javaType)) ?
Arrays.stream((BosEnum[]) javaType.getEnumConstants()).filter(bosEnum -> EntityEnumUtil.getValueByEnum(bosEnum).equals(v)).findFirst()
.orElse(null) : v;
}
/**
* 判断是否需要进行join连接,如有必要则连接并返回。根据BOS模型,有三种可能:
* 1。如若必要,则执行join。如进行one2many或者many2one,则需要进行join,并返回新的连接。
* 2。返回自身(即currentjoin)则表示碰到的是一个embeddable属性,无需join。
* 3。返回null则表示碰到的是一个简单属性,无需jion,为了与第2点区分开,则需要返回null.
*
* @param currentjoin -当前join
* @param attributeName - 当前join对应的实体类中的某属性名称
*/
private From joinIfNecessary(From currentjoin, String attributeName) {
//根据属性名拿到所在实体里对应的属性值,此处可能因为该属性不存在而报错,这说明queryfilter表达式写错了。
Attribute selectedFieldAttribute = JpaDataFetcher.this.entityManager.getMetamodel().entity(currentjoin.getJavaType()).getAttribute(attributeName);
//如果该属性是one2many或者many2one,则检查是否需要在当前from中添加join(如果之前存在就不添加,否则要添加)
boolean jpaMap = (selectedFieldAttribute instanceof PluralAttribute &&
selectedFieldAttribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.ONE_TO_MANY)
|| (selectedFieldAttribute instanceof SingularAttribute
&& selectedFieldAttribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.MANY_TO_ONE);
if (jpaMap) {
//如果不存在则添加,并将返回的from设置为新的join
Optional<Join> optjoin = currentjoin.getJoins()
.stream()
.filter(join -> attributeName.equals(((Join) join).getAttribute().getName()))
.findAny();
return optjoin.isPresent() ? optjoin.get() : currentjoin.join(attributeName, JoinType.LEFT);
} else if (selectedFieldAttribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.EMBEDDED) {//如果是embeddable类型,返回原有的。
return currentjoin;
} else {//如果为简单类型,则说明用不到新的join,返回null。
return null;
}
}
/**
* @param argument -为某个字段的过滤参数生成断言
*/
private Predicate getPredicate(CriteriaBuilder cb, Root root, DataFetchingEnvironment environment, Argument argument) {
Path path = null;
if (!argument.getName().contains(".")) {
Attribute argumentEntityAttribute = getAttribute(environment, argument);
//似乎只能采用但字段不带点号的,且不带关系的标量==式断言,因此这里的join意义不大,TODO 总觉得这个函数有点问题。
// If the argument is a list, let's assume we need to join and do an 'in' clause
if (argumentEntityAttribute instanceof PluralAttribute) {
Join join = root.join(argument.getName());
return join.in(convertValue(environment, argument, argument.getValue()));
}
path = root.get(argument.getName());
return cb.equal(path, convertValue(environment, argument, argument.getValue()));
} else {
String[] parts = argument.getName().split("\\.");
for (String part : parts) {
if (path == null) {
path = root.get(part);
} else {
path = path.get(part);
}
}
return cb.equal(path, convertValue(environment, argument, argument.getValue()));
}
}
protected Object convertValue(DataFetchingEnvironment environment, Argument argument, Value value) {
if (value instanceof StringValue) {
Object convertedValue = environment.getArgument(argument.getName());
if (convertedValue != null) {
// Return real parameter for instance UUID even if the Value is a StringValue
return convertedValue;
} else {
// Return provided StringValue
return ((StringValue) value).getValue();
}
} else if (value instanceof VariableReference) {
return environment.getArguments().get(((VariableReference) value).getName());
} else if (value instanceof ArrayValue) {
return ((ArrayValue) value).getValues().stream().map((it) -> convertValue(environment, argument, it)).collect(Collectors.toList());
} else if (value instanceof EnumValue) {
Class enumType = getJavaType(environment, argument);
return Enum.valueOf(enumType, ((EnumValue) value).getName());
} else if (value instanceof IntValue) {
return ((IntValue) value).getValue();
} else if (value instanceof BooleanValue) {
return ((BooleanValue) value).isValue();
} else if (value instanceof FloatValue) {
return ((FloatValue) value).getValue();
}
return value.toString();
}
private Class getJavaType(DataFetchingEnvironment environment, Argument argument) {
Attribute argumentEntityAttribute = getAttribute(environment, argument);
if (argumentEntityAttribute instanceof PluralAttribute) {
return ((PluralAttribute) argumentEntityAttribute).getElementType().getJavaType();
}
return argumentEntityAttribute.getJavaType();
}
private Attribute getAttribute(DataFetchingEnvironment environment, Argument argument) {
GraphQLObjectType objectType = getObjectType(environment, argument);
EntityType entityType = getEntityType(objectType);
return entityType.getAttribute(argument.getName());
}
private EntityType getEntityType(GraphQLObjectType objectType) {
return entityManager.getMetamodel().getEntities().stream().filter(it -> it.getName().equals(objectType.getName())).findFirst().orElse(null);
}
private GraphQLObjectType getObjectType(DataFetchingEnvironment environment, Argument argument) {
GraphQLType outputType = environment.getFieldType();
if (outputType instanceof GraphQLList) {
outputType = ((GraphQLList) outputType).getWrappedType();
}
if (outputType instanceof GraphQLObjectType) {
return (GraphQLObjectType) outputType;
}
return null;
}
/**
* @param dept 外部调用仅给 0
*/
protected Object convertValue(DataFetchingEnvironment environment, final GraphQLInputType graphQLInputType, Object value, int dept) {
if (graphQLInputType instanceof GraphQLNonNull) {
return convertValue(environment, (GraphQLInputType) (((GraphQLNonNull) graphQLInputType).getWrappedType()), value, dept);
//否则如果为空
} else if (value == null) {
return null;
} else if (value instanceof VariableReference) {
value = environment.getExecutionContext().getVariables().get(((VariableReference) value).getName());
return convertValue(environment, graphQLInputType, value, dept);
//many2one
} else if (graphQLInputType instanceof GraphQLInputObjectType) {
Map<String, Object> map = (value instanceof Map) ? (Map) value : new HashMap();
//还有可能是ObjectValue,内嵌Argument类型(相对于外部variable)的就是这种类型的。
if (value instanceof ObjectValue) {
((ObjectValue) value).getObjectFields().forEach(field -> map.put(field.getName(), field.getValue()));
}
map.keySet().forEach(key -> {
GraphQLInputType giotype = ((GraphQLInputObjectType) graphQLInputType).getField(key.toString()).getType();
map.put(key, convertValue(environment, giotype, map.get(key), dept + 1));
});
Object result;
try {
result = this.graphQlTypeMapper.getClazzByInputType(graphQLInputType).newInstance();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("convertValue.error!");
}
ConfigurablePropertyAccessor wrapper = PropertyAccessorFactory.forDirectFieldAccess(result);
wrapper.setPropertyValues(map);
return result;
} else if (graphQLInputType instanceof GraphQLList) {
List list = new ArrayList();
if (value instanceof ArrayValue) {
GraphQLInputType gitype = ((GraphQLInputType) ((GraphQLList) graphQLInputType).getWrappedType());
list = ((ArrayValue) value).getValues().stream().map((it) -> convertValue(environment, gitype, it, dept + 1)).collect(Collectors.toList());
} else if (value instanceof Collection) {
for (Object item : ((Collection) value)) {
GraphQLInputType gitype = ((GraphQLInputType) ((GraphQLList) graphQLInputType).getWrappedType());
list.add(convertValue(environment, gitype, item, dept + 1));
}
}
//mutation 的顶级参数是 List,返回List 否则全部返回 set,因为 entry 是以set 形式存在
if (dept != 0) {
Set set = new HashSet(list.size());
set.addAll(list);
return set;
} else {
return list;
}
} else if (graphQLInputType instanceof GraphQLEnumType) {
return (value instanceof BosEnum) ? value : this.graphQlTypeMapper.getBosEnumByValue((GraphQLEnumType) graphQLInputType, (value instanceof EnumValue) ? ((EnumValue) value).getName() : value.toString());
//scalar
} else if (graphQLInputType instanceof GraphQLScalarType) {
if (!(value instanceof Value)) {
value = (value instanceof Integer) ? new IntValue(BigInteger.valueOf(((Integer) value).longValue())) :
(value instanceof BigInteger) ? new IntValue((BigInteger) value) :
(value instanceof Boolean) ? (new BooleanValue((Boolean) value)) :
value instanceof String ? new StringValue((String) value) :
value instanceof Float ? new FloatValue(BigDecimal.valueOf((Float) value)) :
value instanceof Double ? new FloatValue(BigDecimal.valueOf((Double) value)) :
value instanceof BigDecimal ? new FloatValue((BigDecimal) value) :
value instanceof Long ? new IntValue(BigInteger.valueOf((Long) value))
: null;
}
if (value != null) {
return ((GraphQLScalarType) graphQLInputType).getCoercing().parseLiteral(value);
}
}
throw new RuntimeException("convertValue scalar mismatch?" + graphQLInputType.getName() + ":" + value.getClass().getCanonicalName());
}
}
|
package edu.buet.cse.spring.ch03.v4.impl;
import edu.buet.cse.spring.ch03.v4.model.Poem;
public class ToHelen implements Poem {
private static final String[] LINES = {
"Helen, thy beauty is to me",
"Like those Nicean barks of yore",
"That gently, o'er a perfumed sea,",
"The weary, way-worn wanderer bore",
"To his own native shore.",
"On desperate seas long wont to roam,",
"Thy hyacinth hair, thy classic face,",
"Thy Naiad airs have brought me home",
"To the glory that was Greece,",
"And the grandeur that was Rome.",
"Lo, in yon brilliant window-niche",
"How statue-like I see thee stand,",
"The agate lamp within thy hand,",
"Ah! Psyche, from the regions which",
"Are Holy Land!"
};
@Override
public void recite() {
for (String line : LINES) {
System.out.println(line);
}
}
}
|
package org.inftel.socialwind.client.mobile.controllers;
import java.io.Serializable;
import java.util.ArrayList;
import org.inftel.socialwind.client.mobile.models.HotspotModel;
import org.inftel.socialwind.client.mobile.vos.Spot;
public class HotspotController implements Serializable {
private static final long serialVersionUID = 1196041083668069897L;
private HotspotModel model;
/**
* Constructor
*
* @param model
*/
public HotspotController(HotspotModel model) {
this.model = model;
}
public ArrayList<Spot> getHotspots() {
return model.getHotspots();
}
/**
* Actualiza los hotspots del modelo
*
* @param hotspots
*/
public void updateHotspots(ArrayList<Spot> hotspots) {
model.setHotspots(hotspots);
}
}
|
package itri.io.emulator.cleaner;
import org.apache.commons.csv.CSVRecord;
/**
* Abstract class of Filter
*/
public abstract class Filter {
public abstract boolean filter(CSVRecord record);
public abstract void setFilterOptions(Object options);
}
|
/*
* 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 it.unive.dagg.card;
/**
* Crea la carta Incantesimo
* @author alessandro
*/
public class SorceryCard extends AbstractCard {
/**
* Costruttore della carta incantesimo
* @param name
* @param desc
*/
public SorceryCard(String name, String desc) {
super(name, desc);
}
}
|
package com.bright.website.service;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.bright.website.web.dao.SysRoleMapper;
import com.bright.website.web.model.SysRole;
import com.bright.website.web.model.SysRoleExample;
@Service
public class RoleServiceImpl implements Roleservice {
@Resource
private SysRoleMapper mapper;
@Resource
private ResourceService service;
@Override
public int deleteByPrimaryKey(Integer id) {
int i = mapper.deleteByPrimaryKey(id);
return i;
}
@Override
public int insert(SysRole record) {
int i = mapper.insert(record);
return i;
}
@Override
public int updateByPrimaryKeySelective(SysRole record) {
int i = updateByPrimaryKeySelective(record);
return i;
}
@Override
public List<SysRole> selectByExample(SysRoleExample example) {
return mapper.selectByExample(example);
}
@Override
public SysRole selectByPrimaryKey(Integer id) {
return mapper.selectByPrimaryKey(id);
}
public Set<String> findRoles(Integer... roleIds) {
Set<String> roles = new HashSet<String>();
for(Integer roleId : roleIds) {
SysRole role = selectByPrimaryKey(roleId);
if(role != null) {
roles.add(role.getRole());
}
}
return roles;
}
public Set<String> findPermissions(Integer[] roleIds) {
Set<Integer> resourceIds = new HashSet<Integer>();
for(Integer roleId : roleIds) {
SysRole role = selectByPrimaryKey(roleId);
if(role != null) {
resourceIds.addAll(role.getresourceIdss());
}
}
return service.findPermissions(resourceIds);
}
}
|
package com.data.rhis2;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.location.Location;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import Common.Connection;
import Common.Global;
/**
* Created by user on 10/03/2015.
*/
public class PregReg extends Activity {
boolean netwoekAvailable = false;
Location currentLocation;
double currentLatitude, currentLongitude;
Location currentLocationNet;
double currentLatitudeNet, currentLongitudeNet;
private boolean IsUserHA() {
if (g.getProvType().equalsIgnoreCase("2"))
return true;
else
return false;
}
//Disabled Back/Home key
//--------------------------------------------------------------------------------------------------
@Override
public boolean onKeyDown(int iKeyCode, KeyEvent event) {
if (iKeyCode == KeyEvent.KEYCODE_BACK || iKeyCode == KeyEvent.KEYCODE_HOME) {
return false;
} else {
return true;
}
}
//Top menu
//--------------------------------------------------------------------------------------------------
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mnuclose, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
AlertDialog.Builder adb = new AlertDialog.Builder(PregReg.this);
switch (item.getItemId()) {
case R.id.menuClose:
adb.setTitle("Close");
adb.setMessage("আপনি কি এই ফর্ম থেকে বের হতে চান?");
adb.setNegativeButton("না", null);
adb.setPositiveButton("হ্যাঁ", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
Intent f2 = new Intent(getApplicationContext(), ELCOForm.class);
startActivity(f2);
}
});
adb.show();
return true;
}
return false;
}
String VariableID;
private int hour;
private int minute;
private int mDay;
private int mMonth;
private int mYear;
static final int DATE_DIALOG = 1;
static final int TIME_DIALOG = 2;
Connection C;
Global g;
SimpleAdapter dataAdapter;
Calendar c = Calendar.getInstance();
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
private String TableName;
private String TablePregRefer;
private String TableANC;
private String TableNameElcoVisit;
TextView txtHealthID;
LinearLayout secdelete1;
//LinearLayout secDelete;
LinearLayout secDiv;
TextView VlblDiv;
EditText txtDiv;
LinearLayout secDist;
TextView VlblDist;
EditText txtDist;
LinearLayout secUpz;
TextView VlblUpz;
EditText txtUpz;
LinearLayout secUN;
TextView VlblUN;
EditText txtUN;
LinearLayout secMouza;
TextView VlblMouza;
EditText txtMouza;
LinearLayout secVill;
TextView VlblVill;
EditText txtVill;
LinearLayout seclblH1;
TextView lblHlblH;
TextView lblHealthID;
EditText txtHHNo;
LinearLayout secSNo;
TextView VlblSLNo;
TextView txtSLNo;
TextView VlblSNo;
TextView txtSNo;
EditText txtELCONo;
LinearLayout secName;
TextView VlblName;
TextView txtName;
LinearLayout secAge;
TextView VlblAge;
TextView txtAge;
LinearLayout secLMP;
TextView VlblLMP;
EditText dtpLMP;
ImageButton btnLMP;
LinearLayout secLive;
TextView VlblLiveSonDau;
EditText txtLiveSonDau;
LinearLayout secPgn;
TextView VlblPgn;
Spinner spnPgn;
LinearLayout secEDD;
TextView VlblEDD;
EditText dtpEDD;
LinearLayout secAgeL;
TextView VlblAgeL;
EditText txtAgeM;
EditText txtAgeY;
/*LinearLayout secVDate;
TextView VlblVDate;
EditText dtpVDate;
ImageButton btnVDate;
LinearLayout secIron;
TextView VlblIron;
RadioGroup rdogrpIron;
RadioButton rdoIron1;
RadioButton rdoIron2;
LinearLayout secMiso;
TextView VlblMiso;
RadioGroup rdogrpMiso;
RadioButton rdoMiso1;
RadioButton rdoMiso2;*/
LinearLayout secDengersine;
TextView VlblDanger;
CheckBox chkDengersine;
LinearLayout secDengersine1;
TextView VlblDanger1;
CheckBox chkDengersine1;
LinearLayout secDengersine2;
TextView VlblDanger2;
CheckBox chkDengersine2;
LinearLayout secDengersine3;
TextView VlblDanger3;
CheckBox chkDengersine3;
LinearLayout secDengersine4;
TextView VlblDanger4;
CheckBox chkDengersine4;
LinearLayout secDengersine5;
TextView VlblDanger5;
CheckBox chkDengersine5;
LinearLayout secDengersine6;
TextView VlblDanger6;
CheckBox chkDengersine6;
LinearLayout secDengersine7;
TextView VlblDanger7;
CheckBox chkDengersine7;
LinearLayout secReferWomen;
TextView VlblReferWomen;
RadioGroup rdogrpReferWomen;
RadioButton rdoReferWomen1;
RadioButton rdoReferWomen2;
LinearLayout secReferFaci;
TextView VlblFaci;
Spinner spnFaci;
TextView VlblServiceId;
//LinearLayout secANCVisit;
String StartTime;
Button cmdSave;
Button btnSaveRef;
LinearLayout secPregVisit;
String sqlnew = "";
String sqlupdate = "";
// String Sex ="";
String Age = "";
String pregnancyNo = "";
String pregnancyNoDelivary = "";
String LastDelivaryDate = "";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.pregnancy_register);
C = new Connection(this);
g = Global.getInstance();
StartTime = g.CurrentTime24();
TableName = "PregWomen";
TablePregRefer = "PregRefer";
TableANC = "ancService";
TableNameElcoVisit = "ELCOVisit";
seclblH1 = (LinearLayout) findViewById(R.id.seclblH1);
secdelete1 = (LinearLayout) findViewById(R.id.secdelete1);
secdelete1.setVisibility(View.GONE);
//secDelete= (LinearLayout) findViewById(R.id.secDelete);
//secDelete.setVisibility(View.GONE);
//Sex Return
//Sex=C.ReturnSingleValue("Select Sex from Member where healthId ='"+g.getHealthID()+"'");
// Age=C.ReturnSingleValue("Select Age from Member where healthId ='"+g.getHealthID()+"'");
//secANCVisit = (LinearLayout) findViewById(R.id.secANCVisit);
secPregVisit = (LinearLayout) findViewById(R.id.secPregVisit);
txtHealthID = (TextView) findViewById(R.id.txtHealthID);
txtHHNo = (EditText) findViewById(R.id.txtHHNo);
VlblSNo = (TextView) findViewById(R.id.VlblSNo);
txtSNo = (TextView) findViewById(R.id.txtSNo);
VlblSLNo = (TextView) findViewById(R.id.VlblSNo);
txtSLNo = (TextView) findViewById(R.id.txtSLNo);
txtSLNo.setText(GetCountSLNoNumber());
VlblSNo.setVisibility(View.GONE);
txtSNo.setVisibility(View.GONE);
txtELCONo = (EditText) findViewById(R.id.txtELCONo);
txtELCONo.setEnabled(false);
// txtELCONo.setText(g.getAMElco());
secName = (LinearLayout) findViewById(R.id.secName);
VlblName = (TextView) findViewById(R.id.VlblName);
txtName = (TextView) findViewById(R.id.txtName);
secAge = (LinearLayout) findViewById(R.id.secAge);
VlblAge = (TextView) findViewById(R.id.VlblAge);
txtAge = (TextView) findViewById(R.id.txtAge);
secLMP = (LinearLayout) findViewById(R.id.secLMP);
VlblLMP = (TextView) findViewById(R.id.VlblLMP);
dtpLMP = (EditText) findViewById(R.id.dtpLMP);
btnLMP = (ImageButton) findViewById(R.id.btnLMP);
secLive = (LinearLayout) findViewById(R.id.secLive);
VlblLiveSonDau = (TextView) findViewById(R.id.VlblLiveSonDau);
txtLiveSonDau = (EditText) findViewById(R.id.txtLiveSonDau);
secPgn = (LinearLayout) findViewById(R.id.secPgn);
VlblPgn = (TextView) findViewById(R.id.VlblPgn);
spnPgn = (Spinner) findViewById(R.id.spnPgn);
spnPgn.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (spnPgn.getSelectedItemPosition() == 0) {
} else {
String PrevPGN = "'" + GetMaxPGN() == "0" ? "" : GetMaxPGN() + "";
if (PrevPGN.equalsIgnoreCase("")) {
} else {
Integer PrevPGNPlus1 = Integer.parseInt(PrevPGN) + 1;
Integer ActualPrevPGN = Integer.parseInt(PrevPGN);
Integer pgnpositionselected = Integer.parseInt(String.valueOf(spnPgn.getSelectedItemPosition()));
if (!pgnpositionselected.equals(ActualPrevPGN)) {
if (!PrevPGNPlus1.equals(pgnpositionselected)) {
Connection.MessageBox(PregReg.this, "বর্তমানে কত তম গর্ভ তথ্য সঠিক নয়।");
spnPgn.requestFocus();
return;
}
}
}
}
}
public void onNothingSelected(AdapterView<?> adapterView) {
return;
}
});
secEDD = (LinearLayout) findViewById(R.id.secEDD);
VlblEDD = (TextView) findViewById(R.id.VlblEDD);
dtpEDD = (EditText) findViewById(R.id.dtpEDD);
secAgeL = (LinearLayout) findViewById(R.id.secAgeL);
VlblAgeL = (TextView) findViewById(R.id.VlblAgeL);
txtAgeM = (EditText) findViewById(R.id.txtAgeMo);
txtAgeY = (EditText) findViewById(R.id.txtAgeY);
secDengersine = (LinearLayout) findViewById(R.id.secDengersine);
VlblDanger = (TextView) findViewById(R.id.VlblDanger);
chkDengersine = (CheckBox) findViewById(R.id.chkDengersine);
chkDengersine.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// g.setRisk("r");
secDengersine1.setVisibility(View.VISIBLE);
secDengersine2.setVisibility(View.VISIBLE);
secDengersine3.setVisibility(View.VISIBLE);
secDengersine4.setVisibility(View.VISIBLE);
secDengersine5.setVisibility(View.VISIBLE);
secDengersine6.setVisibility(View.VISIBLE);
secDengersine7.setVisibility(View.VISIBLE);
} else {
secDengersine1.setVisibility(View.GONE);
secDengersine2.setVisibility(View.GONE);
secDengersine3.setVisibility(View.GONE);
secDengersine4.setVisibility(View.GONE);
secDengersine5.setVisibility(View.GONE);
secDengersine6.setVisibility(View.GONE);
secDengersine7.setVisibility(View.GONE);
}
}
});
secDengersine1 = (LinearLayout) findViewById(R.id.secDengersine1);
VlblDanger1 = (TextView) findViewById(R.id.VlblDanger1);
chkDengersine1 = (CheckBox) findViewById(R.id.chkDengersine1);
chkDengersine1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (chkDengersine1.isChecked() == true || chkDengersine2.isChecked() == true ||
chkDengersine3.isChecked() == true || chkDengersine4.isChecked() == true ||
chkDengersine5.isChecked() == true || chkDengersine6.isChecked() == true || chkDengersine7.isChecked() == true
) {
secReferWomen.setVisibility(View.VISIBLE);
} else if (chkDengersine1.isChecked() == false && chkDengersine2.isChecked() == false &&
chkDengersine3.isChecked() == false && chkDengersine4.isChecked() == false &&
chkDengersine5.isChecked() == false && chkDengersine6.isChecked() == false && chkDengersine7.isChecked() == false
) {
secReferWomen.setVisibility(View.GONE);
}
}
});
secDengersine2 = (LinearLayout) findViewById(R.id.secDengersine2);
VlblDanger2 = (TextView) findViewById(R.id.VlblDanger2);
chkDengersine2 = (CheckBox) findViewById(R.id.chkDengersine2);
chkDengersine2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (chkDengersine1.isChecked() == true || chkDengersine2.isChecked() == true ||
chkDengersine3.isChecked() == true || chkDengersine4.isChecked() == true ||
chkDengersine5.isChecked() == true || chkDengersine6.isChecked() == true || chkDengersine7.isChecked() == true
) {
secReferWomen.setVisibility(View.VISIBLE);
} else if (chkDengersine1.isChecked() == false && chkDengersine2.isChecked() == false &&
chkDengersine3.isChecked() == false && chkDengersine4.isChecked() == false &&
chkDengersine5.isChecked() == false && chkDengersine6.isChecked() == false && chkDengersine7.isChecked() == false
) {
secReferWomen.setVisibility(View.GONE);
}
}
});
secDengersine3 = (LinearLayout) findViewById(R.id.secDengersine3);
VlblDanger3 = (TextView) findViewById(R.id.VlblDanger3);
chkDengersine3 = (CheckBox) findViewById(R.id.chkDengersine3);
chkDengersine3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (chkDengersine1.isChecked() == true || chkDengersine2.isChecked() == true ||
chkDengersine3.isChecked() == true || chkDengersine4.isChecked() == true ||
chkDengersine5.isChecked() == true || chkDengersine6.isChecked() == true || chkDengersine7.isChecked() == true
) {
secReferWomen.setVisibility(View.VISIBLE);
} else if (chkDengersine1.isChecked() == false && chkDengersine2.isChecked() == false &&
chkDengersine3.isChecked() == false && chkDengersine4.isChecked() == false &&
chkDengersine5.isChecked() == false && chkDengersine6.isChecked() == false && chkDengersine7.isChecked() == false
) {
secReferWomen.setVisibility(View.GONE);
}
}
});
secDengersine4 = (LinearLayout) findViewById(R.id.secDengersine4);
VlblDanger4 = (TextView) findViewById(R.id.VlblDanger4);
chkDengersine4 = (CheckBox) findViewById(R.id.chkDengersine4);
chkDengersine4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (chkDengersine1.isChecked() == true || chkDengersine2.isChecked() == true ||
chkDengersine3.isChecked() == true || chkDengersine4.isChecked() == true ||
chkDengersine5.isChecked() == true || chkDengersine6.isChecked() == true || chkDengersine7.isChecked() == true
) {
secReferWomen.setVisibility(View.VISIBLE);
} else if (chkDengersine1.isChecked() == false && chkDengersine2.isChecked() == false &&
chkDengersine3.isChecked() == false && chkDengersine4.isChecked() == false &&
chkDengersine5.isChecked() == false && chkDengersine6.isChecked() == false && chkDengersine7.isChecked() == false
) {
secReferWomen.setVisibility(View.GONE);
}
}
});
secDengersine5 = (LinearLayout) findViewById(R.id.secDengersine5);
VlblDanger5 = (TextView) findViewById(R.id.VlblDanger5);
chkDengersine5 = (CheckBox) findViewById(R.id.chkDengersine5);
chkDengersine5.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (chkDengersine1.isChecked() == true || chkDengersine2.isChecked() == true ||
chkDengersine3.isChecked() == true || chkDengersine4.isChecked() == true ||
chkDengersine5.isChecked() == true || chkDengersine6.isChecked() == true || chkDengersine7.isChecked() == true
) {
secReferWomen.setVisibility(View.VISIBLE);
} else if (chkDengersine1.isChecked() == false && chkDengersine2.isChecked() == false &&
chkDengersine3.isChecked() == false && chkDengersine4.isChecked() == false &&
chkDengersine5.isChecked() == false && chkDengersine6.isChecked() == false && chkDengersine7.isChecked() == false
) {
secReferWomen.setVisibility(View.GONE);
}
}
});
secDengersine6 = (LinearLayout) findViewById(R.id.secDengersine6);
VlblDanger6 = (TextView) findViewById(R.id.VlblDanger6);
chkDengersine6 = (CheckBox) findViewById(R.id.chkDengersine6);
chkDengersine6.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (chkDengersine1.isChecked() == true || chkDengersine2.isChecked() == true ||
chkDengersine3.isChecked() == true || chkDengersine4.isChecked() == true ||
chkDengersine5.isChecked() == true || chkDengersine6.isChecked() == true || chkDengersine7.isChecked() == true
) {
secReferWomen.setVisibility(View.VISIBLE);
} else if (chkDengersine1.isChecked() == false && chkDengersine2.isChecked() == false &&
chkDengersine3.isChecked() == false && chkDengersine4.isChecked() == false &&
chkDengersine5.isChecked() == false && chkDengersine6.isChecked() == false && chkDengersine7.isChecked() == false
) {
secReferWomen.setVisibility(View.GONE);
}
}
});
secDengersine7 = (LinearLayout) findViewById(R.id.secDengersine7);
VlblDanger7 = (TextView) findViewById(R.id.VlblDanger7);
chkDengersine7 = (CheckBox) findViewById(R.id.chkDengersine7);
chkDengersine7.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (chkDengersine1.isChecked() == true || chkDengersine2.isChecked() == true ||
chkDengersine3.isChecked() == true || chkDengersine4.isChecked() == true ||
chkDengersine5.isChecked() == true || chkDengersine6.isChecked() == true || chkDengersine7.isChecked() == true
) {
secReferWomen.setVisibility(View.VISIBLE);
} else if (chkDengersine1.isChecked() == false && chkDengersine2.isChecked() == false &&
chkDengersine3.isChecked() == false && chkDengersine4.isChecked() == false &&
chkDengersine5.isChecked() == false && chkDengersine6.isChecked() == false && chkDengersine7.isChecked() == false
) {
secReferWomen.setVisibility(View.GONE);
}
}
});
/* secDengersine = (LinearLayout) findViewById(R.id.secDengersine);
VlblDanger = (TextView) findViewById(R.id.VlblDanger);
rdogrpDanger = (RadioGroup) findViewById(R.id.rdogrpDanger);
rdoDanger1 = (RadioButton) findViewById(R.id.rdoDanger1);
rdoDanger2 = (RadioButton) findViewById(R.id.rdoDanger2);
rdogrpDanger.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(RadioGroup radioGroup,int radioButtonID) {
RadioButton rb = (RadioButton)findViewById(rdogrpDanger.getCheckedRadioButtonId());
if (rb == null) return;
if(rdoDanger2.isChecked()==true)
{
secReferWomen.setVisibility(View.GONE);
rdogrpReferWomen.clearCheck();
secReferFaci.setVisibility(View.GONE);
spnFaci.setSelection(0);
}
else
{
secReferWomen.setVisibility(View.VISIBLE);
}
}
public void onNothingSelected(AdapterView<?> adapterView) {
return;
}
});*/
secReferWomen = (LinearLayout) findViewById(R.id.secReferWomen);
VlblReferWomen = (TextView) findViewById(R.id.VlblReferWomen);
rdogrpReferWomen = (RadioGroup) findViewById(R.id.rdogrpReferWomen);
rdoReferWomen1 = (RadioButton) findViewById(R.id.rdoReferWomen1);
rdoReferWomen2 = (RadioButton) findViewById(R.id.rdoReferWomen2);
rdogrpReferWomen.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int radioButtonID) {
RadioButton rb = (RadioButton) findViewById(rdogrpReferWomen.getCheckedRadioButtonId());
if (rb == null) return;
if (rdoReferWomen2.isChecked() == true) {
secReferFaci.setVisibility(View.GONE);
spnFaci.setSelection(0);
} else {
ReferStatus();
secReferFaci.setVisibility(View.VISIBLE);
}
}
public void onNothingSelected(AdapterView<?> adapterView) {
return;
}
});
secReferFaci = (LinearLayout) findViewById(R.id.secReferFaci);
VlblFaci = (TextView) findViewById(R.id.VlblFaci);
spnFaci = (Spinner) findViewById(R.id.spnFaci);
btnSaveRef = (Button) findViewById(R.id.btnSaveRef);
VlblServiceId = (TextView) findViewById(R.id.VlblServiceId);
VlblServiceId.setVisibility(View.GONE);
List<String> listFacility = new ArrayList<String>();
listFacility.add("");
listFacility.add("01-উপজেলা স্বাস্থ্য কমপ্লেক্স");
listFacility.add("02-ইউনিয়ন স্বাস্থ্য ও পরিবার কল্যাণ কেন্দ্র");
listFacility.add("03-মা ও শিশু কল্যাণ কেন্দ্র");
listFacility.add("04-জেলা সদর বা অন্যান্য সরকারী হাসপাতাল");
listFacility.add("05-এনজিও ক্লিনিক বা হাসপাতাল");
listFacility.add("06-প্রাইভেট ক্লিনিক বা হাসপাতাল");
listFacility.add("77-অন্যান্য");
ArrayAdapter<String> adptrspnFaci = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, listFacility);
spnFaci.setAdapter(adptrspnFaci);
/*
*/
List<String> listPgn = new ArrayList<String>();
listPgn.add("");
listPgn.add("১ম");
listPgn.add("২য় ");
listPgn.add("৩য়");
listPgn.add("৪র্থ");
listPgn.add("৫ম");
listPgn.add("৬ষ্ঠ");
listPgn.add("৭ম");
listPgn.add("৮ম");
listPgn.add("৯ম");
listPgn.add("১০ম ");
ArrayAdapter<String> adptrspnPgn = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, listPgn);
spnPgn.setAdapter(adptrspnPgn);
btnLMP.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
VariableID = "btnLMP";
showDialog(DATE_DIALOG);
}
});
Bundle IDbundle = new Bundle();
IDbundle = getIntent().getExtras();
if (IDbundle != null) {
// fornewpregnancy = IDbundle.getString("exists");
sqlnew = IDbundle.getString("sqlnew");
sqlupdate = IDbundle.getString("sqlupdate");
// PGNNo = IDbundle.getString("PGNNo");
}
/* if(fornewpregnancy.equalsIgnoreCase(""))
{
PregWomenSearch("");
}
else if(fornewpregnancy.equalsIgnoreCase("exists"))
{
PregWomenSearch("exists");
}*/
// add fazlur bhi
ELCOProfile e = new ELCOProfile();
e.ELCOProfile(this, g.getHealthID());
//call from elco
if (g.getCallFrom().equals("elco")) {
pregnancyNo = e.CurrentPregNumber(this, g.getGeneratedId());
}
//call from register
else if (g.getCallFrom().equals("regis")) {
pregnancyNo = e.LastPregNumber(this, g.getGeneratedId());
} else if (g.getCallFrom().equals("1")) {
pregnancyNo = e.LastPregNumber(this, g.getGeneratedId());
} else if (g.getCallFrom().equals("HAregis")) {
pregnancyNo = e.LastPregNumber(this, g.getGeneratedId());
pregnancyNoDelivary = e.LastPregNumberFromDelivary(this, g.getGeneratedId());
//pregnancyNo = e.LastPregNumber(this, g.getGeneratedId());
//pregnancyNoDelivary = e.LastPregNumberFromDelivary(this, g.getGeneratedId());
if (pregnancyNo.equalsIgnoreCase("0")) {
pregnancyNo = "1";
} else if (pregnancyNo.equalsIgnoreCase(pregnancyNoDelivary)) {
LastDelivaryDate = e.LastDelivaryDateFromDelivary(this, g.getGeneratedId());
Integer DaysFromDelivaryDays = Global.DateDifferenceDays(Global.DateNowDMY(), Global.DateConvertDMY(LastDelivaryDate));
if (DaysFromDelivaryDays > 60) {
pregnancyNo = e.CurrentPregNumber(this, g.getGeneratedId());
} else {
pregnancyNo = e.LastPregNumber(this, g.getGeneratedId());
}
} else if (!pregnancyNo.equalsIgnoreCase(pregnancyNoDelivary)) {
pregnancyNo = e.LastPregNumber(this, g.getGeneratedId());
}
}
//Comments for HA module but open for FWA Module
//e.PregnancyInfo(this, g.getGeneratedId(), pregnancyNo);
e.PregnancyInfo(this, g.getGeneratedId(), pregnancyNo);
// add fazlu bhi
// Age = String.valueOf(e.getAge());
// Age = String.valueOf(g.getAAge());
// Sex = e.getSex();
dtpLMP.setText(e.getLMP());
dtpEDD.setText(e.getEDD());
spnPgn.setSelection(Integer.parseInt(e.getGravida() == null ? "0" : e.getGravida()));
String totalChild = e.getTotalLiveChild();
txtLiveSonDau.setText(totalChild);
if (totalChild != null) {
if (GetTotalSonGaughter(g.getGeneratedId()).equals("0")) {
secAgeL.setVisibility(View.GONE);
} else {
secAgeL.setVisibility(View.VISIBLE);
}
}
/* if (totalChild.equalsIgnoreCase("0")) {
secAgeL.setVisibility(View.GONE);
} else {
secAgeL.setVisibility(View.VISIBLE);
}*/
//PregWomenSearch();
//DataSearch(g.getHealthID());
//ELCONoSearch(g.getSerialNo());
//nisan Dengersine
secDengersine1.setVisibility(View.GONE);
secDengersine2.setVisibility(View.GONE);
secDengersine3.setVisibility(View.GONE);
secDengersine4.setVisibility(View.GONE);
secDengersine5.setVisibility(View.GONE);
secDengersine6.setVisibility(View.GONE);
secDengersine7.setVisibility(View.GONE);
secReferWomen.setVisibility(View.GONE);
secReferFaci.setVisibility(View.GONE);
//chkDengersine.setEnabled(false);
chkDengersine1.setEnabled(false);
// chkDengersine2.setEnabled(false);
chkDengersine3.setEnabled(false);
//chkDengersine4.setEnabled(false);
//chkDengersine5.setEnabled(false);
// chkDengersine6.setEnabled(false);
// chkDengersine7.setEnabled(false);
//1
// if((Integer.valueOf(Age)>35||Integer.valueOf(Age)<18) )
if ((Integer.valueOf(g.getAAge()) > 35 || Integer.valueOf(g.getAAge()) < 18)) {
//chkDengersine.setChecked(true);
chkDengersine1.setChecked(true);
VlblDanger1.setText("");
VlblDanger1.setText(Html.fromHtml(VlblDanger1.getText() + "<font color=red>গর্ভবতী মায়ের বয়স ১৮ বছরের কম বা ৩৫ বছরের বেশি হলে</font>"));
} else {
// chkDengersine.setChecked(false);
chkDengersine1.setChecked(false);
}
//2
chkDengersine2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (chkDengersine2.isChecked() == true) {
chkDengersine2.setChecked(true);
VlblDanger2.setText("");
VlblDanger2.setText(Html.fromHtml(VlblDanger2.getText() + "<font color=red>প্রথম গর্ভাবস্থা বা ৩ এর অধিক সন্তান জন্ম দিয়েছেন এমন মা</font>"));
} else if (chkDengersine2.isChecked() == false) {
chkDengersine2.setChecked(false);
VlblDanger2.setText("");
VlblDanger2.setText(Html.fromHtml(VlblDanger2.getText() + "প্রথম গর্ভাবস্থা বা ৩ এর অধিক সন্তান জন্ম দিয়েছেন এমন মা"));
}
}
});
if (Integer.valueOf(PGNNo1()).equals(0) || Integer.valueOf(PGNNo1()).equals(1) || Integer.valueOf(PGNNo1()) >= 3) {
chkDengersine2.setChecked(true);
chkDengersine2.setEnabled(false);
VlblDanger2.setText("");
VlblDanger2.setText(Html.fromHtml(VlblDanger2.getText() + "<font color=red>প্রথম গর্ভাবস্থা বা ৩ এর অধিক সন্তান জন্ম দিয়েছেন এমন মা</font>"));
} else {
chkDengersine2.setChecked(false);
}
//3
String AValue = String.format("Select healthId, pregNo from %s where healthId = '%s' and pregNo = '%s'", TableName, g.getGeneratedId(), pregnancyNo);
if (!C.Existence(AValue)) {
} else if (C.Existence(AValue)) {
//
String height = C.ReturnSingleValue("Select ifnull(height,'') as height from pregWomen WHERE healthId ='" + g.getGeneratedId() + "' AND pregNo ='" + pregnancyNo + "'");
if (height.equals("") | height.equals(null) || height.equals("null")) {
} else if (height != null || height.equals("null")) {
if (Integer.valueOf(height) >= 1 & Integer.valueOf(height) <= 58) {
chkDengersine3.setEnabled(false);
chkDengersine3.setChecked(true);
VlblDanger3.setText("");
VlblDanger3.setText(Html.fromHtml(VlblDanger3.getText() + "<font color=red>মায়ের উচ্চতা ১৪৫ সে মি (৪ ফুট ১০ ইঞ্চি) এর কম হলে</font>"));
} else {
}
}
} else {
}
//4
if (dtpLMP.getText().length() != 0) {
Integer DiffDNow_OC = Global.DateDifferenceDays(e.getLMP(), GetMaxOutComeDate());
if (DiffDNow_OC > 0 & DiffDNow_OC <= 730 & Integer.valueOf(pregnancyNo) > 1) {
chkDengersine4.setEnabled(false);
chkDengersine4.setChecked(true);
VlblDanger4.setText("");
VlblDanger4.setText(Html.fromHtml(VlblDanger4.getText() + "<font color=red>জন্ম বিরতি- ২ বছরের কম হলে</font>"));
} else {
}
}
chkDengersine4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (chkDengersine4.isChecked() == true) {
chkDengersine4.setChecked(true);
VlblDanger4.setText("");
VlblDanger4.setText(Html.fromHtml(VlblDanger4.getText() + "<font color=red>জন্ম বিরতি- ২ বছরের কম হলে</font>"));
} else if (chkDengersine4.isChecked() == false) {
chkDengersine4.setChecked(false);
VlblDanger4.setText("");
VlblDanger4.setText(Html.fromHtml(VlblDanger4.getText() + "জন্ম বিরতি- ২ বছরের কম হলে"));
}
}
});
//ifnull(riskHistoryNote,'') as riskHistoryNote
if (!C.Existence(AValue)) {
} else if (C.Existence(AValue)) {
//
String riskHistory = "Select ifnull(riskHistoryNote,'') as riskHistoryNote from pregWomen WHERE healthId ='" + g.getGeneratedId() + "' AND pregNo ='" + pregnancyNo + "'";
String riskStatus = C.ReturnSingleValue(riskHistory);
String[] risk = Connection.split(riskStatus, ',');
if (riskHistory.equals("") | riskHistory.equals(null)) {
} else if (riskHistory != null)
if (riskStatus.length() == 1) {
String risk1 = risk[0].toString();
if (risk1.equals("1") | risk1.equals("4")) {
chkDengersine5.setChecked(true);
VlblDanger5.setText("");
VlblDanger5.setText(Html.fromHtml(VlblDanger5.getText() + "<font color=red>পূর্ববর্তী প্রসবে প্রসবপূব রক্তক্ষরণ, প্রসবোত্তর রক্তক্ষরণ অথবা জরায়ুতে গর্ভফু্ল আঁটকে থাকার ইতিহাস থাকলে</font>"));
chkDengersine5.setEnabled(false);
}
if (risk1.equals("5") | risk1.equals("6")) {
chkDengersine6.setChecked(true);
VlblDanger6.setText("");
VlblDanger6.setText(Html.fromHtml(VlblDanger6.getText() + "<font color=red>মৃত জন্মের বা নবজাতকের মৃতের ইতিহাস থাকলে</font>"));
chkDengersine6.setEnabled(false);
}
if (risk1.equals("9")) {
chkDengersine7.setChecked(true);
VlblDanger7.setText("");
VlblDanger7.setText(Html.fromHtml(VlblDanger7.getText() + "<font color=red>সিজারিয়ান অপারেশন বা যন্ত্রের মাধ্যমে (ফরসেফ/ ভেকুয়াম) প্রসবের ইতিহাস থাকলে</font>"));
chkDengersine7.setEnabled(false);
}
} else if (riskStatus.length() == 3) {
String risk1 = risk[0].toString();
String risk2 = risk[1].toString();
if (risk1.equals("1") | risk2.equals("1") | risk1.equals("4") | risk2.equals("4")) {
chkDengersine5.setChecked(true);
VlblDanger5.setText("");
VlblDanger5.setText(Html.fromHtml(VlblDanger5.getText() + "<font color=red>পূর্ববর্তী প্রসবে প্রসবপূব রক্তক্ষরণ, প্রসবোত্তর রক্তক্ষরণ অথবা জরায়ুতে গর্ভফু্ল আঁটকে থাকার ইতিহাস থাকলে</font>"));
chkDengersine5.setEnabled(false);
}
if (risk1.equals("5") | risk2.equals("5") | risk1.equals("6") | risk2.equals("6")) {
chkDengersine6.setChecked(true);
VlblDanger6.setText("");
VlblDanger6.setText(Html.fromHtml(VlblDanger6.getText() + "<font color=red>মৃত জন্মের বা নবজাতকের মৃতের ইতিহাস থাকলে</font>"));
chkDengersine6.setEnabled(false);
}
if (risk1.equals("9") | risk2.equals("9")) {
chkDengersine7.setChecked(true);
VlblDanger7.setText("");
VlblDanger7.setText(Html.fromHtml(VlblDanger7.getText() + "<font color=red>সিজারিয়ান অপারেশন বা যন্ত্রের মাধ্যমে (ফরসেফ/ ভেকুয়াম) প্রসবের ইতিহাস থাকলে</font>"));
chkDengersine7.setEnabled(false);
}
} else if (riskStatus.length() == 5) {
String risk1 = risk[0].toString();
String risk2 = risk[1].toString();
String risk3 = risk[2].toString();
if (risk1.equals("1") | risk2.equals("1") | risk3.equals("1") | risk1.equals("4") | risk2.equals("4") | risk3.equals("4")) {
chkDengersine5.setChecked(true);
VlblDanger5.setText("");
VlblDanger5.setText(Html.fromHtml(VlblDanger5.getText() + "<font color=red>পূর্ববর্তী প্রসবে প্রসবপূব রক্তক্ষরণ, প্রসবোত্তর রক্তক্ষরণ অথবা জরায়ুতে গর্ভফু্ল আঁটকে থাকার ইতিহাস থাকলে</font>"));
chkDengersine5.setEnabled(false);
}
if (risk1.equals("5") | risk2.equals("5") | risk3.equals("5") | risk1.equals("6") | risk2.equals("6") | risk3.equals("6")) {
chkDengersine6.setChecked(true);
VlblDanger6.setText("");
VlblDanger6.setText(Html.fromHtml(VlblDanger6.getText() + "<font color=red>মৃত জন্মের বা নবজাতকের মৃতের ইতিহাস থাকলে</font>"));
chkDengersine6.setEnabled(false);
}
if (risk1.equals("9") | risk2.equals("9") | risk3.equals("9")) {
chkDengersine7.setChecked(true);
VlblDanger7.setText("");
VlblDanger7.setText(Html.fromHtml(VlblDanger7.getText() + "<font color=red>সিজারিয়ান অপারেশন বা যন্ত্রের মাধ্যমে (ফরসেফ/ ভেকুয়াম) প্রসবের ইতিহাস থাকলে</font>"));
chkDengersine7.setEnabled(false);
}
} else if (riskStatus.length() == 7) {
String risk1 = risk[0].toString();
String risk2 = risk[1].toString();
String risk3 = risk[2].toString();
String risk4 = risk[3].toString();
if (risk1.equals("1") | risk2.equals("1") | risk3.equals("1") | risk4.equals("1") | risk1.equals("4") | risk2.equals("4") | risk3.equals("4") | risk4.equals("4")) {
chkDengersine5.setChecked(true);
VlblDanger5.setText("");
VlblDanger5.setText(Html.fromHtml(VlblDanger5.getText() + "<font color=red>পূর্ববর্তী প্রসবে প্রসবপূব রক্তক্ষরণ, প্রসবোত্তর রক্তক্ষরণ অথবা জরায়ুতে গর্ভফু্ল আঁটকে থাকার ইতিহাস থাকলে</font>"));
chkDengersine5.setEnabled(false);
}
if (risk1.equals("5") | risk2.equals("5") | risk3.equals("5") | risk4.equals("5") | risk1.equals("6") | risk2.equals("6") | risk3.equals("6") | risk4.equals("6")) {
chkDengersine6.setChecked(true);
VlblDanger6.setText("");
VlblDanger6.setText(Html.fromHtml(VlblDanger6.getText() + "<font color=red>মৃত জন্মের বা নবজাতকের মৃতের ইতিহাস থাকলে</font>"));
chkDengersine6.setEnabled(false);
}
if (risk1.equals("9") | risk2.equals("9") | risk3.equals("9") | risk4.equals("9")) {
chkDengersine7.setChecked(true);
VlblDanger7.setText("");
VlblDanger7.setText(Html.fromHtml(VlblDanger7.getText() + "<font color=red>সিজারিয়ান অপারেশন বা যন্ত্রের মাধ্যমে (ফরসেফ/ ভেকুয়াম) প্রসবের ইতিহাস থাকলে</font>"));
chkDengersine7.setEnabled(false);
}
} else if (riskStatus.length() == 9) {
String risk1 = risk[0].toString();
String risk2 = risk[1].toString();
String risk3 = risk[2].toString();
String risk4 = risk[3].toString();
String risk5 = risk[4].toString();
if (risk1.equals("1") | risk2.equals("1") | risk3.equals("1") | risk4.equals("1") | risk5.equals("1") | risk1.equals("4") | risk2.equals("4") | risk3.equals("4") | risk4.equals("4") | risk5.equals("4")) {
chkDengersine5.setChecked(true);
VlblDanger5.setText("");
VlblDanger5.setText(Html.fromHtml(VlblDanger5.getText() + "<font color=red>পূর্ববর্তী প্রসবে প্রসবপূব রক্তক্ষরণ, প্রসবোত্তর রক্তক্ষরণ অথবা জরায়ুতে গর্ভফু্ল আঁটকে থাকার ইতিহাস থাকলে</font>"));
chkDengersine5.setEnabled(false);
}
if (risk1.equals("5") | risk2.equals("5") | risk3.equals("5") | risk4.equals("5") | risk5.equals("5") | risk1.equals("6") | risk2.equals("6") | risk3.equals("6") | risk4.equals("6") | risk5.equals("6")) {
chkDengersine6.setChecked(true);
VlblDanger6.setText("");
VlblDanger6.setText(Html.fromHtml(VlblDanger6.getText() + "<font color=red>মৃত জন্মের বা নবজাতকের মৃতের ইতিহাস থাকলে</font>"));
chkDengersine6.setEnabled(false);
}
if (risk1.equals("9") | risk2.equals("9") | risk3.equals("9") | risk4.equals("9") | risk5.equals("9")) {
chkDengersine7.setChecked(true);
VlblDanger7.setText("");
VlblDanger7.setText(Html.fromHtml(VlblDanger7.getText() + "<font color=red>সিজারিয়ান অপারেশন বা যন্ত্রের মাধ্যমে (ফরসেফ/ ভেকুয়াম) প্রসবের ইতিহাস থাকলে</font>"));
chkDengersine7.setEnabled(false);
}
} else if (riskStatus.length() == 11) {
String risk1 = risk[0].toString();
String risk2 = risk[1].toString();
String risk3 = risk[2].toString();
String risk4 = risk[3].toString();
String risk5 = risk[4].toString();
String risk6 = risk[5].toString();
if (risk1.equals("1") | risk2.equals("1") | risk3.equals("1") | risk4.equals("1") | risk5.equals("1") | risk6.equals("1") | risk1.equals("4") | risk2.equals("4") | risk3.equals("4") | risk4.equals("4") | risk5.equals("4") | risk6.equals("4")) {
chkDengersine5.setChecked(true);
VlblDanger5.setText("");
VlblDanger5.setText(Html.fromHtml(VlblDanger5.getText() + "<font color=red>পূর্ববর্তী প্রসবে প্রসবপূব রক্তক্ষরণ, প্রসবোত্তর রক্তক্ষরণ অথবা জরায়ুতে গর্ভফু্ল আঁটকে থাকার ইতিহাস থাকলে</font>"));
chkDengersine5.setEnabled(false);
}
if (risk1.equals("5") | risk2.equals("5") | risk3.equals("5") | risk4.equals("5") | risk5.equals("5") | risk6.equals("5") | risk1.equals("6") | risk2.equals("6") | risk3.equals("6") | risk4.equals("6") | risk5.equals("6") | risk6.equals("6"))
{
chkDengersine6.setChecked(true);
VlblDanger6.setText("");
VlblDanger6.setText(Html.fromHtml(VlblDanger6.getText() + "<font color=red>মৃত জন্মের বা নবজাতকের মৃতের ইতিহাস থাকলে</font>"));
chkDengersine6.setEnabled(false);
}
if (risk1.equals("9") | risk2.equals("9") | risk3.equals("9") | risk4.equals("9") | risk5.equals("9") | risk6.equals("9")) {
chkDengersine7.setChecked(true);
VlblDanger7.setText("");
VlblDanger7.setText(Html.fromHtml(VlblDanger7.getText() + "<font color=red>সিজারিয়ান অপারেশন বা যন্ত্রের মাধ্যমে (ফরসেফ/ ভেকুয়াম) প্রসবের ইতিহাস থাকলে</font>"));
chkDengersine7.setEnabled(false);
}
} else if (riskStatus.length() == 13) {
String risk1 = risk[0].toString();
String risk2 = risk[1].toString();
String risk3 = risk[2].toString();
String risk4 = risk[3].toString();
String risk5 = risk[4].toString();
String risk6 = risk[5].toString();
String risk7 = risk[6].toString();
if (risk1.equals("1") | risk2.equals("1") | risk3.equals("1") | risk4.equals("1") | risk5.equals("1") | risk6.equals("1") | risk7.equals("1") | risk1.equals("4") | risk2.equals("4") | risk3.equals("4") | risk4.equals("4") | risk5.equals("4") | risk6.equals("4") | risk7.equals("4")) {
chkDengersine5.setChecked(true);
VlblDanger5.setText("");
VlblDanger5.setText(Html.fromHtml(VlblDanger5.getText() + "<font color=red>পূর্ববর্তী প্রসবে প্রসবপূব রক্তক্ষরণ, প্রসবোত্তর রক্তক্ষরণ অথবা জরায়ুতে গর্ভফু্ল আঁটকে থাকার ইতিহাস থাকলে</font>"));
chkDengersine5.setEnabled(false);
}
if (risk1.equals("5") | risk2.equals("5") | risk3.equals("5") | risk4.equals("5") | risk5.equals("5") | risk6.equals("5") | risk7.equals("6") | risk1.equals("6") | risk2.equals("6") | risk3.equals("6") | risk4.equals("6") | risk5.equals("6") | risk6.equals("6") | risk7.equals("6"))
{
chkDengersine6.setChecked(true);
VlblDanger6.setText("");
VlblDanger6.setText(Html.fromHtml(VlblDanger6.getText() + "<font color=red>মৃত জন্মের বা নবজাতকের মৃতের ইতিহাস থাকলে</font>"));
chkDengersine6.setEnabled(false);
}
if (risk1.equals("9") | risk2.equals("9") | risk3.equals("9") | risk4.equals("9") | risk5.equals("9") | risk6.equals("9") | risk7.equals("9")) {
chkDengersine7.setChecked(true);
VlblDanger7.setText("");
VlblDanger7.setText(Html.fromHtml(VlblDanger7.getText() + "<font color=red>সিজারিয়ান অপারেশন বা যন্ত্রের মাধ্যমে (ফরসেফ/ ভেকুয়াম) প্রসবের ইতিহাস থাকলে</font>"));
chkDengersine7.setEnabled(false);
}
} else if (riskStatus.length() == 15) {
String risk1 = risk[0].toString();
String risk2 = risk[1].toString();
String risk3 = risk[2].toString();
String risk4 = risk[3].toString();
String risk5 = risk[4].toString();
String risk6 = risk[5].toString();
String risk7 = risk[6].toString();
String risk8 = risk[7].toString();
if (risk1.equals("1") | risk2.equals("1") | risk3.equals("1") | risk4.equals("1") | risk5.equals("1") | risk6.equals("1") | risk7.equals("1") | risk8.equals("1") | risk1.equals("4") | risk2.equals("4") | risk3.equals("4") | risk4.equals("4") | risk5.equals("4") | risk6.equals("4") | risk7.equals("4") | risk8.equals("4")) {
chkDengersine5.setChecked(true);
VlblDanger5.setText("");
VlblDanger5.setText(Html.fromHtml(VlblDanger5.getText() + "<font color=red>পূর্ববর্তী প্রসবে প্রসবপূব রক্তক্ষরণ, প্রসবোত্তর রক্তক্ষরণ অথবা জরায়ুতে গর্ভফু্ল আঁটকে থাকার ইতিহাস থাকলে</font>"));
chkDengersine5.setEnabled(false);
}
if (risk1.equals("5") | risk2.equals("5") | risk3.equals("5") | risk4.equals("5") | risk5.equals("5") | risk6.equals("5") | risk7.equals("5") | risk8.equals("5") | risk1.equals("6") | risk2.equals("6") | risk3.equals("6") | risk4.equals("6") | risk5.equals("6") | risk6.equals("6") | risk7.equals("6") | risk8.equals("6"))
{
chkDengersine6.setChecked(true);
VlblDanger6.setText("");
VlblDanger6.setText(Html.fromHtml(VlblDanger6.getText() + "<font color=red>মৃত জন্মের বা নবজাতকের মৃতের ইতিহাস থাকলে</font>"));
chkDengersine6.setEnabled(false);
}
if (risk1.equals("9") | risk2.equals("9") | risk3.equals("9") | risk4.equals("9") | risk5.equals("9") | risk6.equals("9") | risk7.equals("9") | risk8.equals("9")) {
chkDengersine7.setChecked(true);
VlblDanger7.setText("");
VlblDanger7.setText(Html.fromHtml(VlblDanger7.getText() + "<font color=red>সিজারিয়ান অপারেশন বা যন্ত্রের মাধ্যমে (ফরসেফ/ ভেকুয়াম) প্রসবের ইতিহাস থাকলে</font>"));
chkDengersine7.setEnabled(false);
}
} else if (riskStatus.length() == 17) {
String risk1 = risk[0].toString();
String risk2 = risk[1].toString();
String risk3 = risk[2].toString();
String risk4 = risk[3].toString();
String risk5 = risk[4].toString();
String risk6 = risk[5].toString();
String risk7 = risk[6].toString();
String risk8 = risk[7].toString();
String risk9 = risk[8].toString();
if (risk1.equals("1") | risk2.equals("1") | risk3.equals("1") | risk4.equals("1") | risk5.equals("1") | risk6.equals("1") | risk7.equals("1") | risk8.equals("1") | risk9.equals("1") | risk1.equals("4") | risk2.equals("4") | risk3.equals("4") | risk4.equals("4") | risk5.equals("4") | risk6.equals("4") | risk7.equals("4") | risk8.equals("4") | risk9.equals("4")) {
chkDengersine5.setChecked(true);
VlblDanger5.setText("");
VlblDanger5.setText(Html.fromHtml(VlblDanger5.getText() + "<font color=red>পূর্ববর্তী প্রসবে প্রসবপূব রক্তক্ষরণ, প্রসবোত্তর রক্তক্ষরণ অথবা জরায়ুতে গর্ভফু্ল আঁটকে থাকার ইতিহাস থাকলে</font>"));
chkDengersine5.setEnabled(false);
}
if (risk1.equals("5") | risk2.equals("5") | risk3.equals("5") | risk4.equals("5") | risk5.equals("5") | risk6.equals("5") | risk7.equals("5") | risk8.equals("5") | risk9.equals("5") | risk1.equals("6") | risk2.equals("6") | risk3.equals("6") | risk4.equals("6") | risk5.equals("6") | risk6.equals("6") | risk7.equals("6") | risk8.equals("6") | risk9.equals("6"))
{
chkDengersine6.setChecked(true);
VlblDanger6.setText("");
VlblDanger6.setText(Html.fromHtml(VlblDanger6.getText() + "<font color=red>মৃত জন্মের বা নবজাতকের মৃতের ইতিহাস থাকলে</font>"));
chkDengersine6.setEnabled(false);
}
if (risk1.equals("9") | risk2.equals("9") | risk3.equals("9") | risk4.equals("9") | risk5.equals("9") | risk6.equals("9") | risk7.equals("9") | risk8.equals("9") | risk9.equals("9")) {
chkDengersine7.setChecked(true);
VlblDanger7.setText("");
VlblDanger7.setText(Html.fromHtml(VlblDanger7.getText() + "<font color=red>সিজারিয়ান অপারেশন বা যন্ত্রের মাধ্যমে (ফরসেফ/ ভেকুয়াম) প্রসবের ইতিহাস থাকলে</font>"));
chkDengersine7.setEnabled(false);
}
} else {
}
} else {
}
//6
if (!GetStillbirthBirth().equalsIgnoreCase("null") && !GetStillbirthBirth().equalsIgnoreCase("")) {
if (Integer.valueOf(GetStillbirthBirth()) < 1) {
}
if (Integer.valueOf(GetStillbirthBirth()) >= 1) {
chkDengersine6.setChecked(true);
VlblDanger6.setText("");
VlblDanger6.setText(Html.fromHtml(VlblDanger6.getText() + "<font color=red>মৃত জন্মের বা নবজাতকের মৃতের ইতিহাস থাকলে </font>"));
}
}
if (chkDengersine1.isChecked() == true || chkDengersine2.isChecked() == true ||
chkDengersine3.isChecked() == true || chkDengersine4.isChecked() == true ||
chkDengersine5.isChecked() == true || chkDengersine6.isChecked() == true || chkDengersine7.isChecked() == true
) {
// seclblH1.(Color.RED);
chkDengersine.setChecked(true);
secReferWomen.setVisibility(View.VISIBLE);
// secReferFaci.setVisibility(View.VISIBLE);
}
if (chkDengersine1.isChecked() == false && chkDengersine2.isChecked() == false &&
chkDengersine3.isChecked() == false && chkDengersine4.isChecked() == false &&
chkDengersine5.isChecked() == false && chkDengersine6.isChecked() == false && chkDengersine7.isChecked() == false
) {
secDengersine.setVisibility(View.GONE);
secReferWomen.setVisibility(View.GONE);
secReferFaci.setVisibility(View.GONE);
chkDengersine.setChecked(false);
}
DataSerchPregRefer();
btnSaveRef.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (spnFaci.getSelectedItemPosition() == 0) {
Connection.MessageBox(PregReg.this, "কোথায় রেফার করা হয়েছে সিলেক্ট করুন।");
spnFaci.requestFocus();
return;
} else {
DataPregRefer();
Connection.MessageBox(PregReg.this, "তথ্য সফলভাবে সংরক্ষণ হয়েছে।");
//ReferStatus();
}
}
});
Button cmdSavePreg = (Button) findViewById(R.id.cmdSavePreg);
cmdSavePreg.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
DataSavePregnant();
}
});
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
PregWomenSearch();
PregWomenLastChildSearch();
} catch (Exception e) {
Connection.MessageBox(PregReg.this, e.getMessage());
return;
}
}
//Add days with system Date
public static String getCalculatedDate(String dateFormat, int days) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat s = new SimpleDateFormat(dateFormat);
cal.add(Calendar.DAY_OF_YEAR, days);
return s.format(new Date(cal.getTimeInMillis()));
}
//Add days with user given date
public static String getCalculatedDate1(String date, String dateFormat, int days) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat s = new SimpleDateFormat(dateFormat);
cal.add(Calendar.DAY_OF_YEAR, days);
try {
return s.format(new Date(s.parse(date).getTime()));
} catch (ParseException e) {
// TODO Auto-generated catch block
Log.e("TAG", "Error in Parsing Date : " + e.getMessage());
}
return null;
}
private String VisitNumber() {
String SQL = "";
SQL = "Select (ifnull(max(cast(Visit as int)),0)+1)MaxHH from ANC";
SQL += " where";
SQL += " dist='" + g.getDistrict() + "' and upz='" + g.getUpazila() + "' and un='" + g.getUnion() + "' and Mouza='" + g.getMouza() + "' and vill='" + g.getVillage() + "' and ProvType='" + g.getProvType() + "' and ProvCode='" + g.getProvCode() + "' and HHNo='" + g.getHouseholdNo() + "' and SNo='" + txtSNo.getText() + "'";
String VisitNo = Global.Right(("00" + C.ReturnSingleValue(SQL)), 2);
return VisitNo;
}
private String GetCountSLNoNumber() {
String SQL = "select ((cast(Count(*) as int))) as Totalno from PregWomen";
String Val = String.valueOf(C.ReturnSingleValue(SQL));
if (Val.equalsIgnoreCase("0")) {
return "1";
} else
return Val;
}
private String PGNNoNull() {
String SQL = "";
String PGNNo = "";
SQL = "select '0'||(ifnull(max(cast(PregNo as int)),1))MaxPGNNo from PregWomen WHERE healthId = " + g.getGeneratedId();
/*SQL += " where";
SQL += " dist='" + g.getDistrict() + "' and upz='" + g.getUpazila() + "' and un='" + g.getUnion() + "' and Mouza='" + g.getMouza() + "' and vill='" + g.getVillage() + "' and ProvType='"+ g.getProvType() +"' and ProvCode='"+ g.getProvCode() +"' and HHNo='" + g.getHouseholdNo() + "' and SNo='" + txtSNo.getText() + "'";*/
PGNNo = Global.Right(("00" + C.ReturnSingleValue(SQL)), 2);
return PGNNo;
}
private String serviceID(String pregNo) {
String SQL = "";
String PGNNo = "";
//String MaxPGNNo=PregMaxPGNNo();
SQL = "select '0'||(ifnull(max(cast(serviceId as int)),0))MaxserviceId from PregRefer WHERE healthId = " + g.getGeneratedId() + " AND pregNo = " + pregNo;
String tempserviceID = C.ReturnSingleValue(SQL);
return String.valueOf((Long.parseLong(tempserviceID) + 1));
/*if (serviceID.equalsIgnoreCase("1")) {
return String.valueOf(g.getGeneratedId() + pregNo + serviceID);
} else {
return String.valueOf(serviceID);
}*/
}
private String GetCurrentPregnancyNumber() {
String SQL = "select ifnull((select '0'||cast(max(pregNo) as string)),0) AS PregNo from PregWomen";
SQL += " Where HealthId='" + g.getGeneratedId() + "'";
String Val = String.valueOf(C.ReturnSingleValue(SQL));
if (Val.equalsIgnoreCase("")) {
return "0";
} else
return Val;
}
private String PregMaxPGNNo() {
String SQL = "";
String PGNNo = "";
SQL = "select ifnull((select '0'||cast(max(pregNo) as string)),0) AS PregNo from PregWomen WHERE healthId=" + g.getGeneratedId();
/*SQL += " where";
SQL += " dist='" + g.getDistrict() + "' and upz='" + g.getUpazila() + "' and un='" + g.getUnion() + "' and Mouza='" + g.getMouza() + "' and vill='" + g.getVillage() + "' and ProvType='"+ g.getProvType() +"' and ProvCode='"+ g.getProvCode() +"' and HHNo='" + g.getHouseholdNo() + "' and SNo='" + txtSNo.getText() + "'";*/
// PGNNo = Global.Right(("00"+ C.ReturnSingleValue(SQL)),2);
PGNNo = C.ReturnSingleValue(SQL);
return PGNNo;
}
private String PGNNo() {
String SQL = "";
String PGNNo = "";
SQL = "Select (ifnull(max(cast(PregNo as int)),0)+1)MaxPGNNo from PregWomen WHERE healthId = " + g.getGeneratedId();
/*SQL += " where";
SQL += " dist='" + g.getDistrict() + "' and upz='" + g.getUpazila() + "' and un='" + g.getUnion() + "' and Mouza='" + g.getMouza() + "' and vill='" + g.getVillage() + "' and ProvType='"+ g.getProvType() +"' and ProvCode='"+ g.getProvCode() +"' and HHNo='" + g.getHouseholdNo() + "' and SNo='" + txtSNo.getText() + "'";*/
PGNNo = Global.Right(("00" + C.ReturnSingleValue(SQL)), 2);
return PGNNo;
}
private String PGNNo1() {
String SQL = "";
String PGNNo = "";
SQL = "Select (ifnull(max(cast(pregNo as int)),0))pregNo from delivery WHERE healthId = " + g.getGeneratedId();
/*SQL += " where";
SQL += " dist='" + g.getDistrict() + "' and upz='" + g.getUpazila() + "' and un='" + g.getUnion() + "' and Mouza='" + g.getMouza() + "' and vill='" + g.getVillage() + "' and ProvType='"+ g.getProvType() +"' and ProvCode='"+ g.getProvCode() +"' and HHNo='" + g.getHouseholdNo() + "' and SNo='" + txtSNo.getText() + "'";*/
PGNNo = Global.Right(("00" + C.ReturnSingleValue(SQL)), 2);
return PGNNo;
}
private String GetStillbirthBirth() {
String SQL = "";
String SBirth = "";
SQL = String.format("Select stillbirth from delivery where healthId = '%s'", g.getGeneratedId());
SBirth = C.ReturnSingleValue(SQL);
return SBirth;
}
private String ELCOLastVisitNum() {
String SQL = "";
SQL = "Select max(Visit)MaxHH from ELCOVisit";
SQL += " where";
SQL += " dist='" + g.getDistrict() + "' and upz='" + g.getUpazila() + "' and un='" + g.getUnion() + "' and Mouza='" + g.getMouza() + "' and vill='" + g.getVillage() + "' and HHNo='" + g.getHouseholdNo() + "' and SNo='" + txtSNo.getText() + "'";
String VisitNo = Global.Right(("00" + C.ReturnSingleValue(SQL)), 2);
return VisitNo;
}
private void ClearAll() {
dtpLMP.setText("");
dtpEDD.setText("");
spnPgn.setSelection(0);
txtAgeM.setText("");
txtAgeY.setText("");
}
private void DataSavePreg() {
AlertDialog.Builder adb = new AlertDialog.Builder(PregReg.this);
adb.setTitle("Close");
adb.setMessage("তথ্য সফলভাবে সংরক্ষণ হয়েছে। আপনি কি গর্ভকালীন সেবার তথ্য সংগ্রহ করতে চান?");
//adb.setNegativeButton("No", null);
adb.setNegativeButton("না", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
Intent f2 = new Intent(getApplicationContext(), MemberList.class);
startActivity(f2);
}
});
adb.setPositiveButton("হ্যাঁ", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//setContentView(R.layout.fwareg_main);
//TabHost tabHost = getTabHost();
//((TabHost)findViewById(R.id..tabhost))
//secPregVisit.setVisibility(View.VISIBLE);
}
});
adb.show();
}
private String GetTotalSonGaughter(String HealthId) {
//String sq = String.format("Select SUM((ifnull((cast(son as int)),0)) + (ifnull((cast(dau as int)),0))) Total from elco WHERE healthId = '%s'", g.getGeneratedId());
String sq = String.format("Select (ifnull(SUM((ifnull((cast(son as int)),0)) + (ifnull((cast(dau as int)),0))),0)) Total from elco WHERE healthId = '%s'", g.getGeneratedId());
return C.ReturnSingleValue(sq);
}
private String GetDOB(String HealthId) {
String sq = String.format("Select DOB from member WHERE healthId = '%s'", g.getHealthID());
return C.ReturnSingleValue(sq);
}
private String GetMaxOutComeDate() {
String SQL = "";
String MaxOutcomeDate = "";
SQL = "Select ifnull(Max(outcomedate),0) from delivery WHERE healthId ='" + g.getGeneratedId() + "' and pregNo=(select Max(pregNo) from ancService WHERE healthId='" + g.getGeneratedId() + "')";
MaxOutcomeDate = C.ReturnSingleValue(SQL);
return MaxOutcomeDate;
}
private String GetMaxANCDate() {
String SQL = "";
String MaxANCDate = "";
SQL = "Select ifnull(Max(visitDate),0) from ancService WHERE healthId ='" + g.getGeneratedId() + "' and pregNo=(select Max(pregNo) from ancService WHERE healthId='" + g.getGeneratedId() + "')";
MaxANCDate = C.ReturnSingleValue(SQL);
return MaxANCDate;
}
/*private String GetMaxANCDate(String HealthId) {
//Select Max(visitDate) from ancService WHERE healthId='261174' and pregNo=(select Max(pregNo) from ancService WHERE healthId='261174')
String sq = String.format("Select Max(visitDate) from ancService WHERE healthId = '%s' and pregNo=(select Max(pregNo) from ancService WHERE healthId='%s')", g.getGeneratedId());
return C.ReturnSingleValue(sq);
}*/
private String GetMaxPGN() {
String SQL = "";
String MaxPGN = "";
SQL = "Select '0'||ifnull(gravida,0)gravida from PregWomen WHERE healthId ='" + g.getGeneratedId() + "' and pregNo=(select Max(pregNo) from PregWomen WHERE healthId='" + g.getGeneratedId() + "')";
MaxPGN = C.ReturnSingleValue(SQL);
return MaxPGN;
}
private void DataSerchPregRefer() {
//Ewmt
String PGNAnc = String.format("Select healthId, pregNo from %s where healthId = '%s' and pregNo = '%s'", TablePregRefer, g.getGeneratedId(), pregnancyNo);
if (C.Existence(PGNAnc)) {
rdoReferWomen1.setChecked(true);
} else {
rdoReferWomen1.setChecked(false);
}
}
private void DataPregRefer() {
//Ewmt
String SQL = "";
String PGNAnc = "select referCenter FROM PregRefer ";
PGNAnc += " WHERE healthId = '" + g.getGeneratedId() + "' AND pregNo ='" + pregnancyNo + "' and serviceId='" + VlblServiceId.getText() + "'";//visitDate='"+ Global.DateConvertYMD(dtpVDate.getText().toString()) +"'
//String PGNAnc = String.format("Select healthId, pregNo,serviceId from %s where healthId = '%s' and pregNo = '%s'",TablePregRefer,g.getGeneratedId(), pregnancyNo,VlblServiceId.getText());
try {
if (!C.Existence(PGNAnc)) {
if (rdoReferWomen1.isChecked() & secReferWomen.isShown()) {
if (spnFaci.getSelectedItemPosition() == 0) {
Connection.MessageBox(PregReg.this, "কোথায় রেফার করা হয়েছে সিলেক্ট করুন।");
spnFaci.requestFocus();
return;
}
}
String ServiceId = serviceID(pregnancyNo);
SQL = "INSERT INTO " + TablePregRefer + " (healthId,pregNo,serviceId,providerId,referCenter,systemEntryDate,upload) " +
"VALUES (" + "'" + g.getGeneratedId() + "'," + "'" + pregnancyNo + "','" + ServiceId + "'," + "'" + g.getProvCode() + "'," + "'" + Global.Left(spnFaci.getSelectedItem().toString(), 2) + "','" + Global.DateTimeNowYMDHMS() + "','2')";
C.Save(SQL);
//ReferStatus();
DisplayReferStatus();
VlblServiceId.setText("");
btnSaveRef.setText("Add");
} else {
if (rdoReferWomen1.isChecked() & secReferWomen.isShown()) {
if (spnFaci.getSelectedItemPosition() == 0) {
Connection.MessageBox(PregReg.this, "কোথায় রেফার করা হয়েছে সিলেক্ট করুন।");
spnFaci.requestFocus();
return;
}
}
SQL = "Update " + TablePregRefer + " Set ";
SQL += "referCenter = '" + Global.Left(spnFaci.getSelectedItem().toString(), 2) + "',";
SQL += "modifyDate = '" + Global.DateTimeNowYMDHMS() + "'";
SQL += "Where healthId='" + g.getGeneratedId() + "' and pregNo='" + pregnancyNo + "' and serviceId='" + VlblServiceId.getText() + "'";
C.Save(SQL);
DisplayReferStatus();
//ReferStatus();
VlblServiceId.setText("");
btnSaveRef.setText("Add");
}
} catch (Exception e) {
Connection.MessageBox(PregReg.this, e.getMessage());
return;
}
}
private void DataSavePregnant() {
try {
String dob = GetDOB(g.getHealthID());
Integer DobAge = Global.DateDifferenceYears(dtpLMP.getText().toString(), Global.DateConvertDMY(dob.toString()));
Integer DiffDNow_VD = Global.DateDifferenceDays(Global.DateNowDMY(), dtpLMP.getText().toString());
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String formattedDate = sdf.format(c.getTime());
Date date1 = sdf.parse(formattedDate);
Date date5 = sdf.parse(dtpLMP.getText().toString());
String PrevPGN = "'" + GetMaxPGN() == "0" ? "" : GetMaxPGN() + "";
if (dtpLMP.getText().toString().length() == 0) {
Connection.MessageBox(PregReg.this, "সর্বশেষ মাসিকের তারিখ কত লিখুন।");
dtpLMP.requestFocus();
return;
}/* else if (DobAge < 12) {
Connection.MessageBox(PregReg.this, "মহিলার বয়স ১২ বছরের বেশি হতে হবে ");
dtpLMP.requestFocus();
return;
} */ else if (dtpEDD.getText().toString().length() == 0) {
Connection.MessageBox(PregReg.this, "সম্ভাব্য প্রসবের তারিখ কত লিখুন।");
dtpEDD.requestFocus();
return;
} else if (spnPgn.getSelectedItemPosition() == 0 & spnPgn.isShown()) {
Connection.MessageBox(PregReg.this, "বর্তমানে কত তম গর্ভ তালিকা থেকে সিলেক্ট করুন।।");
spnPgn.requestFocus();
return;
} else if (date5.after(date1)) {
Connection.MessageBox(PregReg.this, "শেষ মাসিকের তারিখ আজকের তারিখ অপেক্ষা বড় হবে না");
dtpLMP.requestFocus();
return;
} else if (date5.equals(date1)) {
Connection.MessageBox(PregReg.this, "শেষ মাসিকের তারিখ আজকের তারিখ সমান হবে না");
dtpLMP.requestFocus();
return;
} else if (DiffDNow_VD <= 29) {
Connection.MessageBox(PregReg.this, "শেষ মাসিকের তারিখ ৩০ দিনের কম হবে না");
dtpLMP.requestFocus();
return;
}
/*else if (GetCurrentPregNoFromAncService(pregnancyNo).equals(pregnancyNo)) {
Connection.MessageBox(PregReg.this, "এ এন সি ভিজিট থাকলে গর্ভবতী মহিলার সাধারন তথ্য সম্পাদন হবে না");
//dtpLMP.requestFocus();
return;
}*/
else if (PrevPGN.equalsIgnoreCase("")) {
} else {
/*Integer PrevPGNPlus1 = Integer.parseInt(PrevPGN) + 1;
Integer ActualPrevPGN = Integer.parseInt(PrevPGN);
Integer pgnpositionselected1 = Integer.parseInt(String.valueOf(spnPgn.getSelectedItemPosition()));
if (pgnpositionselected1.equals(ActualPrevPGN)) {
Connection.MessageBox(PregReg.this, "বর্তমানে কত তম গর্ভ তথ্য সঠিক নয়।");
spnPgn.requestFocus();
return;
} else if (!PrevPGNPlus1.equals(pgnpositionselected1)) {
Connection.MessageBox(PregReg.this, "বর্তমানে কত তম গর্ভ তথ্য সঠিক নয়।");
spnPgn.requestFocus();
return;
}*/
}
/* if(!rdoDanger1.isChecked() & !rdoDanger2.isChecked() & secDengersine.isShown())
{
Connection.MessageBox(PregReg.this, "ঝুঁকিপূর্ণা সিলেক্ট করুন।");
rdoDanger1.requestFocus();
return;
}
if(!rdoReferWomen1.isChecked() & !rdoReferWomen2.isChecked() & secReferWomen.isShown())
{
Connection.MessageBox(PregReg.this, "জটিল গর্ভবতীর মাকে রেফার করা হয়েছে সিলেক্ট করুন।");
rdoReferWomen1.requestFocus();
return;
}*/
if (txtLiveSonDau.getText().toString().equalsIgnoreCase("0")) {
} else {
if (txtAgeY.getText().toString().length() == 0) {
Connection.MessageBox(PregReg.this, "শেষ সন্তানের বয়স কত বছর লিখুন");
txtAgeY.requestFocus();
return;
} else if (txtAgeM.getText().toString().length() == 0) {
Connection.MessageBox(PregReg.this, "শেষ সন্তানের বয়স কত মাস লিখুন।");
txtAgeM.requestFocus();
return;
}
/*if (txtAgeM.getText().toString().length() == 0 && txtAgeY.getText().toString().length() == 0) {
Connection.MessageBox(PregReg.this, "শেষ সন্তানের বয়স কত লিখুন।");
txtAgeM.requestFocus();
return;
}*/
}
/*else if(dtpVDate.getText().toString().length()==0)
{
Connection.MessageBox(PregReg.this,"পরিদর্শনের তারিখ কত লিখুন।");
dtpVDate.requestFocus();
return;
}
if(!rdoIron1.isChecked() & !rdoIron2.isChecked() & secIron.isShown())
{
Connection.MessageBox(PregReg.this, "আয়রন ও ফলিক এসিড পেয়েছেন কিনা সিলেক্ট করুন।");
rdoIron1.requestFocus();
return;
}
if(rdoIron1.isChecked() & secIron.isShown())
{
if(txtIronQty.getText().toString().length()==0)
{
Connection.MessageBox(PregReg.this, "আয়রন ও ফলিক এসিডের পরিমাণ কত লিখুন।");
txtIronQty.requestFocus();
return;
}
else if(spnIronUnit.getSelectedItemPosition()==0)
{
Connection.MessageBox(PregReg.this, "আয়রন ও ফলিক এসিডের ইউনিট তালিকা থেকে সিলেক্ট করুন।।");
spnIronUnit.requestFocus();
return;
}
}
if(!rdoMiso1.isChecked() & !rdoMiso2.isChecked() & secMiso.isShown())
{
Connection.MessageBox(PregReg.this, "মিসোপ্রস্টল বড়ি পেয়েছেন কিনা সিলেক্ট করুন।");
rdoMiso1.requestFocus();
return;
}
if(rdoMiso1.isChecked() & secMiso.isShown())
{
if(txtMisoQty.getText().toString().length()==0)
{
Connection.MessageBox(PregReg.this, "মিসোপ্রস্টল বড়ির পরিমাণ কত লিখুন।");
txtMisoQty.requestFocus();
return;
}
else if(spnMisoUnit.getSelectedItemPosition()==0)
{
Connection.MessageBox(PregReg.this, "মিসোপ্রস্টল বড়ির ইউনিট তালিকা থেকে সিলেক্ট করুন।।");
spnMisoUnit.requestFocus();
return;
}
}
*/
/* String SQ1 = "";
SQ1 = "select PGN from PregWomen where";
SQ1 += " Dist='"+ g.getDistrict() +"' and";
SQ1 += " Upz='"+ g.getUpazila() +"' and";
SQ1 += " UN='"+ g.getUnion() +"' and";
SQ1 += " Vill='"+ g.getVillage() +"' and";
SQ1 += " ProvType='"+ g.getProvType() +"' and";
SQ1 += " ProvCode='"+ g.getProvCode() +"' and";
SQ1 += " HHNo='"+ g.getHouseholdNo() +"' and SNo='"+ g.getSerialNo() +"'";
SQ1 += " order by RegDT desc limit 1";
String RecentPregPGN = C.ReturnSingleValue(SQ1);
String PregPGNStatus = RecentPregPGN;
String SQ2 = "";
SQ2 = "select PGN||'^'||Outcome from Deliv where";
SQ2 += " Dist='"+ g.getDistrict() +"' and";
SQ2 += " Upz='"+ g.getUpazila() +"' and";
SQ2 += " UN='"+ g.getUnion() +"' and";
SQ2 += " Vill='"+ g.getVillage() +"' and";
SQ2 += " ProvType='"+ g.getProvType() +"' and";
SQ2 += " ProvCode='"+ g.getProvCode() +"' and";
SQ2 += " HHNo='"+ g.getHouseholdNo() +"' and SNo='"+ g.getSerialNo() +"'";
SQ2 += " order by EnDt desc limit 1";*/
// String RecentDelivPGN = C.ReturnSingleValue(SQ2);
// String[] CurrStatusDelivPGN = Connection.split(RecentDelivPGN, '^');
// String DelivPGNStatus = CurrStatusDelivPGN[0].toString();
//String DelivOutcomesatus = CurrStatusDelivPGN[1].toString();
//Ewmt
String SQL = "";
String PGNNoNull = PGNNoNull();
String PGNNo = PGNNo();
String PregMaxPGNNo = PregMaxPGNNo();
// if(DelivPGNStatus.equalsIgnoreCase(""))
// {
//pgn will be increase 1
String pgnpositionselected = String.valueOf(spnPgn.getSelectedItemPosition());
// String pregNo = (spnPgn.getSelectedItemPosition()==0?"":Global.Left(spnPgn.getSelectedItem().toString(),2));
String refCenter = String.valueOf(spnFaci.getSelectedItemPosition());
String sq = String.format("Select healthId, pregNo from %s where healthId = '%s' and pregNo = '%s'", TableName, g.getGeneratedId(), pregnancyNo);
if (!C.Existence(sq)) {
/*SQL = "INSERT INTO " + TableName + " (healthId , pregNo, providerId, LMP,tempLMP, EDD, gravida, lastChildAge,StartTime, EndTime, systemEntryDate,Upload) " +
"VALUES (" + "'" + g.getGeneratedId() + "'," + "'" + pregnancyNo + "'," + "'" + g.getProvCode() + "'," + "'" + Global.DateConvertYMD(dtpLMP.getText().toString()) + "'," +
"'" + Global.DateConvertYMD(dtpLMP.getText().toString()) + "'," +
"'" + Global.DateConvertYMD(dtpEDD.getText().toString()) + "','" +
pgnpositionselected + "'," + "'" + ComputeAge(txtAgeM.getText().toString(), txtAgeY.getText().toString()) + "'," + "'" + StartTime + "'," + "'" +
g.CurrentTime24() + "'," + "'" + g.DateNowYMD() + "','2')";
C.Save(SQL);*/
SQL = "INSERT INTO " + TableName + " (healthId , pregNo, providerId, LMP,tempLMP, EDD, gravida, lastChildAge,systemEntryDate,upload) " +
"VALUES (" + "'" + g.getGeneratedId() + "'," + "'" + pregnancyNo + "'," + "'" + g.getProvCode() + "'," + "'" + Global.DateConvertYMD(dtpLMP.getText().toString()) + "'," +
"'" + Global.DateConvertYMD(dtpLMP.getText().toString()) + "'," +
"'" + Global.DateConvertYMD(dtpEDD.getText().toString()) + "','" +
pgnpositionselected + "'," + "'" + ComputeAge(txtAgeM.getText().toString(), txtAgeY.getText().toString()) + "','" + Global.DateTimeNowYMDHMS() + "','2')";
C.Save(SQL);
if (sqlnew != null & !sqlnew.equalsIgnoreCase("")) {
if (sqlnew.length() > 0) {
C.Save(sqlnew);
}
} else if (sqlnew.equalsIgnoreCase("")) {
if (!C.Existence("Select healthid from ELCO Where healthid='" + g.getGeneratedId() + "'"))// and currStatus = '"+ Global.Left(spnMethod.getSelectedItem().toString(), 2) +"'
{
String ELCOsql = "";
ELCOsql = "Insert into ELCO(healthId,providerId,regDT,systemEntryDate,upload)Values(";
ELCOsql += "'" + g.getGeneratedId() + "',";
ELCOsql += "'" + g.getProvCode() + "',";
ELCOsql += "'',";
ELCOsql += "'" + Global.DateTimeNowYMDHMS() + "',";
ELCOsql += "'2')";
C.Save(ELCOsql);
}
String ELCOupdate = "";
ELCOupdate = "Update ELCO Set hhStatus = '1',";
ELCOupdate += "haHHNo = '',";//Global.DateTimeNowYMDHMS() " + Global.DateConvertYMD(dtpOutcomeDT.getText().toString()) + "
ELCOupdate += "elcoNo = '',";
ELCOupdate += "husbandName = '',";
ELCOupdate += "husbandAge = '',";
ELCOupdate += "DOMSource = '',";
ELCOupdate += "MarrDate = '',";
ELCOupdate += "MarrAge = '',";
ELCOupdate += "Son = '',";
ELCOupdate += "Dau = '',";
ELCOupdate += "modifyDate = '" + Global.DateTimeNowYMDHMS() + "'";
ELCOupdate += " Where HealthID='" + g.getGeneratedId() + "'";
C.Save(ELCOupdate);
}
}
SQL = "Update " + TableName + " Set ";
SQL += "LMP = '" + Global.DateConvertYMD(dtpLMP.getText().toString()) + "',";
SQL += "tempLMP = '" + Global.DateConvertYMD(dtpLMP.getText().toString()) + "',";
SQL += "EDD = '" + Global.DateConvertYMD(dtpEDD.getText().toString()) + "',";
SQL += "gravida = '" + pgnpositionselected + "',";
SQL += "lastChildAge = '" + ComputeAge(txtAgeM.getText().toString(), txtAgeY.getText().toString()) + "',";
SQL += "modifyDate = '" + Global.DateTimeNowYMDHMS() + "'";
SQL += "Where healthId='" + g.getGeneratedId() + "' and pregNo='" + pregnancyNo + "'";
C.Save(SQL);
if (sqlupdate != null & !sqlupdate.equalsIgnoreCase("")) {
if (sqlupdate.length() > 0) {
C.Save(sqlupdate);
}
} else if (sqlupdate.equalsIgnoreCase("")) {
String VisitNo = VisitNumber(g.getGeneratedId());
if (!C.Existence("Select healthid from elcoVisit Where healthid='" + g.getGeneratedId() + "' and Visit='" + VisitNo + "'"))// and currStatus = '"+ Global.Left(spnMethod.getSelectedItem().toString(), 2) +"'
{
String elcoVisitsql = "";
elcoVisitsql = "Insert into elcoVisit(healthId,providerId,visit,systemEntryDate,modifyDate, pregNo)Values(";
elcoVisitsql += "'" + g.getGeneratedId() + "',";
elcoVisitsql += "'" + g.getProvCode() + "',";
elcoVisitsql += "'" + VisitNo + "',";
elcoVisitsql += "'" + Global.DateTimeNowYMDHMS() + "',";
elcoVisitsql += "'" + Global.DateTimeNowYMDHMS() + "',";
elcoVisitsql += "'" + pregnancyNo + "')";
C.Save(elcoVisitsql);
}
String elcoVisitupdate = "";
elcoVisitupdate = "Update elcoVisit Set pregNo = '" + pregnancyNo + "',";
elcoVisitupdate += "vDate = '',";//Global.DateTimeNowYMDHMS() " + Global.DateConvertYMD(dtpOutcomeDT.getText().toString()) + "
elcoVisitupdate += "visitStatus = '1',";
elcoVisitupdate += "currStatus = '12',";
elcoVisitupdate += "newOld = 'M',";
elcoVisitupdate += "mDate = '',";
elcoVisitupdate += "sSource = '',";
elcoVisitupdate += "qty = '',";
elcoVisitupdate += "unit = '',";
elcoVisitupdate += "brand = '',";
elcoVisitupdate += "referPlace = '',";
elcoVisitupdate += "validity = '',";
elcoVisitupdate += "dayMonYear = '',";
elcoVisitupdate += "mrSource = '1',";
elcoVisitupdate += "MRDate = '',";
elcoVisitupdate += "MRAge = '0',";
elcoVisitupdate += "modifyDate = '" + Global.DateTimeNowYMDHMS() + "',";
elcoVisitupdate += "syrinsQty = '',";
elcoVisitupdate += "upload = '2'";
elcoVisitupdate += " Where HealthID='" + g.getGeneratedId() + "' and Visit='" + VisitNo + "'";
C.Save(elcoVisitupdate);
}
String PGNAnc = String.format("Select healthId, pregNo from %s where healthId = '%s' and pregNo = '%s'", TablePregRefer, g.getGeneratedId(), pregnancyNo);
/// Remove nisan
/* if(rdoReferWomen1.isChecked() & secReferWomen.isShown())
{
if(!C.Existence(PGNAnc)) {
if(rdoReferWomen1.isChecked() & secReferWomen.isShown())
{
if(spnFaci.getSelectedItemPosition()==0)
{
Connection.MessageBox(PregReg.this, "কোথায় রেফার করা হয়েছে সিলেক্ট করুন।");
spnFaci.requestFocus();
return;
}
}
SQL = "INSERT INTO " + TablePregRefer + " (healthId,pregNo,providerId,referCenter,systemEntryDate,upload) " +
"VALUES (" + "'" + g.getGeneratedId() + "'," + "'" + pregnancyNo + "'," + "'" + g.getProvCode() + "'," + "'" + Global.Left(spnFaci.getSelectedItem().toString(), 2) + "','"+ Global.DateTimeNowYMDHMS() + "','2')";
C.Save(SQL);
}
if(rdoReferWomen1.isChecked() & secReferWomen.isShown())
{
if(spnFaci.getSelectedItemPosition()==0)
{
Connection.MessageBox(PregReg.this, "কোথায় রেফার করা হয়েছে সিলেক্ট করুন।");
spnFaci.requestFocus();
return;
}
}
SQL = "Update " + TablePregRefer + " Set ";
SQL += "referCenter = '" + Global.Left(spnFaci.getSelectedItem().toString(), 2) + "',";
SQL += "modifyDate = '" + Global.DateTimeNowYMDHMS() + "'";
SQL += "Where healthId='" + g.getGeneratedId() + "' and pregNo='" + pregnancyNo + "' and providerId='" + g.getProvCode() + "'";
C.Save(SQL);
}*/
if (IsUserHA()) {
g.setCallFrom("HAregis");
DataSavePreg();
} else {
g.setCallFrom("regis");
DataSavePreg();
}
} catch (Exception e) {
Connection.MessageBox(PregReg.this, e.getMessage());
return;
}
}
private String VisitNumber(String HealthID) {
String SQL = "";
SQL = "Select (ifnull(max(cast(Visit as int)),0)+1)MaxVisit from ELCOVisit";
SQL += " where healthid='" + HealthID + "'";
String VisitNo = Global.Right(("00" + C.ReturnSingleValue(SQL)), 2);
return VisitNo;
}
private void DisplayReferStatus() {
GridView gcount = (GridView) findViewById(R.id.gridRF);
g.setImuCode(String.valueOf(gcount.getCount() + 1));
ReferStatus();
}
public void ReferStatus() {
GridView g1 = (GridView) findViewById(R.id.gridRF);
g1.setAdapter(new Refer(this));
g1.setNumColumns(6);
}
public class Refer extends BaseAdapter {
private Context mContext;
String[][] vcode;
Integer totalRec;
public Refer(Context c) {
mContext = c;
}
public int getCount() {
return Integer.parseInt(C.ReturnSingleValue("Select count(*)total from PregRefer where healthid='" + g.getGeneratedId() + "' AND pregNo = '" + pregnancyNo + "'"));
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View MyView = convertView;
if (convertView == null) {
LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
MyView = li.inflate(R.layout.tt_item, null);
//String ServiceId = String.valueOf(vcode[1][position]);
String SQL = "Select (case when referCenter='01' then 'UHC' \n" +
"when referCenter='02' then 'UHFWC' \n" +
"when referCenter='03' then 'MCWC' \n" +
"when referCenter='04' then 'DH/GOB Hosp.' \n" +
"when referCenter='05' then 'NGO Clinic/Hosp.' \n" +
"when referCenter='06' then 'Private Clinic/Hosp.' \n" +
"when referCenter='77' then 'Others' \n" +
"else '' end) referCenter,serviceId from PregRefer where healthid='" + g.getGeneratedId() + "' AND pregNo = '" + pregnancyNo + "'";//order by systemEntryDate asc date(imudate) asc
try {
Cursor cur = C.ReadData(SQL);
cur.moveToFirst();
totalRec = cur.getCount();
vcode = new String[3][totalRec];
int i = 0;
while (!cur.isAfterLast()) {
vcode[0][i] = "রেফার " + String.valueOf(i + 1);//String.valueOf(cur.getString(cur.getColumnIndex("imucode")));
vcode[1][i] = cur.getString(cur.getColumnIndex("referCenter"));
vcode[2][i] = cur.getString(cur.getColumnIndex("serviceId"));
// vcode[3][i]= String.valueOf(cur.getString(cur.getColumnIndex("imucode")));
i += 1;
cur.moveToNext();
}
cur.close();
Button tv = (Button) MyView.findViewById(R.id.image_name);
tv.setTextSize(14);
if (vcode[0][position] != "") {
tv.setText(vcode[0][position] + "\n" + vcode[1][position]);
}
final Integer p = position;
tv.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String ServiceId = String.valueOf(vcode[2][position]);
Cursor cur = C.ReadData("Select (case when referCenter='01' then 'UHC' \n" +
"when referCenter='02' then 'UHFWC' \n" +
"when referCenter='03' then 'MCWC' \n" +
"when referCenter='04' then 'DH/GOB Hosp.' \n" +
"when referCenter='05' then 'NGO Clinic/Hosp.' \n" +
"when referCenter='06' then 'Private Clinic/Hosp.' \n" +
"when referCenter='77' then 'Others' \n" +
"else '' end) referCenter,serviceId from PregRefer where healthid='" + g.getGeneratedId() + "' AND pregNo = '" + pregnancyNo + "' AND serviceId = '" + ServiceId + "'");//order by systemEntryDate asc date(imudate) asc
cur.moveToFirst();
while (!cur.isAfterLast()) {
VlblServiceId.setText(ServiceId);
if (vcode[1][position].equals("UHC")) {
spnFaci.setSelection(1);
rdoReferWomen1.setChecked(true);
//rdogrpTTCard.setVisibility(View.VISIBLE);
} else if (vcode[1][position].equals("UHFWC")) {
spnFaci.setSelection(2);
rdoReferWomen1.setChecked(true);
} else if (vcode[1][position].equals("MCWC")) {
spnFaci.setSelection(3);
rdoReferWomen1.setChecked(true);
} else if (vcode[1][position].equals("DH/GOB Hosp.")) {
spnFaci.setSelection(4);
rdoReferWomen1.setChecked(true);
} else if (vcode[1][position].equals("NGO Clinic/Hosp.")) {
spnFaci.setSelection(5);
rdoReferWomen1.setChecked(true);
} else if (vcode[1][position].equals("Private Clinic/Hosp.")) {
spnFaci.setSelection(6);
rdoReferWomen1.setChecked(true);
} else if (vcode[1][position].equals("Others")) {
spnFaci.setSelection(7);
rdoReferWomen1.setChecked(true);
}
// if(vcode[1][position].length()!=0)
// {
//dtpDOTT1.setText(vcode[1][position]);
// dtpDOTT1.setVisibility(View.VISIBLE);
// btnDOTT1.setVisibility(View.VISIBLE);
// }
// else
// {
//dtpDOTT1.setText("");
//dtpDOTT1.setVisibility(View.GONE);
//btnDOTT1.setVisibility(View.GONE);
// }
//secTT1.setVisibility(View.VISIBLE);
// btnTTClose.setVisibility(View.VISIBLE);
// btnAddTT.setVisibility(View.GONE);
// btnSaveTT.setVisibility(View.VISIBLE);
//g.setImuCode(vcode[1][position]);
btnSaveRef.setText("Edit");
cur.moveToNext();
}
cur.close();
}
});
} catch (Exception ex) {
Connection.MessageBox(PregReg.this, ex.getMessage());
}
}
return MyView;
}
}
private Integer ComputeAge(String mon, String yr) {
Integer totalmonth = 0;
if (yr.length() > 0) {
if (Integer.parseInt(yr) >= 1) {
Integer yearinmonth = Integer.parseInt(yr);
totalmonth = 12 * yearinmonth;
}
if (Integer.parseInt(mon) > 0) {
totalmonth = totalmonth + Integer.parseInt(mon);
}
}
return totalmonth;
}
private void DisplayAge(String mon) {
Float totalmonth = null;
if (mon != null) {
if (mon.length() > 0) {
if (Integer.parseInt(mon) >= 1) {
Integer yearinmonth = Integer.parseInt(mon) / 12;
txtAgeY.setText(String.valueOf(yearinmonth));
txtAgeM.setText(String.valueOf(Integer.parseInt(mon) - (yearinmonth * 12)));
}
}
}
}
private void DataSearch(String healthID) {
try {
String SQL = "";
SQL = "Select SNo as SNo, ifnull(HealthID,'') as HealthID, ifnull(NameEng,'') as NameEng,";
SQL += "ifnull(Age,'') as Age";
SQL += " from Member Where HealthID='" + healthID + "'";
Cursor cur = C.ReadData(SQL);
cur.moveToFirst();
while (!cur.isAfterLast()) {
txtHealthID.setText(cur.getString(cur.getColumnIndex("HealthID")));
txtSNo.setText(cur.getString(cur.getColumnIndex("SNo")));
txtName.setText(cur.getString(cur.getColumnIndex("NameEng")));
txtAge.setText(cur.getString(cur.getColumnIndex("Age")));
cur.moveToNext();
}
cur.close();
} catch (Exception e) {
Connection.MessageBox(PregReg.this, e.getMessage());
return;
}
}
private void ELCONoSearch(String SNo) {
try {
String SQL = "";
SQL = "select E.ELCONo as ELCONo from ELCO E Where E.healthId='" + g.getGeneratedId() + "'";
Cursor cur = C.ReadData(SQL);
cur.moveToFirst();
while (!cur.isAfterLast()) {
txtELCONo.setText(cur.getString(cur.getColumnIndex("ELCONo")));
cur.moveToNext();
}
cur.close();
} catch (Exception e) {
Connection.MessageBox(PregReg.this, e.getMessage());
return;
}
}
private String GetCurrentPregNoFromAncService(String pregNo) {
String SQL = "select (ifnull(max(pregNo),0))pregno from ancService";
SQL += " Where HealthId='" + g.getGeneratedId() + "' AND pregNo = '" + pregNo + "'";
String Val = String.valueOf(C.ReturnSingleValue(SQL));
return Val;
/*String Val = String.valueOf(C.ReturnSingleValue(SQL));
if (Val.equalsIgnoreCase("")) {
return "0";
} else
return Val;*/
}
private void PregWomenSearch() {
try {
String SQL = "";
txtLiveSonDau.setText(GetTotalSonGaughter(g.getGeneratedId()));
SQL = "select referCenter from PregRefer";
SQL += " Where HealthId='" + g.getGeneratedId() + "' and pregNo = '" + pregnancyNo + "'";
Cursor cur = C.ReadData(SQL);
cur.moveToFirst();
while (!cur.isAfterLast()) {
spnFaci.setSelection(Global.SpinnerItemPosition(spnFaci, 2, cur.getString(cur.getColumnIndex("referCenter"))));
btnSaveRef.setText("Add");
// DisplayAge(cur.getString(cur.getColumnIndex("lastChildAge")));
String sq = String.format("Select healthId, pregNo from %s where healthId = '%s' and pregNo = '%s'", TableANC, g.getGeneratedId(), g.getPregNo());
if (!C.Existence(sq)) {
secPregVisit.setVisibility(View.VISIBLE);
} else {
secPregVisit.setVisibility(View.GONE);
}
cur.moveToNext();
}
cur.close();
} catch (Exception e) {
Log.e("Error from pregwoman", e.getMessage());
Connection.MessageBox(PregReg.this, e.getMessage());
return;
}
}
private void PregWomenLastChildSearch() {
try {
String SQL = "";
SQL = "select lastChildAge from pregWomen";
SQL += " Where HealthId='" + g.getGeneratedId() + "' and pregNo = '" + pregnancyNo + "'";
Cursor cur = C.ReadData(SQL);
cur.moveToFirst();
while (!cur.isAfterLast()) {
DisplayAge(cur.getString(cur.getColumnIndex("lastChildAge")));
cur.moveToNext();
}
cur.close();
} catch (Exception e) {
Log.e("Error from pregwoman", e.getMessage());
Connection.MessageBox(PregReg.this, e.getMessage());
return;
}
}
protected Dialog onCreateDialog(int id) {
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
Integer Y = g.mYear;
Integer M = g.mMonth;
Integer D = g.mDay;
switch (id) {
case DATE_DIALOG:
return new DatePickerDialog(this, mDateSetListener, Y, M - 1, D);
case TIME_DIALOG:
return new TimePickerDialog(this, timePickerListener, hour, minute, false);
}
return null;
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
mYear = year;
mMonth = monthOfYear + 1;
mDay = dayOfMonth;
EditText dtpDate;
dtpDate = (EditText) findViewById(R.id.dtpLMP);
if (VariableID.equals("btnLMP")) {
dtpDate = (EditText) findViewById(R.id.dtpLMP);
} else if (VariableID.equals("btnVDate")) {
dtpDate = (EditText) findViewById(R.id.dtpVDate);
}
dtpDate.setText(new StringBuilder()
.append(Global.Right("00" + mDay, 2)).append("/")
.append(Global.Right("00" + mMonth, 2)).append("/")
.append(mYear));
dtpEDD.setText(Global.addDays(dtpLMP.getText().toString(), 280));
//comments Integer DiffLMP_VD = Global.DateDifferenceDays(dtpVDate.getText().toString(), dtpLMP.getText().toString());
Integer DiffDNow_VD = Global.DateDifferenceDays(Global.DateNowDMY(), dtpLMP.getText().toString());
Integer DiffDNow_OC = Global.DateDifferenceDays(dtpLMP.getText().toString(), GetMaxOutComeDate());
//comments
/*if (DiffLMP_VD >= 224) {
secMiso.setVisibility(View.VISIBLE);
} else {
secMiso.setVisibility(View.GONE);
}*/
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String formattedDate = sdf.format(c.getTime());
String PrevAncVisit = "'" + GetMaxANCDate() == "0" ? "" : GetMaxANCDate() + "";// '"+ GetMaxANCDate()==0?"":GetMaxANCDate()) +"'";
//Date MaxAncVisitDate = sdf.parse(Global.DateConvertDMY(PrevAncVisit));
Date date1 = sdf.parse(formattedDate);
//comments Date date4 = sdf.parse(dtpVDate.getText().toString());
Date date5 = sdf.parse(dtpLMP.getText().toString());
//comments Date date2 = sdf.parse(dtpVDate.getText().toString());
String DOB = GetDOB(g.getGeneratedId());
Integer DobAge = Global.DateDifferenceYears(dtpLMP.getText().toString(), Global.DateConvertDMY(DOB.toString()));
//comments
/* if (date4.after(date1)) {
if (VariableID.equals("btnVDate")) {
Connection.MessageBox(PregReg.this, "ভিজিটের তারিখ আজকের তারিখ অপেক্ষা বড় হবে না");
}
//dtpVDate.setText(null);
dtpVDate.requestFocus();
} else if (date4.before(date5)) {
if (VariableID.equals("btnVDate")) {
Connection.MessageBox(PregReg.this, "ভিজিটের তারিখ শেষ মাসিকের তারিখ এবং সিস্টেমের তারিখের মধ্যে হবে");
}
//dtpVDate.setText(null);
dtpVDate.requestFocus();
} else if (DiffLMP_VD >= 300) {
if (VariableID.equals("btnVDate")) {
Connection.MessageBox(PregReg.this, "ভিজিটের তারিখ শেষ মাসিকের তারিখ থেকে ৩০০ দিনের বেশি হতে পারে না।");
}
//dtpVDate.setText(null);
dtpVDate.requestFocus();
}
if (PrevAncVisit.equalsIgnoreCase("0")) {
} else {
Date MaxAncVisitDate = sdf.parse(Global.DateConvertDMY(PrevAncVisit));
if (date4.before(MaxAncVisitDate)) {
if (VariableID.equals("btnVDate")) {
Connection.MessageBox(PregReg.this, "পূর্বের ভিজিটের তারিখ অপেক্ষা বর্তমান ভিজিট বড় হতে হবে।");
}
//dtpVDate.setText(null);
dtpVDate.requestFocus();
}
}*/
if (date5.after(date1)) {
if (VariableID.equals("btnLMP")) {
Connection.MessageBox(PregReg.this, "শেষ মাসিকের তারিখ আজকের তারিখ অপেক্ষা বড় হবে না");
}
//dtpLMP.setText(null);
dtpLMP.requestFocus();
//return;
} else if (date5.equals(date1)) {
if (VariableID.equals("btnLMP")) {
Connection.MessageBox(PregReg.this, "শেষ মাসিকের তারিখ আজকের তারিখ সমান হবে না");
}
//dtpLMP.setText(null);
dtpLMP.requestFocus();
} else if (DiffDNow_VD <= 29) {
if (VariableID.equals("btnLMP")) {
Connection.MessageBox(PregReg.this, "শেষ মাসিকের তারিখ ৩০ দিনের কম হবে না");
}
//dtpLMP.setText(null);
dtpLMP.requestFocus();
} else if (DobAge < 12) {
if (VariableID.equals("btnLMP")) {
Connection.MessageBox(PregReg.this, "মহিলার বয়স ১২ বছরের বেশি হতে হবে ");
}
//comments dtpVDate.requestFocus();
}
/* if (DiffDNow_OC<730)
{
chkDengersine4.setChecked(true);
}
else
{
}*/
} catch (ParseException ex) {
ex.printStackTrace();
}
}
};
private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) {
hour = selectedHour;
minute = selectedMinute;
EditText tpTime;
}
};
public class ExpectedANC extends BaseAdapter {
private Context mContext;
String[][] vcode;
Integer totalRec;
String ExpDate;
public ExpectedANC(Context c, String ExpAncDate) {
mContext = c;
ExpDate = ExpAncDate;
}
public int getCount() {
return Integer.parseInt("4");//C.ReturnSingleValue("Select count(*)total from Immunization where healthid='"+ g.getGeneratedId() +"'"));
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View MyView = convertView;
if (convertView == null) {
LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
MyView = li.inflate(R.layout.anc_item, null);
// String SQL = "Select imucode as imucode,imudate as imudate,imuCard as imucard from Immunization where healthid='"+ g.getGeneratedId() +"' order by cast(imudate as date) desc";
try {
//Cursor cur = C.ReadData(SQL);
// cur.moveToFirst();
totalRec = 4;//cur.getCount();
vcode = new String[4][totalRec];
int i = 0;
// while(!cur.isAfterLast())
//{
//dtpEDD.setText(Global.addDays(dtpLMP.getText().toString(), 280));
/*vcode[0][0] = "পরিদর্শন 1 " + Global.addDays(dtpLMP.getText().toString(), 120);
vcode[0][1] = "পরিদর্শন 2 " + Global.addDays(dtpLMP.getText().toString(), 180);
vcode[0][2] = "পরিদর্শন 3 " + Global.addDays(dtpLMP.getText().toString(), 240);
vcode[0][3] = "পরিদর্শন 4 " + Global.addDays(dtpLMP.getText().toString(), 270);
*/
vcode[0][0] = "পরিদর্শন 1 " + Global.addDays(dtpLMP.getText().toString(), 106) + " হতে " + Global.addDays(dtpLMP.getText().toString(), 112);
vcode[0][1] = "পরিদর্শন 2 " + Global.addDays(dtpLMP.getText().toString(), 162) + " হতে " + Global.addDays(dtpLMP.getText().toString(), 196);
vcode[0][2] = "পরিদর্শন 3 " + Global.addDays(dtpLMP.getText().toString(), 218) + " হতে " + Global.addDays(dtpLMP.getText().toString(), 224);
vcode[0][3] = "পরিদর্শন 4 " + Global.addDays(dtpLMP.getText().toString(), 246) + " হতে " + Global.addDays(dtpLMP.getText().toString(), 252);
//+ String.valueOf(cur.getString(cur.getColumnIndex("imucode")));
// vcode[1][i]= "ANC 2 - "+ Global.DateConvertYMD(dtpLMP.getText().toString());//cur.getString(cur.getColumnIndex("imudate"));
//vcode[2][i]= "ANC 3 - "+ Global.DateConvertYMD(dtpLMP.getText().toString());//cur.getString(cur.getColumnIndex("imucard"));
// vcode[3][i]= "ANC 4 - "+ Global.DateConvertYMD(dtpLMP.getText().toString());//String.valueOf(cur.getString(cur.getColumnIndex("imucode")));
i += 1;
// cur.moveToNext();
// }
//cur.close();
Button tv = (Button) MyView.findViewById(R.id.image_name);
tv.setTextSize(14);
//tv.setText(vcode[0][position] + "\n" + vcode[1][position]);
tv.setText(vcode[0][position] + "\n");
final Integer p = position;
/* tv.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// ChkTT1.setChecked(true);
if(vcode[2][position].equals("1"))
{
// rdoCardYes.setChecked(true);
}
else if(vcode[2][position].equals("2"))
{
// rdoCardNo.setChecked(true);
}
if(vcode[1][position].length()!=0)
{
// dtpDOTT1.setText(vcode[1][position]);
}
else
{
// dtpDOTT1.setText("");
}
// secTT1.setVisibility(View.VISIBLE);
// btnTTClose.setVisibility(View.VISIBLE);
// btnAddTT.setVisibility(View.GONE);
g.setImuCode(vcode[3][position]);
}
});*/
} catch (Exception ex) {
Connection.MessageBox(PregReg.this, ex.getMessage());
}
}
return MyView;
}
}
}
|
package com.robotarm.tests;
import com.robotarm.util.Helper;
import java.util.Scanner;
/**
* Created by higgsy789 on 24/03/2017.
*/
public abstract class Test {
protected static Helper h = Helper.getInstance();
protected static Scanner s = new Scanner(System.in);
}
|
package br.ufrn.raszz.persistence;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateUtil {
private static SessionFactory sessionFactory = null;
private static SessionFactory buildSessionFactory(String config){
try{
// Create ServiceRegistry from hibernate_swt.cfg.xml
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.configure("hibernate.cfg.xml").build();
// Create a metadata sources using the service registry
Metadata metadata = new MetadataSources(serviceRegistry)
.getMetadataBuilder().build();
return metadata.getSessionFactoryBuilder().build();
} catch (Exception e){
e.printStackTrace();
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSqlSessionFactory(String config){
if (sessionFactory == null)
sessionFactory = buildSessionFactory(config);
return sessionFactory;
}
public static void shutdown(){
if (sessionFactory != null) {
sessionFactory.close();
sessionFactory = null;
}
}
}
|
import org.sql2o.*;
import org.junit.*;
import static org.junit.Assert.*;
import java.util.Arrays;
public class PatientTest {
@Before
public void setUp() {
DB.sql2o = new Sql2o("jdbc:postgresql://localhost:5432/doctor_test", null, null);
}
@After
public void tearDown() {
try(Connection con = DB.sql2o.open()) {
String deleteDoctorsQuery = "DELETE FROM doctors *;";
String deletePatientsQuery = "DELETE FROM patients *;";
String deleteSpecialtiesQuery = "DELETE FROM specialties *;";
con.createQuery(deleteDoctorsQuery).executeUpdate();
con.createQuery(deletePatientsQuery).executeUpdate();
con.createQuery(deleteSpecialtiesQuery).executeUpdate();
}
}
@Test
public void patient_instantiatesCorrectly_true() {
Patient testPatient = new Patient("Bob", 1);
assertEquals(true, testPatient instanceof Patient);
}
@Test
public void getName_patientWithName_String(){
Patient myPatient = new Patient("Merry", 1);
assertEquals("Merry", myPatient.getName());
}
@Test
public void all_emptyAtFirst() {
assertEquals(Patient.all().size(), 0);
}
@Test
public void save_assignsIdToObject() {
Patient myPatient = new Patient("Merry", 1);
myPatient.save();
Patient savedPatient = Patient.all().get(0);
assertEquals(myPatient.getId(), savedPatient.getId());
}
@Test
public void find_findsPatientInDatabase_True() {
Patient myPatient = new Patient("Merry", 1);
myPatient.save();
Patient savedPatient = Patient.find(myPatient.getId());
assertTrue(myPatient.equals(savedPatient));
}
}
|
package com.travel.repositories;
import com.travel.models.Trip;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TripRepository extends JpaRepository<Trip, Long> {}
|
package chapter10.Exercise10_14;
public class TestMyDate {
public static void main(String[] args) {
MyDate dt1 = new MyDate();
MyDate dt2 = new MyDate((34355555133101L));
System.out.println(dt1.getDay() + "." + dt1.getMonth() + "." + dt1.getYear());
System.out.println(dt2.getDay() + "." + dt2.getMonth() + "." + dt2.getYear());
}
}
|
package day53_inheritance.hiding;
public class Mobile extends Phone {
String type = "Mobile phone";
/*
Method Hiding
we are hiding use()static method
*/
public static void use(){
System.out.println("Using mobile phone");
System.out.println("Thank you for helping");
int a = 5;
int b = 10;
System.out.println(a * b);
}
public void text(){
use();
System.out.println("and sending a text message");
}
@Override
public void call(){
use();
System.out.println("and calling on mobile");
}
}
|
package activities.db;
import activities.db.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class DBInteraction
{
private static final String dblogin = "root";
private static final String dbpasswd = "dat14";
Query q;
Connection con;
//Constructor that connects to the Database
public DBInteraction () throws SQLException {
String url="jdbc:mysql://localhost/B2B";
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch (java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
try {
System.out.println("Trying to connect...");
con = DriverManager.getConnection (url, dblogin, dbpasswd);
System.out.println("Connected!");
}
catch(SQLException ex) {
System.err.print("SQLException: ");
System.err.println(ex.getMessage());
}
q=new Query(con);
}
//Method to close the database Connection
public void close()throws Exception{
q.close();
con.close();
}
//Method to add a new user to the CLIENTS table
public void addusr(String NIA, String nombre, String apellidos, String mail, String password, String telephone)
throws Exception{
//String addusr="INSERT INTO USUARIOS VALUES ('"+NIA+"','"+nombre+"','"+apellidos+"','"+mail+"','"+password+"','"+false+"','"+telephone+"')";
//String addusr="INSERT INTO USUARIOS VALUES ('"+NIA+"','"+nombre+"','"+apellidos+"','"+mail+"','"+password+"','"+false+"','"+telephone+"')";
//String addusr="INSERT INTO USUARIOS (NIA, Nombre, Apellido, Mail, Password, Admin, Telephone) VALUES ('"+NIA+"','"+nombre+"','"+apellidos+"','"+mail+"','"+password+"',''"+falsee+"','"+telephone+"')";
//q.doUpdate(addusr);
String addusr="INSERT INTO USUARIOS (NIA,Nombre,Apellido,Mail,Password,Admin,Telephone) VALUES ('"+NIA+"','"+nombre+"','"+apellidos+"','"+mail+"','"+password+"',"+false+",'"+telephone+"')";
System.out.println(addusr);
q.doUpdate(addusr);
}
public void delusr(String NIA) throws Exception{
String delusr="DELETE FROM USUARIOS WHERE NIA='"+NIA+"'";
q.doUpdate(delusr);
}
//Method to add a new Box to the CLIENTS table
public void addBox( String size, String piso)
throws Exception{
String addusr="INSERT INTO BOXES (Size, Piso) VALUES ('"+size+"', '"+piso+"')";
q.doUpdate(addusr);
}
public void delBox(String id_box) throws Exception{
String delusr="DELETE FROM BOXES WHERE Id_BOX='"+id_box+"'";
q.doUpdate(delusr);
}
public void modBox(String id_box, String tamano, String piso) throws SQLException{
String update = "UPDATE BOXES SET Size='"+tamano+"', Piso= '"+piso+"' WHERE Id_BOX='"+id_box+"'";
q.doUpdate(update);
}
public void modificarReserva(String fecha, String horaInicio, String horaFin, String nBox, String idRes) throws SQLException{
String update = "UPDATE RESERVAS SET Fecha='"+fecha+"', Horario_Inicio='"+horaInicio+"', Horario_Fin='"+horaFin+"', Box_id="+nBox+" WHERE Id_Res="+idRes;
q.doUpdate(update);
}
//Method to add a new user to the CLLIENTS table
public void addReserva(String fecha, String horarioInicio, String horarioFin, String NIA, String box)
throws Exception{
String addusr="INSERT INTO RESERVAS (Fecha, Horario_Inicio, Horario_Fin, Confirmed, User_NIA, Box_id) VALUES ('"+fecha+"','"+horarioInicio+"','"+horarioFin+"',"+false+",'"+NIA+"',"+box+")";
q.doUpdate(addusr);
}
public void delReserva(String id_reserva) throws Exception{
String delReserva="DELETE FROM RESERVAS WHERE Id_Res='"+id_reserva+"'";
q.doUpdate(delReserva);
}
public ArrayList<Reserva> mostrarReserva(String NIA) throws Exception{
ArrayList<Reserva> data = new ArrayList<Reserva>();
String delReserva="SELECT * FROM RESERVAS WHERE User_NIA='"+NIA+"'";
ResultSet rs=q.doSelect(delReserva);
while(rs.next()){
String numres = rs.getString(1);
String Fecha = rs.getString(2);
String Horario_inicio = rs.getString(3);
String Horario_fin = rs.getString(4);
boolean Confirmed = rs.getBoolean(5);
String user_Nia = rs.getString(6);
String box_Id = rs.getString(7);
data.add(new Reserva(numres, Fecha, Horario_inicio,Horario_fin, Confirmed, user_Nia, box_Id));
}
return data;
}
public ArrayList<Reserva> mostrarReservas() throws Exception{
ArrayList<Reserva> data = new ArrayList<Reserva>();
String delReserva="SELECT * FROM RESERVAS";
ResultSet rs=q.doSelect(delReserva);
while(rs.next()){
String numres = rs.getString(1);
String Fecha = rs.getString(2);
String Horario_inicio = rs.getString(3);
String Horario_fin = rs.getString(4);
boolean Confirmed = rs.getBoolean(5);
String user_Nia = rs.getString(6);
String box_Id = rs.getString(7);
System.out.println("Reserva número: "+numres+" se hizo para la fecha: "+Fecha+" para la hora: "+Horario_inicio+" confirmada: "+Confirmed);
data.add(new Reserva(numres, Fecha, Horario_inicio,Horario_fin, Confirmed, user_Nia, box_Id));
}
return data;
}
public void addIncidencia(String cause, String description)
throws Exception{
String addusr="INSERT INTO INCIDENCIAS (Cause, Description) VALUES ('"+cause+"','"+description+"')";
q.doUpdate(addusr);
}
public ArrayList<Incidencias> mostrarIncidencia(String Id_res) throws Exception{
ArrayList<Incidencias> data = new ArrayList<Incidencias>();
String incidencias= "SELECT * FROM INCIDENCIAS WHERE Id_reserv ='"+Id_res+"'";
ResultSet rs=q.doSelect(incidencias);
System.out.println("las incidencias de la reserva: "+Id_res+" son:");
while(rs.next()){
String id = rs.getString(1);
String id_reserv= rs.getString(2);
String cause=rs.getString(3);
String description=rs.getString(4);
System.out.println("id: "+id+" cause: "+cause+" description"+ description);
data.add(new Incidencias(id, id_reserv,cause, description));
}
return data;
}
public ArrayList<Incidencias> mostrarIncidencias() throws Exception{
ArrayList<Incidencias> data = new ArrayList<Incidencias>();
String incidencias= "SELECT * FROM INCIDENCIAS";
ResultSet rs=q.doSelect(incidencias);
while(rs.next()){
String id = rs.getString(1);
String id_reserv= rs.getString(2);
String cause=rs.getString(3);
String description=rs.getString(4);
System.out.println("id: "+id+" cause: "+cause+" description"+ description);
data.add(new Incidencias(id, id_reserv,cause, description));
}
return data;
}
public ArrayList<Usuarios> mostrarUss() throws Exception{
ArrayList<Usuarios> data = new ArrayList<Usuarios>();
String usuarios= "SELECT * FROM USUARIOS";
ResultSet res= q.doSelect(usuarios);
while(res.next()){
String NIA = res.getString(1);
String nombre = res.getString(2);
String apellidos = res.getString(3);
String mail = res.getString(4);
String contraseña = res.getString(5);
boolean admin = res.getBoolean(6);
String telefono = res.getString(7);
System.out.println("\nNIA: "+res.getString(1)+"\nNombre: "+res.getString(2)+"\nApellidos: "+res.getString(3)+"\nMail: "+res.getString(4)+"\nContraseña: "+res.getString(5)+"\nAdministrador: "+res.getBoolean(6)+"\nTelefono: "+res.getString(7));
data.add(new Usuarios(NIA, nombre, apellidos, mail, contraseña, telefono,admin));
}
return data;
}
public ArrayList<Boxes> mostrarBox() throws Exception{
ArrayList<Boxes> data = new ArrayList<Boxes>();
String usuarios= "SELECT * FROM BOXES";
ResultSet res= q.doSelect(usuarios);
while(res.next()){
String id = res.getString(1);
String size = res.getString(2);
String piso = res.getString(3);
System.out.println("\nBox ID: "+res.getString(1)+"\nSize: "+res.getString(2));
data.add(new Boxes(id,size, piso));
}
return data;
}
public int authentication(String NIA, String pwd)throws Exception
{
String list="SELECT * FROM USUARIOS WHERE NIA='"+NIA+"'";
String password=null;
//String pass="SELECT Password FROM USUARIOS WHERE NIA='"+NIA+"'";
ResultSet rs=q.doSelect(list); //rs will contain the row with login passed as parameter
//ResultSet password=q.doSelect(pass); //rs will contain the row with login passed as parameter
//1:Admin, 2:Usuario, 3:No existe, 4:Contraseña incorrecta
if (rs.next()){ //Check if the Resultset is empty
password = rs.getString(5);
}
if (password == null){
return(3);
}
if(password.equals(pwd)){ // In case the password for this login in the table is the same as the one passed as parameter
boolean administrador = rs.getBoolean(6);
if(administrador==true)
{
return(1);
}
else
{
return(2);
}
}
else {
return(4);
}
}
public void modUser(String NIA,String nombre,String apellido, String mail,String pass,String telephone) throws Exception{
String update = "UPDATE USUARIOS SET Nombre='"+nombre+"', Apellido='"+apellido+"', Mail='"+mail+"', Password='"+pass+"',Telephone='"+telephone+"' WHERE NIA = '"+NIA+"'";
q.doUpdate(update);
//borramos los datos anteriores
//delusr(NIA_Antiguo);
//introducimos los nuevos datos del usuario
//addusr(NIA_Antiguo, Nombre, Apellido, mail, Password, Telephone);
}
public ArrayList<Boxes> findBoxes(String nPersonas, String fecha, String horarioInicio, String horarioFin)
throws Exception{
ArrayList<Boxes> data = new ArrayList<Boxes>();
System.out.println("\nLos siguientes boxes estan disponibles en la fecha y horario deseado: \n");
String boxId="SELECT B.* FROM BOXES B WHERE ((B.SIZE >= "+Integer.parseInt(nPersonas)+") AND ((B.Id_BOX=(SELECT Box_id from RESERVAS R WHERE R.Fecha = '"+fecha+"' AND R.HORARIO_Inicio >= '"+Integer.parseInt(horarioFin)+"'OR R.HORARIO_Fin <= '"+Integer.parseInt(horarioInicio)+"')) OR (0=(SELECT COUNT(0) from RESERVAS))))";
//QUERY BUENA
//SELECT B.* FROM BOXES B WHERE ((B.SIZE >= '5') AND ((B.Id_BOX=(SELECT Box_id from RESERVAS R WHERE R.Fecha = '21/04/2018' AND R.HORARIO_Inicio >= '20' OR R.HORARIO_Fin <= '17'))OR (0=(SELECT count(0) from RESERVAS))));
//BOXES LIBRES
ResultSet boxesLibres=q.doSelect(boxId);
while (boxesLibres.next()) {
String id = boxesLibres.getString(1);
String size = boxesLibres.getString(2);
String piso = boxesLibres.getString(3);
data.add(new Boxes(id,size, piso));
System.out.println("\nID: "+boxesLibres.getString(1)+"\nSize: "+boxesLibres.getString(2));
}
return data;
}
}
|
package com.example.skripsi;
import androidx.appcompat.app.AppCompatActivity;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.example.skripsi.network.ApiServices;
import com.example.skripsi.network.InitLibrary;
import com.example.skripsi.response.Distance;
import com.example.skripsi.response.LegsItem;
import com.example.skripsi.response.ResponseRoute;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.net.PlacesClient;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class hasilSistemZonasi extends AppCompatActivity {
TextView hasilNilai, alamatSiswa;
String skorJarak, nilaiBindo, nilaiBing, nilaiMate, nilaiIPA, nilaiHasil, skorJarakAkhir, hasilStr, jarakStr, LatlngTempatTinggal, sma, alamatTempatTinggal, a;
double bindo, bing, mate, ipa, nilai, nilaiJarak, hasilDoub, jarakDoub;
int size;
List<String> SMANegeri = new ArrayList<>();
List<String> hasilJarak = new ArrayList<>();
List<String> hasilAkhir = new ArrayList<>();
String[] namaSekolah = {"SMA Negeri 1 Medan", "SMA Negeri 2 Medan", "SMA Negeri 3 Medan",
"SMA Negeri 4 Medan", "SMA Negeri 5 Medan", "SMA Negeri 6 Medan",
"SMA Negeri 7 Medan", "SMA Negeri 8 Medan", "SMA Negeri 9 Medan",
"SMA Negeri 10 Medan", "SMA Negeri 11 Medan", "SMA Negeri 12 Medan",
"SMA Negeri 13 Medan", "SMA Negeri 14 Medan", "SMA Negeri 15 Medan",
"SMA Negeri 16 Medan", "SMA Negeri 17 Medan", "SMA Negeri 18 Medan",
"SMA Negeri 19 Medan", "SMA Negeri 20 Medan", "SMA Negeri 21 Medan"
};
//String[] mHasilJarak;
//String[] mhasilAkhir;
//String mHasilJarak[] = new String[21];
//String hasilAkhir[] = new String[21];
ArrayList<Zonasi> zonasiList = new ArrayList<>();
private String API_KEY = "AIzaSyBCITS4OOelRvvFGj8yQAZ0Knz6m8Mvsz8";
public static final int PICK_UP = 0;
public static final int DEST_LOC = 1;
private static int REQUEST_CODE = 0;
private ListView listView;
private ZonasiAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hasil_sistem_zonasi);
if (!Places.isInitialized()) {
Places.initialize(getApplicationContext(), API_KEY);
}
PlacesClient placesClient = Places.createClient(this);
hasilNilai = findViewById(R.id.nilaiUN);
alamatSiswa = findViewById(R.id.alamatSiswa);
ListView listView = findViewById(R.id.listview);
skorJarak = getIntent().getStringExtra("skorJarak");
nilaiBindo = getIntent().getStringExtra("nilaiBindo");
nilaiBing = getIntent().getStringExtra("nilaiBing");
nilaiMate = getIntent().getStringExtra("nilaiMate");
nilaiIPA = getIntent().getStringExtra("nilaiIPA");
LatlngTempatTinggal = getIntent().getStringExtra("LatlngTempatTinggal");
alamatTempatTinggal = getIntent().getStringExtra("alamatTempatTinggal");
alamatSiswa.setText(alamatTempatTinggal);
bindo = Double.parseDouble(nilaiBindo);
bing = Double.parseDouble(nilaiBing);
mate = Double.parseDouble(nilaiMate);
ipa = Double.parseDouble(nilaiIPA);
nilai = 0.1*(bindo+bing+mate+ipa);
nilaiHasil = Double.toString(nilai);
hasilNilai.setText(String.format("%.2f", nilai));
SMANegeri.add(new String("3.581612,98.669566"));
SMANegeri.add(new String("3.546568,98.682362"));
SMANegeri.add(new String("3.621412,98.671977"));
SMANegeri.add(new String("3.597267,98.655111"));
SMANegeri.add(new String("3.565695,98.698324"));
SMANegeri.add(new String("3.581412,98.692059"));
SMANegeri.add(new String("3.601499,98.678906"));
SMANegeri.add(new String("3.589381,98.698085"));
SMANegeri.add(new String("3.722349,98.689050"));
SMANegeri.add(new String("3.582216,98.691475"));
SMANegeri.add(new String("3.593730,98.732131"));
SMANegeri.add(new String("3.612068,98.640546"));
SMANegeri.add(new String("3.529935,98.682744"));
SMANegeri.add(new String("3.561102,98.716707"));
SMANegeri.add(new String("3.569777,98.614360"));
SMANegeri.add(new String("3.711748,98.642710"));
SMANegeri.add(new String("3.508695,98.615943"));
SMANegeri.add(new String("3.588039,98.693438"));
SMANegeri.add(new String("3.732649,98.678032"));
SMANegeri.add(new String("3.774633,98.705486"));
SMANegeri.add(new String("3.553006,98.726029"));
size = SMANegeri.size();
for (int i=0; i<namaSekolah.length; i++){
a= namaSekolah[i];
sma = SMANegeri.get(i);
ApiServices api = InitLibrary.getInstance();
// Siapkan request
Call<ResponseRoute> routeRequest = api.request_route(LatlngTempatTinggal, sma, API_KEY);
// kirim request
final int finalI = i;
routeRequest.enqueue(new Callback<ResponseRoute>() {
@Override
public void onResponse(Call<ResponseRoute> call, Response<ResponseRoute> response) {
if (response.isSuccessful()){
// tampung response ke variable
ResponseRoute dataDirection = response.body();
// mencari jarak
LegsItem dataLegs = dataDirection.getRoutes().get(0).getLegs().get(0);
Distance dataDistance = dataLegs.getDistance();
// perhitungan skor jarak
jarakStr = dataDistance.getText();
jarakDoub = dataDistance.getValue();
nilaiJarak = 60-(jarakDoub/300);
skorJarakAkhir = Double.toString(nilaiJarak);
// perhitungan skor akhir, skor UN+skor jarak
hasilDoub = nilai+nilaiJarak;
hasilStr = Double.toString(hasilDoub);
zonasiList.add(new Zonasi(a, skorJarakAkhir, hasilStr));
}
}
@Override
public void onFailure(Call<ResponseRoute> call, Throwable t) {
t.printStackTrace();
}
});
}
mAdapter = new ZonasiAdapter(this, zonasiList);
listView.setAdapter(mAdapter);
}
}
|
package com.thefuzzydragon.jen.codefellowship;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.view.RedirectView;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
@Controller
public class PostController {
@Autowired
PostRepository postRepository;
@Autowired
AppUserRepository appUserRepository;
@GetMapping("/post")
public String createNewPost(){
return "post";
}
@PostMapping("/post")
public RedirectView createPost(Principal p, String body) {
AppUser creator = appUserRepository.findByUsername(p.getName());
Post newPost = new Post(body, creator);
postRepository.save(newPost);
return new RedirectView("/myprofile");
}
@GetMapping("/feed")
public String getFeed(Principal p, Model m) {
AppUser currentUser = appUserRepository.findByUsername(p.getName());
List<AppUser> following = new ArrayList<>(currentUser.following);
m.addAttribute("following", following);
return "/feed";
}
}
|
package es.uma.sportjump.sjs.service.services.test.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import es.uma.sportjump.sjs.model.entities.Coach;
import es.uma.sportjump.sjs.model.entities.Training;
import es.uma.sportjump.sjs.service.services.TrainingService;
@Component
public class TrainingServiceTestUtil {
@Autowired
TrainingService trainingService;
public Training createTraining(int num, Coach coach) {
//Variables
String name = "Entrenamiento fuerza" + num;
String type = "Fuerza" + num;
String description = "Haremos hincapie en la fuerza de hombros" + num;
return trainingService.setNewTraining(name, type, description, null, coach);
}
public void removeTraining(Training training){
trainingService.removeTraining(training);
}
}
|
package com.example.devenc.gosolar;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class project_menu extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_project_menu);
Button button_create_project = (Button) findViewById(R.id.button_create_project);
button_create_project.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(project_menu.this, create_project.class));
}
});
}
}
|
package com.cinema_ticketing_sys.cinema.entity;
import com.cinema_ticketing_sys.movie.entity.Movie;
import javax.persistence.*;
import java.util.Set;
/**
* Created by huitianrui on 2017/5/11.
*/
@Entity
@Table(name = "cinema", schema = "cinema_ticketing_db")
public class Cinema {
private int cinemaId;
private String cinemaName;
private String address;
private String description;
private Integer rate;
private Set<Movie> movies;
public Cinema() {}
// 影院 双向一对多关联 电影
@OneToMany(cascade = CascadeType.ALL, targetEntity = Movie.class, mappedBy = "cinema")
public Set<Movie> getMovies() {
return movies;
}
public void setMovies(Set<Movie> movies) {
this.movies = movies;
}
@Id
@Column(name = "cinema_id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getCinemaId() {
return cinemaId;
}
public void setCinemaId(int cinemaId) {
this.cinemaId = cinemaId;
}
@Basic
@Column(name = "cinema_name")
public String getCinemaName() {
return cinemaName;
}
public void setCinemaName(String cinemaName) {
this.cinemaName = cinemaName;
}
@Basic
@Column(name = "address")
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Basic
@Column(name = "description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Basic
@Column(name = "rate")
public Integer getRate() {
return rate;
}
public void setRate(Integer rate) {
this.rate = rate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Cinema that = (Cinema) o;
if (cinemaId != that.cinemaId) return false;
if (cinemaName != null ? !cinemaName.equals(that.cinemaName) : that.cinemaName != null) return false;
if (address != null ? !address.equals(that.address) : that.address != null) return false;
if (description != null ? !description.equals(that.description) : that.description != null) return false;
if (rate != null ? !rate.equals(that.rate) : that.rate != null) return false;
return true;
}
@Override
public int hashCode() {
int result = cinemaId;
result = 31 * result + (cinemaName != null ? cinemaName.hashCode() : 0);
result = 31 * result + (address != null ? address.hashCode() : 0);
result = 31 * result + (description != null ? description.hashCode() : 0);
result = 31 * result + (rate != null ? rate.hashCode() : 0);
return result;
}
}
|
package exercicios;
import java.util.Scanner;
public class Exercicio3_3 {
public static void main(String[] args) {
int i, num;
Scanner in = new Scanner(System.in);
num = in.nextInt();
i = 1;
while(i <= num) {
System.out.printf("%d" , i);
i *= 2;
if (i <= num) {
System.out.printf(",");
}
}
in.close();
}
}
|
package ru.otus.l121.auth;
/*
* Created by VSkurikhin at winter 2018.
*/
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import ru.otus.l121.dataset.UserDataSet;
import ru.otus.l121.db.DBService;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class provides access to a centralized registry of the user's online
* accounts. The user enters credentials (username and password) once per
* account, granting applications access to online resources with
* "one-click" approval.
*/
public class AuthAccount {
public static final String ADMIN_NAME = "admin_username";
private static final String ADMIN_PASSWORD = "admin_password";
private Map<String, String> adminsUserPassword = new HashMap<>();
private Map<String, String> usersPassword = new HashMap<>();
private static Map<String, String> loadAdmins(DBService dbService, String fileName)
throws Exception {
URL url = Resources.getResource(fileName);
List<String> lines = Resources.readLines(url, Charsets.UTF_8);
int index = 1;
Map<String, String> result = new HashMap<>();
for (String line : lines) {
String[] variablePair = line.split("=", 2 );
if (2 == variablePair.length) {
String variableName = variablePair[0].trim();
String variableValue = variablePair[1].trim();
result.put(variableName, variableValue);
if (variableName.equals(AuthAccount.ADMIN_NAME)) {
UserDataSet adminUser = new UserDataSet(
index++, variableValue, null
);
dbService.save(adminUser);
}
}
}
return result;
}
/**
* The constructor initializes the list of admin accounts.
*
* @param admins the list of admin accounts with passwords.
*/
public AuthAccount(Map<String, String> admins) {
if (admins.containsKey(ADMIN_NAME)) {
String adminName = admins.get(ADMIN_NAME);
System.out.println("adminName = " + adminName);
if (admins.containsKey(ADMIN_PASSWORD)) {
String password = admins.get(ADMIN_PASSWORD);
System.out.println("password = " + password);
adminsUserPassword.put(adminName, password);
}
}
}
public AuthAccount(DBService dbService, String fileName) throws Exception {
this(loadAdmins(dbService, fileName));
}
/**
* The method is procedure for users authentication.
*
* @param username the name of user
* @param password the password of user
* @return true if authentication is success
*/
public boolean auth(String username, String password) {
if (usersPassword.containsKey(username)) {
return usersPassword.get(username).equals(password);
}
return adminsUserPassword.containsKey(username)
&& adminsUserPassword.get(username).equals(password);
}
/**
* The method is procedure for detecting admin accounts.
*
* @param username the name of user
* @return true if account is administrator
*/
public boolean isAdministrator(String username) {
return adminsUserPassword.containsKey(username);
}
/**
* The method adds the user to authentication map.
*
* @param user the name of user
* @param password the password of user
*/
public void put(String user, String password) {
usersPassword.put(user, password);
}
}
/* vim: syntax=java:fileencoding=utf-8:fileformat=unix:tw=78:ts=4:sw=4:sts=4:et
*/
//EOF
|
package com.junye.vo;
/**
* @author 作者 junye E-mail: 1105128664@qq.com
* @version 创建时间:2018年9月9日
* 类说明 :
*/
import java.util.Date;
public class ProductVo {
private String id;
private String name;
private Date ctime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCtime() {
return ctime;
}
public void setCtime(Date ctime) {
this.ctime = ctime;
}
}
|
package pl.coderslab.dal.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import pl.coderslab.domain.devices.DeviceDetails;
import pl.coderslab.domain.devices.OnOffDevice;
import java.util.Collection;
import java.util.List;
@Repository
@Transactional
public interface OnOffDeviceRepo extends JpaRepository<OnOffDevice, Long> {
List<OnOffDevice> findAll();
OnOffDevice findFirstById(Long id);
OnOffDevice findFirstByPin(Integer pin);
}
//markdown zapoznac //todo markdown
|
package com.example.myreadproject8.ui.activity.user;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.example.myreadproject8.AAATest.mysql.RegisterCnn;
import com.example.myreadproject8.R;
import com.example.myreadproject8.util.toast.ToastUtils;
public class RegisterActivity extends AppCompatActivity {
private EditText editTextTextEmailAddress,editTextTextPassword,editTextTextPassword2;
private String userName,password1,password2;
private CheckBox mCheckBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
init();
}
private void init(){
editTextTextEmailAddress=findViewById(R.id.editTextTextEmailAddress);
editTextTextPassword=findViewById(R.id.editTextTextPassword);
editTextTextPassword2=findViewById(R.id.editTextTextPassword2);
mCheckBox = findViewById(R.id.cb_agreement);
}
public void registerBtn(View view) {
userName=editTextTextEmailAddress.getText().toString().trim();
password1=editTextTextPassword.getText().toString().trim();
password2=editTextTextPassword2.getText().toString().trim();
//判断输入框内容
if(userName.equals("")){
ToastUtils.showWarring("请输入用户名");
return;
}else if(password1.equals("")){
ToastUtils.showWarring("请输入密码");
return;
}else if(password2.equals("")){
ToastUtils.showWarring("请再次输入密码");
return;
}else if (!(password1.equals(password2))){
ToastUtils.showWarring("两次密码不一致,请重新输入");
return;
}else if(!mCheckBox.isChecked()){
ToastUtils.showWarring("请先勾选用户协议!");
return;
}else{
//RegisterBackground register = new RegisterBackground(this);
//register.execute(userName,password1);
RegisterCnn register = new RegisterCnn(this);
register.setConnStr(getResources().getString(R.string.registerConnStr));
register.execute(userName,password1);
}
}
}
|
// **********************************************************************
// This file was generated by a TAF parser!
// TAF version 3.2.1.6 by WSRD Tencent.
// Generated from `/data/jcetool/taf//upload/geraldzhu/AppPituWnsInterface.jce'
// **********************************************************************
package PituClientInterface;
public final class stSensitivePersonDetectReq extends com.qq.taf.jce.JceStruct
{
public String raw_base64 = "";
public stSensitivePersonDetectReq()
{
}
public stSensitivePersonDetectReq(String raw_base64)
{
this.raw_base64 = raw_base64;
}
public void writeTo(com.qq.taf.jce.JceOutputStream _os)
{
_os.write(raw_base64, 0);
}
public void readFrom(com.qq.taf.jce.JceInputStream _is)
{
this.raw_base64 = _is.readString(0, true);
}
}
|
import java.util.*;
public class CountNumberOf3 {
}
|
package com.example.nata.hallimane;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Fragment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import static com.example.nata.hallimane.UrlClass.Dashboard;
import static com.example.nata.hallimane.UrlClass.num_of_persons;
import static com.example.nata.hallimane.UrlClass.num_of_rooms;
import static com.example.nata.hallimane.UrlClass.room_type_url;
public class RoomAvailabilityFragment extends DialogFragment implements AdapterView.OnItemSelectedListener,DatePickerDialog.OnDateSetListener {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
static String email="";
static String SType="",Scin="",Scout="",Srooms="",Sguests="";
static int SuccessMsgFlag = 0;
public String successText = "";
EditText Checkin, Checkout;
TextView SuccessMsg;
int month_x, year_x, day_x;
int id1 = 0, id2 = 0;
Button Check;
int mDay=6 ;//= 15;
int mMonth=10;// = 7; // August, month starts from 0
int mYear=2016;//= 1986;
String Temp;
Bundle b;
SessionManager session;
static String tempEmail;
static int SuccessMessage = 0;
String cin = "", cout = "";
ProgressDialog pDialog;
private Spinner spinnerRoomType, spinNumOfRooms, spinNumOfGuests;
// array list for spinner adapter
private ArrayList<Category> roomTypeList, roomNumList, roomGuestNum;
public static String sendType() {
return SType;
}
public static String sendCin() {
return Scin;
}
public static String sendCout() {
return Scout;
}
public static String sendRooms() {
return Srooms;
}
public static String sendGuests() {
return Sguests;
}
public static String sendMail(){
return tempEmail;
}
public RoomAvailabilityFragment() {
}
/*
public static RoomAvailabilityFragment newInstance(String param1) {
RoomAvailabilityFragment fragment = new RoomAvailabilityFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
}
}*/
/** This handles the message send from DatePickerDialogFragment on setting date */
Handler mHandler = new Handler(){
@Override
public void handleMessage(Message m){
/** Creating a bundle object to pass currently set date to the fragment */
b = m.getData();
/** Getting the day of month from bundle */
mDay = b.getInt("set_day");
/** Getting the month of year from bundle */
mMonth = b.getInt("set_month");
/** Getting the year from bundle */
mYear = b.getInt("set_year");
/** Displaying a short time message containing date set by Date picker dialog fragment */
//Toast.makeText(getActivity(), b.getString("set_date"), Toast.LENGTH_SHORT).show();
if(Temp.equals("dob")){
Checkin.setText(b.getString("set_date"));
//Scin = b.getString("set_date");
}else if(Temp.equals("dob1")){
Checkout.setText(b.getString("set_date"));
//Scout = b.getString("set_date");
}
}
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_room_availability, container, false);
session = new SessionManager(getActivity());
HashMap<String,String> user = session.getUserDetails();
tempEmail =user.get(SessionManager.KEY_EMAIL);
/*Toast.makeText(getActivity(),mParam1,Toast.LENGTH_SHORT).show();
TextView textView =(TextView)view.findViewById(R.id.SuccessText);
textView.setText(mParam1);*/
email = MainActivity.mailForward();
SuccessMsg = (TextView)view.findViewById(R.id.SuccessText);
SuccessMessage = 0;
// SuccessMsg.setText(tempEmail);
//SuccessMsg.setText(email);
spinnerRoomType = (Spinner) view.findViewById(R.id.spinRoomType);
Checkin = (EditText) view.findViewById(R.id.checkin);
Checkout = (EditText) view.findViewById(R.id.checkout);
spinNumOfRooms = (Spinner) view.findViewById(R.id.spinNumOfRooms);
spinNumOfGuests = (Spinner) view.findViewById(R.id.spinNumOfGuests);
DateFunc(Checkin,"dob");
DateFunc(Checkout,"dob1");
Check =(Button)view.findViewById(R.id.check);
Check.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String rType = spinnerRoomType.getSelectedItem().toString();
String rrequiredRooms = spinNumOfRooms.getSelectedItem().toString();
String rGuests = spinNumOfGuests.getSelectedItem().toString();
String cin = Checkin.getText().toString().trim();
String cout = Checkout.getText().toString().trim();
SType =rType;
Scin = cin;
Scout =cout;
Srooms =rrequiredRooms;
Sguests =rGuests;
successText = SuccessMsg.getText().toString().trim();
//SuccessMsg.setText(rType+" "+cin+" "+ cout+" "+rrequiredRooms +" "+ rGuests+" "+tempEmail);
if (CheckValidation()) {
if (!rType.equals("Select Room Type")){
if (!rrequiredRooms.equals("Select Num Of Rooms")){
if (!rGuests.equals("Select Num Of Guests")){
//Toast.makeText(RoomAvailability.this, rType + " " + cin + " " + cout + " " + rrequiredRooms + " " + rGuests, Toast.LENGTH_SHORT).show();
//SuccessMsg.setText(null);
CABILITY(rType,Scin,Scout,rrequiredRooms,rGuests,tempEmail);
//if (successText.equals("Rooms Are Available. Tap Here To Book"))
if (SuccessMessage==1)
SuccessMsg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//startActivity(new Intent(getActivity(), Book.class));
}
});
}else{
Toast.makeText(RoomAvailabilityFragment.this.getActivity(),"Choose The Num Of Guests Joining Us",Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(RoomAvailabilityFragment.this.getActivity(),"Choose Required Number Of Rooms",Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(RoomAvailabilityFragment.this.getActivity(),"Choose Room Type",Toast.LENGTH_SHORT).show();
}
}
}
});
//calender event
final Calendar cal = Calendar.getInstance();
year_x = cal.get(Calendar.YEAR);
month_x = cal.get(Calendar.MONTH);
day_x = cal.get(Calendar.DAY_OF_MONTH);
//calender event ends
roomTypeList = new ArrayList<Category>();
roomNumList = new ArrayList<Category>();
roomGuestNum = new ArrayList<Category>();
// spinner item select listener
spinnerRoomType.setOnItemSelectedListener(this);
spinNumOfRooms.setOnItemSelectedListener(this);
spinNumOfGuests.setOnItemSelectedListener(this);
//call for spinners
new GetRoomType().execute();
new GetNumOfRooms().execute();
new GetNumOfGuests().execute();
//call for spinners ends
return view;
}
public void DateFunc(EditText editText, final String DateOfBirth){
editText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Temp = DateOfBirth;
/** Creating a bundle object to pass currently set date to the fragment */
Bundle b = new Bundle();
/** Adding currently set day to bundle object */
b.putInt("set_day", mDay);
/** Adding currently set month to bundle object */
b.putInt("set_month", mMonth);
/** Adding currently set year to bundle object */
b.putInt("set_year", mYear);
/** Instantiating DatePickerDialogFragment */
DatePickerDialogFragment datePicker = new DatePickerDialogFragment();
datePicker.SetMhandler(mHandler);
/** Setting the bundle object on datepicker fragment */
datePicker.setArguments(b);
/** Getting fragment manger for this activity */
FragmentManager fm = getFragmentManager();
/** Starting a fragment transaction */
FragmentTransaction ft = fm.beginTransaction();
/** Adding the fragment object to the fragment transaction */
ft.add(datePicker, "date_picker");
/** Opening the DatePicker fragment */
ft.commit();
}
});
}
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
/**
* Adding spinner data
*/
private void populateSpinner() {
List<String> lablestype = new ArrayList<String>();
for (int i = 0; i < roomTypeList.size(); i++) {
lablestype.add(roomTypeList.get(i).getName().toString().toUpperCase());
//Toast.makeText(RoomAvailability.this,"ondu",Toast.LENGTH_SHORT).show();
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdaptertype = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, lablestype);
// Drop down layout style - list view with radio button
spinnerAdaptertype.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerRoomType.setAdapter(spinnerAdaptertype);
}
private void populateSpinner1() {
List<String> lablesroom = new ArrayList<String>();
for (int i = 0; i < roomNumList.size(); i++) {
lablesroom.add(roomNumList.get(i).getName());
// Toast.makeText(RoomAvailability.this,i,Toast.LENGTH_SHORT).show();
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapterroom = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, lablesroom);
// Drop down layout style - list view with radio button
spinnerAdapterroom.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinNumOfRooms.setAdapter(spinnerAdapterroom);
}
private void populateSpinner2() {
List<String> lablesguest = new ArrayList<String>();
for (int i = 0; i < roomGuestNum.size(); i++) {
lablesguest.add(roomGuestNum.get(i).getName());
// Toast.makeText(RoomAvailability.this,i,Toast.LENGTH_SHORT).show();
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapterroom = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_item, lablesguest);
// Drop down layout style - list view with radio button
spinnerAdapterroom.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinNumOfGuests.setAdapter(spinnerAdapterroom);
}
public boolean CheckValidation() {
boolean ret = true;
if (!Validation.hasText(Checkin)) ret=false;
if (!Validation.hasText(Checkout)) ret=false;
return ret;
}
public void CABILITY(String type,String cin,String cout,String nRooms,String nGuests,String Mail){
class CheckAvailability extends AsyncTask<String,Void,String> {
AlertDialog alertDialog;
private Dialog loadingDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(RoomAvailabilityFragment.this.getActivity(),"Please wait","Fetching Data");
alertDialog = new AlertDialog.Builder(RoomAvailabilityFragment.this.getActivity()).create();
}
@Override
protected String doInBackground(String... params) {
String rtype = params[0];
String rcin = params[1];
String rcout = params[2];
String rrooms = params[3];
String rguests = params[4];
String remail = params[5];
try{
URL url =new URL(Dashboard);
HttpURLConnection httpURLConnection =(HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream =httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter =new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String Room_Availability_data = URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(remail,"UTF-8")+"&"+
URLEncoder.encode("type","UTF-8")+"="+URLEncoder.encode(rtype,"UTF-8")+"&"+
URLEncoder.encode("from","UTF-8")+"="+URLEncoder.encode(rcin,"UTF-8")+"&"+
URLEncoder.encode("to","UTF-8")+"="+URLEncoder.encode(rcout,"UTF-8")+"&"+
URLEncoder.encode("room","UTF-8")+"="+URLEncoder.encode(rrooms,"UTF-8")+"&"+
URLEncoder.encode("person","UTF-8")+"="+URLEncoder.encode(rguests,"UTF-8");
bufferedWriter.write(Room_Availability_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader =new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String response = "";
String line ="";
while ((line=bufferedReader.readLine())!=null){
response = line;
}
inputStream.close();
bufferedReader.close();
return response;
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
alertDialog.setTitle("Room Availability");
alertDialog.setCanceledOnTouchOutside(true);
loadingDialog.dismiss();
if (result.equals("success")){
SuccessMsg.setEnabled(true);
SuccessMsg.setText(" "+"Rooms Are Available. Tap Here To Book");
Toast.makeText(getActivity(),"Rooms Are Available",Toast.LENGTH_SHORT).show();
BookFragment bookFragment = new BookFragment();
FragmentManager manager = getFragmentManager();
manager.beginTransaction().replace(R.id.content_doddudu,bookFragment,bookFragment.getTag()).commit();
//startActivity(new Intent(getActivity(),Book.class));
SuccessMessage = 1;
}else{
successText = "";
alertDialog.setMessage(result);
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Okay", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
alertDialog.show();
SuccessMessage=0;
}
}
}
CheckAvailability checkAvailability = new CheckAvailability();
checkAvailability.execute(type,cin,cout,nRooms,nGuests,Mail);
}
@Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
}
/**
* Async task to get all room types
*/
private class GetRoomType extends AsyncTask<Void, Void, Void> {
private Dialog loadingDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(RoomAvailabilityFragment.this.getActivity(),"Please Wait ","Fetching data...");
/* pDialog = new ProgressDialog(RoomAvailability.this);
pDialog.setMessage("Fetching Data Please Wait..");
pDialog.setCancelable(false);
pDialog.show();
pDialog.dismiss();*/
}
@Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(room_type_url, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray roomType = jsonObj.getJSONArray("results");
for (int i = 0; i < roomType.length(); i++) {
JSONObject rTypeObj = (JSONObject) roomType.get(i);
Category rcat1 = new Category(rTypeObj.getInt("id"), rTypeObj.getString("type"));
roomTypeList.add(rcat1);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//if (pDialog.isShowing())
// pDialog.dismiss();
populateSpinner();
loadingDialog.dismiss();
}
}
private class GetNumOfRooms extends AsyncTask<Void, Void, Void> {
private Dialog loadingDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(RoomAvailabilityFragment.this.getActivity(),"Please wait","Fetching data...");
/* pDialog = new ProgressDialog(RoomAvailability.this);
pDialog.setMessage("Fetching Data Please Wait..");
pDialog.setCancelable(false);
pDialog.show();*/
}
@Override
protected Void doInBackground(Void... params) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(num_of_rooms, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray numOfRooms = jsonObj.getJSONArray("rooms");
for (int i = 0; i < numOfRooms.length(); i++) {
JSONObject rNum = (JSONObject) numOfRooms.get(i);
Category rcat2 = new Category(rNum.getInt("id"), rNum.getString("roomNum"));
roomNumList.add(rcat2);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
populateSpinner1();
loadingDialog.dismiss();
}
}
private class GetNumOfGuests extends AsyncTask<Void, Void, Void> {
private Dialog loadDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
loadDialog =ProgressDialog.show(RoomAvailabilityFragment.this.getActivity(),"Please wait"," Fetching data...");
}
@Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(num_of_persons, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray roomGuest = jsonObj.getJSONArray("persons");
for (int i = 0; i < roomGuest.length(); i++) {
JSONObject rGuestObj = (JSONObject) roomGuest.get(i);
Category rcat3 = new Category(rGuestObj.getInt("id"), rGuestObj.getString("nPersons"));
roomGuestNum.add(rcat3);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
populateSpinner2();
loadDialog.dismiss();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.