text stringlengths 10 2.72M |
|---|
package com.mycompany.time_table_management_system.db.model;
// Generated Aug 2, 2015 2:18:56 PM by Hibernate Tools 3.6.0
import java.math.BigDecimal;
/**
* Equipment generated by hbm2java
*/
public class Equipment implements java.io.Serializable {
private EquipmentId id;
private Department department;
private String discription;
private BigDecimal equipmentValue;
private String equipmentType;
public Equipment() {
}
public Equipment(EquipmentId id, Department department) {
this.id = id;
this.department = department;
}
public Equipment(EquipmentId id, Department department, String discription, BigDecimal equipmentValue, String equipmentType) {
this.id = id;
this.department = department;
this.discription = discription;
this.equipmentValue = equipmentValue;
this.equipmentType = equipmentType;
}
public EquipmentId getId() {
return this.id;
}
public void setId(EquipmentId id) {
this.id = id;
}
public Department getDepartment() {
return this.department;
}
public void setDepartment(Department department) {
this.department = department;
}
public String getDiscription() {
return this.discription;
}
public void setDiscription(String discription) {
this.discription = discription;
}
public BigDecimal getEquipmentValue() {
return this.equipmentValue;
}
public void setEquipmentValue(BigDecimal equipmentValue) {
this.equipmentValue = equipmentValue;
}
public String getEquipmentType() {
return this.equipmentType;
}
public void setEquipmentType(String equipmentType) {
this.equipmentType = equipmentType;
}
}
|
package com.zundrel.ollivanders.client.render;
import com.mojang.blaze3d.platform.GLX;
import com.mojang.blaze3d.platform.GlStateManager;
import com.zundrel.ollivanders.common.entity.EntitySpellProjectile;
import net.minecraft.client.render.BufferBuilder;
import net.minecraft.client.render.GuiLighting;
import net.minecraft.client.render.Tessellator;
import net.minecraft.client.render.VertexFormats;
import net.minecraft.client.render.entity.EntityRenderDispatcher;
import net.minecraft.client.render.entity.EntityRenderer;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.MathHelper;
public class RenderSpellProjectile extends EntityRenderer<EntitySpellProjectile> {
private static final Identifier EXPERIENCE_ORB_TEXTURES = new Identifier("textures/entity/experience_orb.png");
public RenderSpellProjectile(EntityRenderDispatcher renderManagerIn) {
super(renderManagerIn);
this.field_4673 = 0.15F;
this.field_4672 = 0.75F;
}
/**
* Renders the desired {@code T} type Entity.
*/
public void doRender(EntitySpellProjectile entity, double x, double y, double z, float entityYaw, float partialTicks) {
if(!this.renderOutlines && entity.getSpell() != null) {
GlStateManager.pushMatrix();
GlStateManager.translatef((float) x, (float) y, (float) z);
this.bindEntityTexture(entity);
GuiLighting.enable();
int i = 10;
float f = (float) (i % 4 * 16) / 64.0F;
float f1 = (float) (i % 4 * 16 + 16) / 64.0F;
float f2 = (float) (i / 4 * 16) / 64.0F;
float f3 = (float) (i / 4 * 16 + 16) / 64.0F;
int j = entity.getLightmapCoordinates();
int k = j % 65536;
int l = j / 65536;
GLX.glMultiTexCoord2f(GLX.GL_TEXTURE1, (float) k, (float) l);
GlStateManager.color4f(1.0F, 1.0F, 1.0F, 1.0F);
float f9 = ((float) entity.getSpell().getColor()) / 2.0F;
l = (int) ((MathHelper.sin(f9 + 1) + 1.0F) * 255);
int j1 = 0xFFFFFF;//(int) ((MathHelper.sin(f9 + 4.1887903F) + 1.0F) * 255.0F);
GlStateManager.translatef(0.0F, 0.1F, 0.0F);
GlStateManager.rotatef(180.0F - this.renderManager.cameraPitch, 0.0F, 1.0F, 0.0F);
GlStateManager.rotatef((float) (this.renderManager.gameOptions != null && this.renderManager.gameOptions.perspective == 2 ? -1 : 1) * -this.renderManager.cameraYaw, 1.0F, 0.0F, 0.0F);
GlStateManager.scalef(0.3F, 0.3F, 0.3F);
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder vertexbuffer = tessellator.getBufferBuilder();
vertexbuffer.begin(7, VertexFormats.POSITION_UV_COLOR_NORMAL);
vertexbuffer.vertex(-1, -1, 0.0D).texture((double) f, (double) f3).color(l, 255, j1, 128).normal(0.0F, 1.0F, 0.0F).end();
vertexbuffer.vertex(1, -1, 0.0D).texture((double) f1, (double) f3).color(l, 255, j1, 128).normal(0.0F, 1.0F, 0.0F).end();
vertexbuffer.vertex(1, 1, 0.0D).texture((double) f1, (double) f2).color(l, 255, j1, 128).normal(0.0F, 1.0F, 0.0F).end();
vertexbuffer.vertex(-1, 1, 0.0D).texture((double) f, (double) f2).color(l, 255, j1, 128).normal(0.0F, 1.0F, 0.0F).end();
tessellator.draw();
GlStateManager.disableBlend();
GlStateManager.disableRescaleNormal();
GlStateManager.popMatrix();
}
}
@Override
protected Identifier getTexture(EntitySpellProjectile entitySpellProjectile) {
return EXPERIENCE_ORB_TEXTURES;
}
} |
package helloworldmvc.model;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Model implements IModel{
public String getMessage() {
File f = new File(Model.class.getResource("./message.txt").getFile());
FileReader fr;
String line;
String res = "";
try {
fr = new FileReader(f);
BufferedReader b = new BufferedReader(fr);
while((line = b.readLine()) != null) {
res += line;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
}
|
package com.lenovohit.hwe.treat.service.impl;
import java.util.Map;
import com.lenovohit.hwe.treat.dto.GenericRestDto;
import com.lenovohit.hwe.treat.model.Hospital;
import com.lenovohit.hwe.treat.service.HisHospitalService;
import com.lenovohit.hwe.treat.transfer.RestEntityResponse;
/**
*
* @author xiaweiyi
*/
public class HisHospitalRestServiceImpl implements HisHospitalService {
GenericRestDto<Hospital> dto;
public HisHospitalRestServiceImpl(final GenericRestDto<Hospital> dto) {
super();
this.dto = dto;
}
@Override
public RestEntityResponse<Hospital> getInfo(Hospital hospital, Map<String, ?> variables) {
return dto.getForEntity("hcp/app/base/hospital/get", null, variables);
}
}
|
/**
*/
package iso20022.impl;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EObjectWithInverseResolvingEList;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.util.InternalEList;
import iso20022.BusinessRole;
import iso20022.BusinessTransaction;
import iso20022.Iso20022Package;
import iso20022.MultiplicityEntity;
import iso20022.Participant;
import iso20022.Receive;
import iso20022.Send;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Participant</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link iso20022.impl.ParticipantImpl#getMaxOccurs <em>Max Occurs</em>}</li>
* <li>{@link iso20022.impl.ParticipantImpl#getMinOccurs <em>Min Occurs</em>}</li>
* <li>{@link iso20022.impl.ParticipantImpl#getBusinessTransaction <em>Business Transaction</em>}</li>
* <li>{@link iso20022.impl.ParticipantImpl#getReceives <em>Receives</em>}</li>
* <li>{@link iso20022.impl.ParticipantImpl#getSends <em>Sends</em>}</li>
* <li>{@link iso20022.impl.ParticipantImpl#getBusinessRoleTrace <em>Business Role Trace</em>}</li>
* </ul>
*
* @generated
*/
public class ParticipantImpl extends RepositoryConceptImpl implements Participant {
/**
* The default value of the '{@link #getMaxOccurs() <em>Max Occurs</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMaxOccurs()
* @generated
* @ordered
*/
protected static final Integer MAX_OCCURS_EDEFAULT = null;
/**
* The cached value of the '{@link #getMaxOccurs() <em>Max Occurs</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMaxOccurs()
* @generated
* @ordered
*/
protected Integer maxOccurs = MAX_OCCURS_EDEFAULT;
/**
* The default value of the '{@link #getMinOccurs() <em>Min Occurs</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMinOccurs()
* @generated
* @ordered
*/
protected static final Integer MIN_OCCURS_EDEFAULT = new Integer(0);
/**
* The cached value of the '{@link #getMinOccurs() <em>Min Occurs</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMinOccurs()
* @generated
* @ordered
*/
protected Integer minOccurs = MIN_OCCURS_EDEFAULT;
/**
* The cached value of the '{@link #getReceives() <em>Receives</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getReceives()
* @generated
* @ordered
*/
protected EList<Receive> receives;
/**
* The cached value of the '{@link #getSends() <em>Sends</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getSends()
* @generated
* @ordered
*/
protected EList<Send> sends;
/**
* The cached value of the '{@link #getBusinessRoleTrace() <em>Business Role Trace</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getBusinessRoleTrace()
* @generated
* @ordered
*/
protected BusinessRole businessRoleTrace;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ParticipantImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Iso20022Package.eINSTANCE.getParticipant();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Integer getMaxOccurs() {
return maxOccurs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setMaxOccurs(Integer newMaxOccurs) {
Integer oldMaxOccurs = maxOccurs;
maxOccurs = newMaxOccurs;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Iso20022Package.PARTICIPANT__MAX_OCCURS, oldMaxOccurs, maxOccurs));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Integer getMinOccurs() {
return minOccurs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setMinOccurs(Integer newMinOccurs) {
Integer oldMinOccurs = minOccurs;
minOccurs = newMinOccurs;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Iso20022Package.PARTICIPANT__MIN_OCCURS, oldMinOccurs, minOccurs));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BusinessTransaction getBusinessTransaction() {
if (eContainerFeatureID() != Iso20022Package.PARTICIPANT__BUSINESS_TRANSACTION) return null;
return (BusinessTransaction)eInternalContainer();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetBusinessTransaction(BusinessTransaction newBusinessTransaction, NotificationChain msgs) {
msgs = eBasicSetContainer((InternalEObject)newBusinessTransaction, Iso20022Package.PARTICIPANT__BUSINESS_TRANSACTION, msgs);
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setBusinessTransaction(BusinessTransaction newBusinessTransaction) {
if (newBusinessTransaction != eInternalContainer() || (eContainerFeatureID() != Iso20022Package.PARTICIPANT__BUSINESS_TRANSACTION && newBusinessTransaction != null)) {
if (EcoreUtil.isAncestor(this, newBusinessTransaction))
throw new IllegalArgumentException("Recursive containment not allowed for " + toString());
NotificationChain msgs = null;
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
if (newBusinessTransaction != null)
msgs = ((InternalEObject)newBusinessTransaction).eInverseAdd(this, Iso20022Package.BUSINESS_TRANSACTION__PARTICIPANT, BusinessTransaction.class, msgs);
msgs = basicSetBusinessTransaction(newBusinessTransaction, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Iso20022Package.PARTICIPANT__BUSINESS_TRANSACTION, newBusinessTransaction, newBusinessTransaction));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Receive> getReceives() {
if (receives == null) {
receives = new EObjectWithInverseResolvingEList<Receive>(Receive.class, this, Iso20022Package.PARTICIPANT__RECEIVES, Iso20022Package.RECEIVE__RECEIVER);
}
return receives;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<Send> getSends() {
if (sends == null) {
sends = new EObjectWithInverseResolvingEList<Send>(Send.class, this, Iso20022Package.PARTICIPANT__SENDS, Iso20022Package.SEND__SENDER);
}
return sends;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BusinessRole getBusinessRoleTrace() {
if (businessRoleTrace != null && businessRoleTrace.eIsProxy()) {
InternalEObject oldBusinessRoleTrace = (InternalEObject)businessRoleTrace;
businessRoleTrace = (BusinessRole)eResolveProxy(oldBusinessRoleTrace);
if (businessRoleTrace != oldBusinessRoleTrace) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, Iso20022Package.PARTICIPANT__BUSINESS_ROLE_TRACE, oldBusinessRoleTrace, businessRoleTrace));
}
}
return businessRoleTrace;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BusinessRole basicGetBusinessRoleTrace() {
return businessRoleTrace;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetBusinessRoleTrace(BusinessRole newBusinessRoleTrace, NotificationChain msgs) {
BusinessRole oldBusinessRoleTrace = businessRoleTrace;
businessRoleTrace = newBusinessRoleTrace;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, Iso20022Package.PARTICIPANT__BUSINESS_ROLE_TRACE, oldBusinessRoleTrace, newBusinessRoleTrace);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setBusinessRoleTrace(BusinessRole newBusinessRoleTrace) {
if (newBusinessRoleTrace != businessRoleTrace) {
NotificationChain msgs = null;
if (businessRoleTrace != null)
msgs = ((InternalEObject)businessRoleTrace).eInverseRemove(this, Iso20022Package.BUSINESS_ROLE__BUSINESS_ROLE_TRACE, BusinessRole.class, msgs);
if (newBusinessRoleTrace != null)
msgs = ((InternalEObject)newBusinessRoleTrace).eInverseAdd(this, Iso20022Package.BUSINESS_ROLE__BUSINESS_ROLE_TRACE, BusinessRole.class, msgs);
msgs = basicSetBusinessRoleTrace(newBusinessRoleTrace, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Iso20022Package.PARTICIPANT__BUSINESS_ROLE_TRACE, newBusinessRoleTrace, newBusinessRoleTrace));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Iso20022Package.PARTICIPANT__BUSINESS_TRANSACTION:
if (eInternalContainer() != null)
msgs = eBasicRemoveFromContainer(msgs);
return basicSetBusinessTransaction((BusinessTransaction)otherEnd, msgs);
case Iso20022Package.PARTICIPANT__RECEIVES:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getReceives()).basicAdd(otherEnd, msgs);
case Iso20022Package.PARTICIPANT__SENDS:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getSends()).basicAdd(otherEnd, msgs);
case Iso20022Package.PARTICIPANT__BUSINESS_ROLE_TRACE:
if (businessRoleTrace != null)
msgs = ((InternalEObject)businessRoleTrace).eInverseRemove(this, Iso20022Package.BUSINESS_ROLE__BUSINESS_ROLE_TRACE, BusinessRole.class, msgs);
return basicSetBusinessRoleTrace((BusinessRole)otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Iso20022Package.PARTICIPANT__BUSINESS_TRANSACTION:
return basicSetBusinessTransaction(null, msgs);
case Iso20022Package.PARTICIPANT__RECEIVES:
return ((InternalEList<?>)getReceives()).basicRemove(otherEnd, msgs);
case Iso20022Package.PARTICIPANT__SENDS:
return ((InternalEList<?>)getSends()).basicRemove(otherEnd, msgs);
case Iso20022Package.PARTICIPANT__BUSINESS_ROLE_TRACE:
return basicSetBusinessRoleTrace(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eBasicRemoveFromContainerFeature(NotificationChain msgs) {
switch (eContainerFeatureID()) {
case Iso20022Package.PARTICIPANT__BUSINESS_TRANSACTION:
return eInternalContainer().eInverseRemove(this, Iso20022Package.BUSINESS_TRANSACTION__PARTICIPANT, BusinessTransaction.class, msgs);
}
return super.eBasicRemoveFromContainerFeature(msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Iso20022Package.PARTICIPANT__MAX_OCCURS:
return getMaxOccurs();
case Iso20022Package.PARTICIPANT__MIN_OCCURS:
return getMinOccurs();
case Iso20022Package.PARTICIPANT__BUSINESS_TRANSACTION:
return getBusinessTransaction();
case Iso20022Package.PARTICIPANT__RECEIVES:
return getReceives();
case Iso20022Package.PARTICIPANT__SENDS:
return getSends();
case Iso20022Package.PARTICIPANT__BUSINESS_ROLE_TRACE:
if (resolve) return getBusinessRoleTrace();
return basicGetBusinessRoleTrace();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Iso20022Package.PARTICIPANT__MAX_OCCURS:
setMaxOccurs((Integer)newValue);
return;
case Iso20022Package.PARTICIPANT__MIN_OCCURS:
setMinOccurs((Integer)newValue);
return;
case Iso20022Package.PARTICIPANT__BUSINESS_TRANSACTION:
setBusinessTransaction((BusinessTransaction)newValue);
return;
case Iso20022Package.PARTICIPANT__RECEIVES:
getReceives().clear();
getReceives().addAll((Collection<? extends Receive>)newValue);
return;
case Iso20022Package.PARTICIPANT__SENDS:
getSends().clear();
getSends().addAll((Collection<? extends Send>)newValue);
return;
case Iso20022Package.PARTICIPANT__BUSINESS_ROLE_TRACE:
setBusinessRoleTrace((BusinessRole)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Iso20022Package.PARTICIPANT__MAX_OCCURS:
setMaxOccurs(MAX_OCCURS_EDEFAULT);
return;
case Iso20022Package.PARTICIPANT__MIN_OCCURS:
setMinOccurs(MIN_OCCURS_EDEFAULT);
return;
case Iso20022Package.PARTICIPANT__BUSINESS_TRANSACTION:
setBusinessTransaction((BusinessTransaction)null);
return;
case Iso20022Package.PARTICIPANT__RECEIVES:
getReceives().clear();
return;
case Iso20022Package.PARTICIPANT__SENDS:
getSends().clear();
return;
case Iso20022Package.PARTICIPANT__BUSINESS_ROLE_TRACE:
setBusinessRoleTrace((BusinessRole)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Iso20022Package.PARTICIPANT__MAX_OCCURS:
return MAX_OCCURS_EDEFAULT == null ? maxOccurs != null : !MAX_OCCURS_EDEFAULT.equals(maxOccurs);
case Iso20022Package.PARTICIPANT__MIN_OCCURS:
return MIN_OCCURS_EDEFAULT == null ? minOccurs != null : !MIN_OCCURS_EDEFAULT.equals(minOccurs);
case Iso20022Package.PARTICIPANT__BUSINESS_TRANSACTION:
return getBusinessTransaction() != null;
case Iso20022Package.PARTICIPANT__RECEIVES:
return receives != null && !receives.isEmpty();
case Iso20022Package.PARTICIPANT__SENDS:
return sends != null && !sends.isEmpty();
case Iso20022Package.PARTICIPANT__BUSINESS_ROLE_TRACE:
return businessRoleTrace != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public int eBaseStructuralFeatureID(int derivedFeatureID, Class<?> baseClass) {
if (baseClass == MultiplicityEntity.class) {
switch (derivedFeatureID) {
case Iso20022Package.PARTICIPANT__MAX_OCCURS: return Iso20022Package.MULTIPLICITY_ENTITY__MAX_OCCURS;
case Iso20022Package.PARTICIPANT__MIN_OCCURS: return Iso20022Package.MULTIPLICITY_ENTITY__MIN_OCCURS;
default: return -1;
}
}
return super.eBaseStructuralFeatureID(derivedFeatureID, baseClass);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public int eDerivedStructuralFeatureID(int baseFeatureID, Class<?> baseClass) {
if (baseClass == MultiplicityEntity.class) {
switch (baseFeatureID) {
case Iso20022Package.MULTIPLICITY_ENTITY__MAX_OCCURS: return Iso20022Package.PARTICIPANT__MAX_OCCURS;
case Iso20022Package.MULTIPLICITY_ENTITY__MIN_OCCURS: return Iso20022Package.PARTICIPANT__MIN_OCCURS;
default: return -1;
}
}
return super.eDerivedStructuralFeatureID(baseFeatureID, baseClass);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (maxOccurs: ");
result.append(maxOccurs);
result.append(", minOccurs: ");
result.append(minOccurs);
result.append(')');
return result.toString();
}
} //ParticipantImpl
|
package com.git.cloud.rest.api;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.git.cloud.common.exception.RollbackableBizException;
import com.git.cloud.foundation.common.WebApplicationManager;
import com.git.cloud.handler.common.CommonUtil;
import com.git.cloud.parame.service.ParameterService;
import com.git.cloud.request.model.SrTypeMarkEnum;
import com.git.cloud.request.model.vo.BmSrVo;
import com.git.cloud.request.service.IRequestWorkflowService;
import com.git.cloud.rest.model.ReturnMeta;
import com.git.cloud.rest.model.ServiceRequestParam;
import com.git.cloud.rest.service.impl.ServiceRequestImpl;
@Controller
@RequestMapping("/v1/cloudImplement")
public class ServiceRequestApi {
private static String SUCCESS="0000";
private static String FAIL = "9999";
static Logger logger = LoggerFactory.getLogger(ServiceRequestApi.class);
@RequestMapping(method = RequestMethod.POST, value = "/createMainWorkflowInstance", produces= MediaType.APPLICATION_JSON)
@ResponseBody
public Map<String, ReturnMeta> createWorkflowInstance(HttpServletRequest request) {
Map<String ,ReturnMeta> resultMap = new HashMap<String, ReturnMeta> ();
logger.info("创建主流程实例接口开始");
ReturnMeta result = new ReturnMeta();
result.setCode(SUCCESS);
String instanceId = "";
ServiceRequestImpl resourseService = (ServiceRequestImpl)WebApplicationManager.getBean("serviceRequestImpl");
try {
JSONObject serviceRequestParam = this.thansToJsonData(request);
Object srId = serviceRequestParam.get("srId");
Object srCode = serviceRequestParam.get("srCode");
Object srTypeMark = serviceRequestParam.get("srTypeMark");
if(!CommonUtil.isEmpty(srId) && !CommonUtil.isEmpty(srCode) && !CommonUtil.isEmpty(srTypeMark)) {
// 创建主流程实例
instanceId = resourseService.createMainInstance(srId.toString(), srCode.toString(),srTypeMark.toString());
}else {
result.setCode(FAIL);
result.setMessage("创建主流程传递参数有误,srId:["+ srId +"],srCode:"+"["+ srCode +"],srTypeMark:"+"["+ srTypeMark +"]");
logger.error("创建主流程传递参数有误,srId:["+ srId +"],srCode:"+"["+ srCode +"],srTypeMark:"+"["+ srTypeMark +"]");
}
if(instanceId != null && instanceId != "") {
// 启动主流程实例
resourseService.startMainInstance(srId.toString(), instanceId);;
result.setInstanceId(instanceId);
}else {
result.setCode(FAIL);
result.setMessage("启动主流程实例");
logger.error("启动主流程实例");
}
} catch (Exception e) {
result.setCode(FAIL);
result.setMessage(e.getMessage());
logger.error("创建主流程实例失败");
}
logger.info("创建主流程实例接口结束");
resultMap.put("meta", result);
return resultMap;
}
/**
* 驱动流程
* @param request
* @return
*/
@RequestMapping(method = RequestMethod.POST, value = "/driveWorkflow", produces= MediaType.APPLICATION_JSON)
@ResponseBody
public Map<String, ReturnMeta> driveWorkflow(HttpServletRequest request) {
Map<String ,ReturnMeta> resultMap = new HashMap<String, ReturnMeta> ();
logger.info("驱动流程接口开始");
ReturnMeta result = new ReturnMeta();
result.setCode(SUCCESS);
ServiceRequestImpl resourseService = (ServiceRequestImpl)WebApplicationManager.getBean("serviceRequestImpl");
try {
JSONObject serviceRequestParam = this.thansToJsonData(request);
Object todoId = serviceRequestParam.get("todoId");
Object driveWfType = serviceRequestParam.get("driveWfType");
if(!CommonUtil.isEmpty(todoId) && !CommonUtil.isEmpty(driveWfType)) {
resourseService.startDriveWorkflow(todoId.toString(), driveWfType.toString());
}else {
result.setCode(FAIL);
result.setMessage("驱动流程传递参数有误,todoId:["+ todoId +"],driveWfType:"+"["+ driveWfType +"]");
logger.error("驱动流程传递参数有误,todoId:["+ todoId +"],driveWfType:"+"["+ driveWfType +"]");
}
} catch (Exception e) {
result.setCode(FAIL);
result.setMessage(e.getMessage());
logger.error("驱动流程失败",e);
}
logger.info("驱动流程接口结束");
resultMap.put("meta", result);
return resultMap;
}
@RequestMapping(method = RequestMethod.POST, value = "/resourceAssign", produces= MediaType.APPLICATION_JSON)
@ResponseBody
public Map<String, ReturnMeta> resourceAssign(HttpServletRequest request) {
Map<String ,ReturnMeta> resultMap = new HashMap<String, ReturnMeta> ();
logger.info("[ServiceRequestApi]供给分配资源接口开始");
ReturnMeta result = new ReturnMeta();
result.setCode(SUCCESS);
ServiceRequestImpl resourseService = (ServiceRequestImpl)WebApplicationManager.getBean("serviceRequestImpl");
try {
JSONObject serviceRequestParam = this.thansToJsonData(request);
String srId = serviceRequestParam.getString("srId");
if(!CommonUtil.isEmpty(srId) ) {
String msg = resourseService.startResourceAssign(srId);
result.setMessage(msg);
}else {
result.setCode(FAIL);
result.setMessage("创建主流程传递参数有误,srId:["+ srId +"]");
logger.error("创建主流程传递参数有误,srId:["+ srId +"]");
}
} catch (Exception e) {
result.setCode(FAIL);
result.setMessage(e.getMessage());
logger.error("创建主流程实例失败");
}
logger.info("[ServiceRequestApi]供给分配资源接口结束");
resultMap.put("meta", result);
return resultMap;
}
@RequestMapping(method = RequestMethod.POST, value = "/supply", produces= MediaType.APPLICATION_JSON )
@ResponseBody
public Map<String,ReturnMeta> supply(HttpServletRequest request){
Map<String,ReturnMeta> map = new HashMap<String,ReturnMeta>();
logger.info("供给调用web接口开始");
ReturnMeta result = new ReturnMeta();
BmSrVo bmSr = null;
String instanceId = "";
result.setCode(SUCCESS);
JSONObject serviceRequestParam = null;
try {
serviceRequestParam = this.thansToJsonData(request);
ServiceRequestImpl resourseService = (ServiceRequestImpl)WebApplicationManager.getBean("serviceRequestImpl");
bmSr = resourseService.startService(serviceRequestParam.getString("operModelType"), serviceRequestParam);
if(bmSr != null ){
instanceId = resourseService.createMainInstance(bmSr);
if(instanceId != null && !instanceId.equals("")){
resourseService.startMainInstance(instanceId);
result.setSrCode(bmSr.getSrCode());
result.setInstanceId(instanceId);
}else{
logger.error("启动审批流程失败");
result.setCode(FAIL);
throw new RollbackableBizException("启动审批流程失败");
}
}else{
logger.error("初始化供给信息失败,请检查参数信息");
result.setCode(FAIL);
throw new RollbackableBizException("初始化供给信息失败,请检查参数信息");
}
} catch (IOException e) {
result.setCode(FAIL);
result.setMessage(e.getMessage());
} catch (InterruptedException e) {
result.setCode(FAIL);
result.setMessage(e.getMessage());
} catch (RollbackableBizException e) {
result.setCode(FAIL);
result.setMessage(e.getMessage());
} catch (Exception e) {
result.setCode(FAIL);
result.setMessage(e.getMessage());
}
logger.info("供给调用web接口结束");
map.put("meta", result);
return map;
}
@RequestMapping(method = RequestMethod.POST, value = "/alteration", produces= MediaType.APPLICATION_JSON)
@ResponseBody
public Map<String,ReturnMeta> alteration(HttpServletRequest request) {
Map<String,ReturnMeta> map = new HashMap<String,ReturnMeta>();
logger.info("扩容调用web接口开始");
ReturnMeta result = new ReturnMeta();
result.setCode(SUCCESS);
BmSrVo bmSr = null;
String instanceId = "";
JSONObject serviceRequestParam = null;
try {
serviceRequestParam = this.thansToJsonData(request);
ServiceRequestImpl resourseService = (ServiceRequestImpl)WebApplicationManager.getBean("serviceRequestImpl");
bmSr = resourseService.startService("VE", serviceRequestParam);
if(bmSr != null ){
instanceId = resourseService.createMainInstance(bmSr);
if(instanceId != null && !instanceId.equals("")){
resourseService.startMainInstance(instanceId);
result.setSrCode(bmSr.getSrCode());
result.setInstanceId(instanceId);
}
}else{
logger.error("初始化扩容信息失败,请检查参数信息");
result.setCode(FAIL);
throw new RollbackableBizException("初始化扩容信息失败,请检查参数信息");
}
} catch (IOException e) {
result.setCode(FAIL);
result.setMessage(e.getMessage());
} catch (InterruptedException e) {
result.setCode(FAIL);
result.setMessage(e.getMessage());
} catch (RollbackableBizException e) {
result.setCode(FAIL);
result.setMessage(e.getMessage());
} catch (Exception e) {
result.setCode(FAIL);
result.setMessage(e.getMessage());
}
logger.info("扩容调用web接口结束");
map.put("meta", result);
return map;
}
@RequestMapping(method = RequestMethod.POST, value = "/recycle", produces= MediaType.APPLICATION_JSON)
@ResponseBody
public Map<String,ReturnMeta> recycle(HttpServletRequest request){
Map<String,ReturnMeta> map = new HashMap<String,ReturnMeta>();
logger.info("回收调用web接口开始");
ReturnMeta result = new ReturnMeta();
result.setCode(SUCCESS);
BmSrVo bmSr = null;
String instanceId = "";
JSONObject serviceRequestParam = null;
try {
serviceRequestParam = this.thansToJsonData(request);
ServiceRequestImpl resourseService = (ServiceRequestImpl)WebApplicationManager.getBean("serviceRequestImpl");
bmSr = resourseService.startService(SrTypeMarkEnum.VIRTUAL_RECYCLE.getValue(), serviceRequestParam);
if(bmSr != null ){
instanceId = resourseService.createMainInstance(bmSr);
if(instanceId != null && !instanceId.equals("")){
resourseService.startMainInstance(instanceId);
result.setSrCode(bmSr.getSrCode());
result.setInstanceId(instanceId);
}else{
logger.error("启动审批流程失败");
result.setCode(FAIL);
throw new RollbackableBizException("启动审批流程失败");
}
}else{
logger.error("初始化回收信息失败,请检查参数信息");
result.setCode(FAIL);
throw new RollbackableBizException("初始化回收信息失败,请检查参数信息");
}
logger.info("回收流程结束");
}catch (IOException e) {
result.setCode(FAIL);
result.setMessage(e.getMessage());
} catch (InterruptedException e) {
result.setCode(FAIL);
result.setMessage(e.getMessage());
} catch (RollbackableBizException e) {
result.setCode(FAIL);
result.setMessage(e.getMessage());
} catch (Exception e) {
result.setCode(FAIL);
result.setMessage(e.getMessage());
}
logger.info("回收调用web接口结束");
map.put("meta", result);
return map;
}
@RequestMapping(method = RequestMethod.POST, value = "/addNetworkCard", produces= MediaType.APPLICATION_JSON )
@ResponseBody
public Map<String,ReturnMeta> addNetworkCard(HttpServletRequest request){
Map<String,ReturnMeta> map = new HashMap<String,ReturnMeta>();
logger.info("添加网卡,调用addNetworkCard开始...");
ReturnMeta result = new ReturnMeta();
ServiceRequestParam serviceRequestParam = null;
try {
serviceRequestParam = this.thansToJsonData(request).toJavaObject(ServiceRequestParam.class);
ServiceRequestImpl resourseService = (ServiceRequestImpl)WebApplicationManager.getBean("serviceRequestImpl");
result = resourseService.startServiceAuto("ADD_NETWORKCARD",serviceRequestParam);
} catch (RollbackableBizException e) {
result.setCode(FAIL);
result.setMessage(e.getMessage());
} catch (Exception e) {
result.setCode(FAIL);
result.setMessage(e.getMessage());
}
logger.info("添加网卡,调用addNetworkCard结束...");
map.put("meta", result);
return map;
}
@RequestMapping(method = RequestMethod.POST, value = "/deleteNetworkCard", produces= MediaType.APPLICATION_JSON )
@ResponseBody
public Map<String,ReturnMeta> deleteNetworkCard(HttpServletRequest request){
Map<String,ReturnMeta> map = new HashMap<String,ReturnMeta>();
logger.info("删除网卡,调用addNetworkCard开始...");
ReturnMeta result = new ReturnMeta();
ServiceRequestParam serviceRequestParam = null;
try {
serviceRequestParam = this.thansToJsonData(request).toJavaObject(ServiceRequestParam.class);
ServiceRequestImpl resourseService = (ServiceRequestImpl)WebApplicationManager.getBean("serviceRequestImpl");
result = resourseService.startServiceAuto("DELETE_NETWORKCARD",serviceRequestParam);
} catch (RollbackableBizException e) {
result.setCode(FAIL);
result.setMessage(e.getMessage());
} catch (Exception e) {
result.setCode(FAIL);
result.setMessage(e.getMessage());
}
logger.info("删除网卡,调用deleteNetworkCard结束...");
map.put("meta", result);
return map;
}
@RequestMapping(method = RequestMethod.POST, value = "/addVolume", produces= MediaType.APPLICATION_JSON )
@ResponseBody
public Map<String,ReturnMeta> addVolume(HttpServletRequest request){
Map<String,ReturnMeta> map = new HashMap<String,ReturnMeta>();
logger.info("添加卷,调用addVolume开始...");
ReturnMeta result = new ReturnMeta();
result.setCode(SUCCESS);
BmSrVo bmSr = null;
String instanceId = "";
JSONObject serviceRequestParam = null;
try {
serviceRequestParam = this.thansToJsonData(request);
ServiceRequestImpl resourseService = (ServiceRequestImpl)WebApplicationManager.getBean("serviceRequestImpl");
bmSr = resourseService.startService(SrTypeMarkEnum.SERVICE_AUTO.getValue(),serviceRequestParam);
if(bmSr != null ){
instanceId = resourseService.createMainInstance(bmSr);
if(instanceId != null && !instanceId.equals("")){
resourseService.startMainInstance(instanceId);
result.setSrCode(bmSr.getSrCode());
result.setInstanceId(instanceId);
}else{
logger.error("启动审批流程失败");
result.setCode(FAIL);
throw new RollbackableBizException("启动审批流程失败");
}
}else{
logger.error("请检查参数信息");
result.setCode(FAIL);
throw new RollbackableBizException("请检查参数信息");
}
} catch (RollbackableBizException e) {
result.setCode(FAIL);
result.setMessage(e.getMessage());
} catch (Exception e) {
result.setCode(FAIL);
result.setMessage(e.getMessage());
}
logger.info("添加卷,调用addVolume结束...");
map.put("meta", result);
return map;
}
private JSONObject thansToJsonData(HttpServletRequest request) throws Exception {
StringBuilder buffer = new StringBuilder();
request.setCharacterEncoding("UTF-8");
BufferedReader reader = null;
JSONObject serviceRequestParam = null;
try {
reader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
String line = null;
boolean flag = false;
while ((line = reader.readLine()) != null) {
buffer.append(line);
flag = true;
}
if (flag) {
logger.info("传递的参数信息:"+JSONObject.parse(buffer.toString()));
serviceRequestParam = JSONObject.parseObject(buffer.toString());
}
} catch (Exception e) {
throw new Exception("参数转换有误",e);
}
return serviceRequestParam;
}
//定价审批接口
@RequestMapping(method = RequestMethod.POST, value = "/pricingApproval", produces= MediaType.APPLICATION_JSON )
@ResponseBody
public Map<String,ReturnMeta> pricingApproval(HttpServletRequest request){
Map<String,ReturnMeta> map = new HashMap<String,ReturnMeta>();
logger.debug("定价审批调用接口开始...");
ReturnMeta result = new ReturnMeta();
result.setCode(SUCCESS);
BmSrVo bmSr = null;
String instanceId = "";
JSONObject serviceRequestParam = null;
try {
serviceRequestParam = this.thansToJsonData(request);
ServiceRequestImpl resourseService = (ServiceRequestImpl)WebApplicationManager.getBean("serviceRequestImpl");
bmSr = resourseService.startService(SrTypeMarkEnum.PRICE_EXAMINE_APPROVE.getValue(),serviceRequestParam);
if(bmSr != null ){
instanceId = resourseService.createMainInstance(bmSr);
if(instanceId != null && !instanceId.equals("")){
resourseService.startMainInstance(instanceId);
result.setSrCode(bmSr.getSrCode());
result.setInstanceId(instanceId);
}else{
logger.error("启动审批流程失败");
result.setCode(FAIL);
throw new RollbackableBizException("启动审批流程失败");
}
}else{
logger.error("请检查参数信息");
result.setCode(FAIL);
throw new RollbackableBizException("请检查参数信息");
}
} catch (RollbackableBizException e) {
result.setCode(FAIL);
result.setMessage(e.getMessage());
} catch (Exception e) {
result.setCode(FAIL);
result.setMessage(e.getMessage());
}
logger.debug("定价审批调用接口结束...");
map.put("meta", result);
return map;
}
public ParameterService paraServiceImpl() throws Exception {
return (ParameterService) WebApplicationManager.getBean("parameterServiceImpl");
}
}
|
package com.phoosop.gateway.exception;
import com.phoosop.gateway.model.Response;
import com.phoosop.gateway.model.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.*;
import reactor.core.publisher.Mono;
import static com.phoosop.gateway.exception.StatusConstants.HttpConstants;
@Component
@Order(-2)
public class CustomErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler {
private final Logger LOG = LoggerFactory.getLogger(CustomErrorWebExceptionHandler.class);
public CustomErrorWebExceptionHandler(ErrorAttributes errorAttributes, ApplicationContext applicationContext, ServerCodecConfigurer serverCodecConfigurer) {
super(errorAttributes, new WebProperties.Resources(), applicationContext);
super.setMessageWriters(serverCodecConfigurer.getWriters());
super.setMessageReaders(serverCodecConfigurer.getReaders());
}
@Override
protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
}
@Override
protected void logError(ServerRequest request, ServerResponse response, Throwable throwable) {
}
private Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
Throwable throwable = getError(request);
if (throwable instanceof ServiceException exception) {
LOG.error("Failed {} {}: {}, {}", request.methodName(), request.uri().getPath(), exception.getStatus().getCode(), exception.getStatus().getDesc());
return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR)
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(new Response<>(new Status(exception.getStatus()), null)));
} else {
return this.internalServerError(request, throwable);
}
}
private Mono<ServerResponse> internalServerError(ServerRequest request, Throwable error) {
LOG.error("Failed {} {}: {}", request.methodName(), request.uri().getPath(), error.getMessage());
return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR)
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(new Response<>(new Status(HttpConstants.INTERNAL_SERVER_ERROR), null)));
}
}
|
package com.design.patterns.structurals.bridge;
//Primer nivel de jerarquia con implementacion del tipo de mensaje
// Note que es una implementacion concreta
public class TextMessage extends Message {
public TextMessage(MessageSender messageSender) {
super(messageSender);
}
@Override
public void send() {
messageSender.sendMessage();
}
}
|
package randomforest;
public class Test {
// This test deserializes the forest and tests the remaining 20% test
// records
public static void main(String args[]) {
RFBuilder rfBuilder = new RFBuilder(1000);
// rfBuilder.readFile("test.csv");
rfBuilder.readFromDatabase();
rfBuilder.deserializeForest();
System.out.println("Accuracy of 100 trees: " + (1 - rfBuilder.test(rfBuilder.getAllData())));
}
}
|
package com.cs.rest.status;
import com.cs.payment.PaymentAmountException;
/**
* @author Hadi Movaghar
*/
public class PaymentAmountMessage extends ErrorMessage {
private static final long serialVersionUID = 1L;
public PaymentAmountMessage(final String message, final String value) {
super(StatusCode.INVALID_AMOUNT, message, value);
}
public static PaymentAmountMessage of(final PaymentAmountException exception) {
return new PaymentAmountMessage(exception.getMessage(), exception.getValue());
}
}
|
package com.sinodynamic.hkgta.security;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.StringUtils;
import com.sinodynamic.hkgta.dto.sys.RoleProgramURLDto;
import com.sinodynamic.hkgta.entity.crm.RoleProgram;
import com.sinodynamic.hkgta.security.service.RoleProgramService;
import com.sinodynamic.hkgta.service.sys.UserRoleMap;
import com.sinodynamic.hkgta.util.CommUtil;
import com.sinodynamic.hkgta.util.urlmatcher.AntUrlPathMatcher;
public class GtaInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
@Autowired
private RoleProgramService roleProgramService;
private AntUrlPathMatcher urlMatcher = new AntUrlPathMatcher();
private static Map<String, Collection<ConfigAttribute>> resourceMap = null;
public static Map<String, Collection<ConfigAttribute>> getResourceMap()
{
return resourceMap;
}
public GtaInvocationSecurityMetadataSource() {
}
/** init-method of GtaInvocationSecurityMetadataSource */
//@PostConstruct
public void loadProgramRoles() {
UserRoleMap.getInstance().setRoleMenu(roleProgramService.initRoleMenu());
resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
// fetch role-programs from database, and put them in this.resourceMap.
String programUrlPath = null;
String roleName = null;
Collection<ConfigAttribute> atts = null;
List<RoleProgramURLDto> rolePrograms = roleProgramService.getRoleProgramsWithUrlPath();
if (rolePrograms != null && !rolePrograms.isEmpty()) {
for (RoleProgramURLDto roleProgram : rolePrograms) {
programUrlPath = roleProgram.getUriPath();
roleName = roleProgram.getRoleName();
if (CommUtil.notEmpty(programUrlPath) && CommUtil.notEmpty(roleName)) {
atts = resourceMap.get(programUrlPath);
if (atts == null) {
atts = new ArrayList<ConfigAttribute>();
}
atts.add(new GtaSecurityConfig(roleName, roleProgram.getAccessRight()));
resourceMap.put(programUrlPath, atts);
}
}
}
// TODO programMaster.urlPath == null --> no authorization required?
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
@Override
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
// param "object" --> request (url).
String url = ((FilterInvocation) object).getRequestUrl();
if ("/".equals(url)) {
return null;
}
int firstQuestionMarkIndex = url.indexOf(".");
// (/index.do --> /index)
if (firstQuestionMarkIndex != -1) {
url = url.substring(0, firstQuestionMarkIndex);
}
String urlPath = ((FilterInvocation) object).getHttpRequest().getPathInfo();
if (!StringUtils.isEmpty(urlPath))
{
url = urlPath;
}
Iterator<String> ite = resourceMap.keySet().iterator();
// compare / pattern-actualUrl matching
while (ite.hasNext()) {
String resURL = ite.next(); // url-pattern
if (urlMatcher.pathMatchesUrl(resURL, url)) {
return resourceMap.get(resURL);
}
}
return null;
}
@Override
public boolean supports(Class<?> arg0) {
return true;
}
}
|
package xcelite.writer;
import org.apache.poi.ss.SpreadsheetVersion;
import org.junit.BeforeClass;
import org.junit.Test;
import xcelite.model.BeanWriterTestsBean;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class BeanWriterTests extends AbstractTestBaseForWriterTests {
private static BeanWriterTestsBean bean = new BeanWriterTestsBean();
@BeforeClass
public static void setup() throws Exception {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < SpreadsheetVersion.EXCEL2007.getMaxTextLength(); i++) {
sb.append("a");
}
bean.setLongString(sb.toString());
setup(bean);
}
@Test
public void mustWriteLongStringsOK() throws Exception {
Map<String, Object> columnsMap = extractCellValues (workbook);
String val = bean.getLongString();
Object obj = columnsMap.get("LONG_STRING");
assertEquals(val, obj);
}
}
|
package ch.ffhs.ftoop.doppelgruen.quiz.game;
import ch.ffhs.ftoop.doppelgruen.quiz.client.Client;
import ch.ffhs.ftoop.doppelgruen.quiz.utils.SleepUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
class QuizSessionTest {
private static Server server;
private static Thread serverThread;
private static Players players;
private static final int SERVER_PORT = 60700;
private static final int SAFESLEEP_MILLISECONDS = 100;
@BeforeAll
static void setUp() {
server = new Server(SERVER_PORT);
serverThread = new Thread(server);
serverThread.start();
SleepUtils.safeSleep(TimeUnit.MILLISECONDS, SAFESLEEP_MILLISECONDS);
var client = Client.createClient("localhost", SERVER_PORT);
if (client == null) {
fail();
}
var serverWorker = new ServerWorker(server, client.getSocket());
players = server.getPlayerController();
var player1 = players.createPlayerIfPossible("player1", serverWorker);
var player2 = players.createPlayerIfPossible("player2", serverWorker);
player1.setLocation(Location.INGAME);
player2.setLocation(Location.INGAME);
}
@AfterAll
static void tearDown() {
serverThread.interrupt();
}
@Test
@DisplayName("Test constructor")
void testConstructor1() {
var cut = new QuizSession(server, players.getAllPlayers());
assertNotNull(cut);
}
@Test
@DisplayName("Test constructor null server")
void testConstructor2() {
var playerList = players.getAllPlayers();
assertThrows(NullPointerException.class, () -> new QuizSession(null, playerList));
}
@Test
@DisplayName("Test constructor null players")
void testConstructor3() {
assertThrows(NullPointerException.class, () -> new QuizSession(server, null));
}
}
|
package ru.job4j.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Set;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import ru.job4j.models.Item;
import ru.job4j.services.ItemDAO;
import ru.job4j.utils.Filter;
import ru.job4j.utils.Validation;
/**
* Класс Create реализует контроллер Запись элементов TODO-листа.
*
* @author Gureyev Ilya (mailto:ill-jah@yandex.ru)
* @version 2019-01-12
* @since 2018-04-03
*/
public class Create extends AbstractServlet {
/**
* Карта фильтров.
*/
private final HashMap<String, Filter> filters = new HashMap<>();
/**
* ItemDAO.
*/
private final ItemDAO idao = new ItemDAO();
/**
* Логгер.
*/
private final Logger logger = LogManager.getLogger(this.getClass().getSimpleName());
/**
* Инициализатор.
* @throws javax.servlet.ServletException исключение сервлета.
*/
@Override
public void init() throws ServletException {
try {
super.init();
this.filters.put("name", new Filter("name", new String[]{"isExists", "isFilled"}));
this.filters.put("descr", new Filter("descr", new String[]{"isExists", "isFilled"}));
this.filters.put("created", new Filter("created", new String[]{"isExists", "isFilled"}));
this.filters.put("done", new Filter("done", new String[]{"isExists", "isFilled"}));
} catch (Exception ex) {
this.logger.error("ERROR", ex);
}
}
/**
* Обрабатывает GET-запросы. http://bot.net:8080/ch1_todolist-1.0/create/
* @param req запрос.
* @param resp ответ.
* @throws javax.servlet.ServletException исключение сервлета.
* @throws java.io.IOException исключение ввода-вывода.
*/
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
/**
* Обрабатывает POST-запросы. http://bot.net:8080/ch1_todolist-1.0/create/
* @param req запрос.
* @param resp ответ.
* @throws javax.servlet.ServletException исключение сервлета.
* @throws java.io.IOException исключение ввода-вывода.
*/
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
JsonObjectBuilder jsonb = Json.createObjectBuilder();
JsonObjectBuilder jsonErrors = Json.createObjectBuilder();
String status = "";
try {
String enc = (String) req.getAttribute("encoding");
String name = req.getParameter("name");
String descr = req.getParameter("descr");
String createdStr = req.getParameter("created");
String doneStr = req.getParameter("done");
/*String ajax = req.getParameter("type");
if (ajax == null && !"ajax".equals(ajax.trim())) {
name = new String(name.getBytes("ISO-8859-1"), enc);
descr = new String(descr.getBytes("ISO-8859-1"), enc);
}*/
Validation va = new Validation();
va.validate("name", name, this.filters.get("name").getFilters());
va.validate("descr", descr, this.filters.get("descr").getFilters());
va.validate("created", createdStr, this.filters.get("created").getFilters());
if (!va.hasError("created")) {
va.isDateFormat("created", "yyyy-MM-dd H:m:s", createdStr);
}
va.validate("done", doneStr, this.filters.get("done").getFilters());
if (va.hasErrors()) {
status = "error";
HashMap<String, String> errors = va.getErrors();
Set<String> keys = errors.keySet();
for (String key : keys) {
jsonErrors.add(key, errors.get(key));
}
} else {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd H:m:s");
long created = sdf.parse(createdStr).getTime();
boolean done = Boolean.parseBoolean(doneStr);
Item item = new Item(0, name, descr, created, done);
int id = this.idao.create(item);
if (id != 0) {
item.setId(id);
status = "ok";
jsonb.add("id", id);
} else {
status = "error";
jsonErrors.add("item", "notcreated");
}
}
} catch (Exception ex) {
this.logger.error("ERROR", ex);
status = "error";
jsonErrors.add("exception", "create");
} finally {
jsonb.add("status", status);
jsonb.add("errors", jsonErrors);
JsonObject json = jsonb.build();
StringWriter strWriter = new StringWriter();
try (JsonWriter jsonWriter = Json.createWriter(strWriter)) {
jsonWriter.writeObject(json);
}
String jsonData = strWriter.toString();
resp.setContentType("application/json");
PrintWriter writer = new PrintWriter(resp.getOutputStream());
writer.append(jsonData);
writer.flush();
}
}
/**
* Вызывается при уничтожении сервлета.
*/
@Override
public void destroy() {
try {
this.idao.close();
} catch (Exception ex) {
this.logger.error("ERROR", ex);
}
}
} |
package com.news.demo.Utils;
import com.news.demo.webconfig.TencentAiConfig;
import org.springframework.util.DigestUtils;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class TencentAISignHolder {
// ================================================================
// Constants
// ================================================================
// ================================================================
// Fields
// ================================================================
private static final TencentAiConfig CONFIG = SpringContextHolder.getBean(TencentAiConfig.class);
// ================================================================
// Constructors
// ================================================================
// ================================================================
// Methods from/for super Interfaces or SuperClass
// ================================================================
// ================================================================
// Public or Protected Methods
// ================================================================
/**
* SIGN签名生成算法-JAVA版本 通用。默认参数都为UTF-8适用
*
* @param params 请求参数集,所有参数必须已转换为字符串类型
* @return 签名
* @throws IOException
*/
public static String getSignature(Map<String, Object> params) throws IOException {
Map<String, Object> sortedParams = new TreeMap<>(params);
Set<Map.Entry<String, Object>> entrys = sortedParams.entrySet();
StringBuilder baseString = new StringBuilder();
for (Map.Entry<String, Object> param : entrys) {
if (param.getValue() != null && !"".equals(param.getKey().trim()) &&
!"sign".equals(param.getKey().trim()) && !"".equals(param.getValue())) {
baseString.append(param.getKey().trim()).append("=")
.append(URLEncoder.encode(param.getValue().toString(), "UTF-8")).append("&");
}
}
if (baseString.length() > 0) {
baseString.deleteCharAt(baseString.length() - 1).append("&app_key=")
.append(CONFIG.getAppKey());
}
try {
String sign = DigestUtils.md5DigestAsHex(baseString.toString().getBytes());
System.out.println("sign:" + sign.toUpperCase());
return sign.toUpperCase();
} catch (Exception ex) {
throw new IOException(ex);
}
}
// ================================================================
// Getter & Setter
// ================================================================
// ================================================================
// Private Methods
// ================================================================
// ================================================================
// Inner or Anonymous Class
// ================================================================
// ================================================================
// Test Methods
// ================================================================
}
|
package in.msmartpay.agent.dmr1MoneyTransfer;
import android.os.Bundle;
import android.widget.TextView;
import in.msmartpay.agent.R;
import in.msmartpay.agent.utility.BaseActivity;
/**
* Created by Smartkinda on 6/19/2017.
*/
public class TransactionReceiptActivity extends BaseActivity {
private TextView tviewDeliveryTID, tviewTransferedType, tviewTransferedAmount, tviewBeneficiaryName, tviewBankName, tviewAccountNo, tviewIFSCCode, tviewTransactionStatus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dmr1_transaction_reciept);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setTitle("Transaction Receipt");
// dataAgentID = getIntent().getStringExtra("AgentID");
tviewDeliveryTID = (TextView) findViewById(R.id.tv_delivery_tid);
tviewTransferedType = (TextView) findViewById(R.id.tv_transfer_type);
tviewTransferedAmount = (TextView) findViewById(R.id.tv_transfer_amount);
tviewBeneficiaryName = (TextView) findViewById(R.id.tv_bene_name);
tviewBankName = (TextView) findViewById(R.id.tv_bank_name);
tviewAccountNo = (TextView) findViewById(R.id.tv_account_no);
tviewIFSCCode = (TextView) findViewById(R.id.tv_ifsc_code);
tviewTransactionStatus = (TextView) findViewById(R.id.tv_transaction_status);
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
|
package com.itheima.day_08.demo_01;
import java.io.File;
public class Demo_01 {
public static void main(String[] args) {
//构造方法1:
File f1 = new File("D:/itcast/java.txt");
// File f11 = new File("D:\\itcast\\java.txt"); //使用两个反斜杠分隔也可以
System.out.println(f1);
//构造方法2:
File f2 = new File("D:/itcast", "java.txt");
System.out.println(f2);
//构造方法3:
File srcFile = new File("D:/itcast");
File f3 = new File(srcFile, "java.txt");
System.out.println(f3);
}
}
|
package entities;
import java.awt.Color;
public class Jugador {
private String nickName;
private String estado;
private String clave;
private Color color;
public Jugador(String nick, Color color) {
this.nickName = nick;
//this.clave = clave;
this.color = color;
}
public Color getColor() {
return color;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public void estadoListo() {
this.estado = "Listo";
}
} |
package com.nube.core.instance.dao;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import com.nube.core.instance.dto.Instance;
/**
* Instance DAO Implimentation
* @author kamoorr
*
*/
@Component
public class InstanceDaoImpl implements InstanceDao{
@Autowired
private JdbcTemplate jdbcTemplate;
public Instance getInstance(String key) {
List<Instance> instanceList = this.getInstances();
return instanceList.get(this.getInstances().indexOf(new Instance(key,null)));
}
public List<Instance> getInstances() {
return jdbcTemplate.query(InstanceDaoSql.SELECTS, new InstanceDaoRowMapper());
}
public int save(Instance instance) {
return jdbcTemplate.update(InstanceDaoSql.INSERT, instance.getKey(), instance.getValue(), instance.getDescr());
}
public int delete(String key) {
return jdbcTemplate.update(InstanceDaoSql.DELETE, key);
}
}
|
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
public class Main {
// Workaround for b/18051191.
class Inner {}
public static native void assertIsInterpreted();
public static native void ensureJitCompiled(Class<?> cls, String methodName);
private static void assertEqual(String expected, String actual) {
if (!expected.equals(actual)) {
throw new Error("Assertion failed: " + expected + " != " + actual);
}
}
public static void main(String[] args) throws Throwable {
System.loadLibrary(args[0]);
Class<?> c = Class.forName("TestCase");
int[] array = new int[1];
{
// If the JIT is enabled, ensure it has compiled the method to force the deopt.
ensureJitCompiled(c, "testNoAlias");
Method m = c.getMethod("testNoAlias", int[].class, String.class);
try {
m.invoke(null, new Object[] { array , "foo" });
throw new Error("Expected AIOOBE");
} catch (InvocationTargetException e) {
if (!(e.getCause() instanceof ArrayIndexOutOfBoundsException)) {
throw new Error("Expected AIOOBE");
}
// Ignore
}
Field field = c.getField("staticField");
assertEqual("foo", (String)field.get(null));
}
{
// If the JIT is enabled, ensure it has compiled the method to force the deopt.
ensureJitCompiled(c, "testAlias");
Method m = c.getMethod("testAlias", int[].class, String.class);
try {
m.invoke(null, new Object[] { array, "bar" });
throw new Error("Expected AIOOBE");
} catch (InvocationTargetException e) {
if (!(e.getCause() instanceof ArrayIndexOutOfBoundsException)) {
throw new Error("Expected AIOOBE");
}
// Ignore
}
Field field = c.getField("staticField");
assertEqual("bar", (String)field.get(null));
}
}
}
|
//подсчет количества символов, которые повторяются более 1 раза в строке
package Tasks;
import java.util.Arrays;
public class Task1 {
public static void main(String[] args) {
// String str1 = "aabbcde";
// String str1 = "aabBcde";
// String str1 = "indivisibility";
// String str1 = "Indivisibilities";
// String str1 = "aA11";
// String str1 = "ABBA";
String str1 = "";
int n = 0;
int n1 = 0;
if (str1.length() > 0) {
String str2 = (str1.toLowerCase());
char[] str = str2.toCharArray();
Arrays.sort(str);
System.out.println(str);
System.out.println(str.length);
char c = str[0];
for (int i = 1; i < str.length; i++) {
if (c == str[i]) {
n++;
} else {
if ((n >= 1) && (c != ' ')) {
++n1;
n = 0;
}
}
c = str[i];
}
if (n >= 1) {
++n1;
}
}
System.out.println(n1);
}
}
|
package com.ruoyi.system.service;
import java.util.List;
import com.ruoyi.system.domain.TSaleChance;
/**
* 营销机会Service接口
*
* @author ruoyi
* @date 2021-10-18
*/
public interface ITSaleChanceService
{
/**
* 查询营销机会
*
* @param chanceId 营销机会主键
* @return 营销机会
*/
public TSaleChance selectTSaleChanceByChanceId(Long chanceId);
/**
* 查询营销机会列表
*
* @param tSaleChance 营销机会
* @return 营销机会集合
*/
public List<TSaleChance> selectTSaleChanceList(TSaleChance tSaleChance);
/**
* 新增营销机会
*
* @param tSaleChance 营销机会
* @return 结果
*/
public int insertTSaleChance(TSaleChance tSaleChance);
/**
* 修改营销机会
*
* @param tSaleChance 营销机会
* @return 结果
*/
public int updateTSaleChance(TSaleChance tSaleChance);
/**
* 批量删除营销机会
*
* @param chanceIds 需要删除的营销机会主键集合
* @return 结果
*/
public int deleteTSaleChanceByChanceIds(String chanceIds);
/**
* 删除营销机会信息
*
* @param chanceId 营销机会主键
* @return 结果
*/
public int deleteTSaleChanceByChanceId(Long chanceId);
}
|
package com.micHon.forecast;
import com.micHon.messager.Observer;
import java.util.HashSet;
import java.util.Set;
public class WeatherForecast implements Observable {
private int temperature;
private int pressure;
Set<Observer> registeredObservers = new HashSet<Observer>();
public void registerObserver(Observer observer) {
registeredObservers.add(observer);
}
public void unregisterObserver(Observer observer) {
registeredObservers.remove(observer);
}
public int getTemperature() {
return temperature;
}
public int getPressure() {
return pressure;
}
public void setTemperature(int temperature) {
this.temperature = temperature;
}
public void setPressure(int pressure) {
this.pressure = pressure;
}
public void notifyObservers() {
for (Observer observer: registeredObservers)
{
observer.updateForecast(this);
}
}
}
|
package com.hongchai.testspeed;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TestSpeedApplication {
public static void main(String[] args) {
SpringApplication.run(TestSpeedApplication.class, args);
}
}
|
package me.dags.DeathHockey.Listeners;
import me.dags.DeathHockey.DeathHockey;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import static me.dags.DeathHockey.DeathHockey.game;
/**
* @author dags_ <dags@dags.me>
*/
public class GoalListener implements Listener
{
@EventHandler
public void onMove(PlayerMoveEvent e)
{
if (DeathHockey.gameOn)
{
if (DeathHockey.game.checkGoals())
{
Player p = e.getPlayer();
if (p.getName().equals(DeathHockey.game.getPuck().getName()))
{
Location l = e.getTo();
Block b = l.add(0, -1, 0).getBlock();
if (b.getType().equals(Material.WOOL))
{
if (b.getData() == 11)
{
game.redGoal();
}
if (b.getData() == 14)
{
game.blueGoal();
}
}
}
}
}
}
}
|
package Networking;
/**
* Created by anas on 10/25/15.
*/
import java.net.*;
import java.io.*;
public class FirstClient {
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket("localhost",9000);
socket.setSoTimeout(15000);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
out.write(5);
System.out.println(in.read());
out.flush();
out.close();
in.close();
} catch(IOException e) {
System.err.println(e);
}
}
}
|
package org.squonk.execution.variable;
import org.squonk.notebook.api.VariableKey;
import java.io.IOException;
import java.io.InputStream;
/**
*
* @author timbo
*/
public interface VariableLoader {
public void save() throws IOException;
public <V> V readFromText(VariableKey var, Class<V> type) throws IOException;
public <V> V readFromJson(VariableKey var, Class<V> type) throws IOException;
public InputStream readBytes(VariableKey var, String label) throws IOException;
public void writeToText(VariableKey var, Object o) throws IOException;
public void writeToJson(VariableKey var, Object o) throws IOException;
public void writeToBytes(VariableKey var, String label, InputStream is) throws IOException;
}
|
package am.bizis.cds.dpfdp4;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.util.LinkedList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import taka.CountryCode;
import am.bizis.cds.IVeta;
import am.bizis.exception.ConditionException;
import am.bizis.exception.DataUnsetException;
import am.bizis.exception.MissingElementException;
import am.bizis.exception.MultipleElementsOfSameTypeException;
/**
* Trida EPOFactory vytvori EPO na zaklade dat z uzivatelskeho rozhrani
* pouziti: new EPOFactory(IFormDataGrab).getEPO(getContent()); vrati XML dokument -> ten poslat na CDS MF
*
* @author alex
*/
/*
* Zvlastnosti kodu:
* Jelikoz puvodni implementace metody getContent() zahrnovala dlouhou nudli
* try{}catch(){}finally{
* try{}catch(){}finally{
* try{}catch(){}finally{
* atd.
* }
* }
* }
* zpusobovalo to chybu, kdy JVM povoluje delku kodu metody pouze 65kB
* problem byl vyresen tak, ze kazde finally vola novou metodu, ktera obsahuje try{}catch(){}finally{}
* toto reseni vsak teoreticky muze zpusobit preteceni zasobniku volani
* pokud toto nastane, lze spojit nekolik try{}catch(){}finally{try{}catch(){}finally{}} do sebe a nalezt optimalni
* kompromis mezi delkou stacku volani a delkou jednotlivych metod
*/
public class EPOFactory {
private final IFormDataGrab FORM;
private final EPO EPOdoc;
/**
* Konstruktor vytvori objekt EPO a ulozi si formu
* @param form GUI DPDPF
*/
public EPOFactory(IFormDataGrab form) {
this.FORM=form;
this.EPOdoc=new EPO();
}
/**
* Stane-li se chyba, vypsat uzivateli a do logu
* @param user - zprava pro uzivatele
* @param log - zprava do logu
*/
private void error(String user,String log){
FORM.showMessage(user);
note(log);
}
/**
* Neni-li nastavena nepovinna polozka, zaznamename to do logu
* @param msg zprava
*/
private void note(String msg){
}
/**
* Vytvori XML dokument na zaklade predvytvorenych vet
* @param content obsah XML dokumentu
* @return EPO DPDPF
*/
public Document getEPO(IVeta[] content){
Document doc=null;
try{
doc=EPOdoc.makeXML(content);
}catch(ParserConfigurationException e){
error("Stala se chyba pri vytvareni XML dokumentu","Stala se chyba pri vytvareni XML dokumentu\n"+e.getMessage()+"\n"+e.getStackTrace().toString());
}
return doc;
}
/**
* Vytvori objekty IVeta na zaklade uzivatelem zadanych dat do GUI formulare, ze kterych lze vytvorit samotne EPO
* @return pole vet pro getEPO
*/
public IVeta[] getContent(){
List<IVeta> seznam=new LinkedList<IVeta>();
VetaD d=null;
VetaP p=null;
try{
d=new VetaD(FORM.getAudit(), FORM.getCufo(), FORM.getDap_typ(), FORM.getPlnMoc(), FORM.getRok());
p=new VetaP(FORM.getPoplatnik(),FORM.getCpracufo());
}catch(ParseException e){
error("Neplatny rok: "+FORM.getRok(),e.getMessage()+"\n"+e.getStackTrace().toString());
}catch(MultipleElementsOfSameTypeException e){
error("Stala se chyba pri vytvareni XML dokumentu","Element se vyskytuje vicekrat nez je povoleno: "+e.getMessage()+"\n"+e.getStackTrace());
}catch(MissingElementException e){
error("Stala se chyba pri vytvareni XML dokumentu","Chybi element: "+e.getMessage()+"\n"+e.getStackTrace());
}catch(ConditionException e){
error(e.getMessage(),e.getMessage()+"\n"+e.getStackTrace());
}finally{
d=setD0(d);
seznam.add(d);
p=setP(p);
seznam.add(p);
}
return (IVeta[])seznam.toArray();
}
/**
* Zapise vytvoreny dokument do souboru
* @param f soubor
* @param epo vytvoreny dokument
*/
public void writeFile(File f,Document epo){
try {
FileWriter fw=new FileWriter(f);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.transform(new DOMSource(epo),
new StreamResult(fw));
} catch (IOException e) {
error("Chyba pri zapisu souboru",e.getMessage()+"\n"+e.getStackTrace());
} catch (TransformerException e) {
error("Chyba pri vytvareni XML dokumentu",e.getMessage()+"\n"+e.getStackTrace());
}
}
private VetaD setD0(VetaD d){
try{
d.setD_uv(FORM.getDen());
}catch(DataUnsetException e){
error("Neni vyplneno, ke kteremu dni se udaje z tabulek vztahuji",e.getMessage()+"\n"+e.getStackTrace().toString());
}
finally {
d=setD1(d);
}
return d;
}
private VetaD setD1(VetaD d){
try{
d.setDuvodpoddapdpf(FORM.getDuvod(), FORM.getDuvodDate());
}
catch(DataUnsetException e){
note("Neni nastaven kod rozliseni nebo datum");
}
finally {
d=setD2(d);
}
return d;
}
private VetaD setD2(VetaD d){
try{
d.setDa_celod13(FORM.getDanCelkem());
}catch(DataUnsetException e){
error("Neni vyplnena dan celkem",e.getMessage()+"\n"+e.getStackTrace().toString());
}
finally{
d=setD3(d);
}
return d;
}
private VetaD setD3(VetaD d){
try{
d.setKc_dazvyhod(FORM.getZvyhodDite());
}catch(DataUnsetException e){
note("Danove zvyhodneni na vyzivovane dite neni nastaveno");
}
finally{
d=setD4(d);
}
return d;
}
private VetaD setD4(VetaD d){
try{
d.setKc_dztrata(FORM.getDztrata());
}catch(DataUnsetException e){
note("Danova ztrata neni nastavena");
}
finally{
d=setD5(d);
}
return d;
}
private VetaD setD5(VetaD d){
try{
d.setKc_konkurs(FORM.getZaloha());
}catch(DataUnsetException e){
note("Zaplacena danova povinnost neni nastavena");
}
finally{
d=setD6(d);
}
return d;
}
private VetaD setD6(VetaD d){
try{
d.setKc_op15_1c(FORM.getManz());
try{
d.setManz(FORM.getManzID());
}catch(DataUnsetException e){
error("Je uplatnovana sleva na manzela/ku, ale nevime o koho jde",e.getMessage()+"\n"+e.getStackTrace());
}
try{
d.setM_manz(FORM.getManzMes());
}catch(DataUnsetException e){
error("Je uplatnovana sleva na manzela/-ku, ale neni uveden pocet mesicu",e.getMessage()+"\n"+e.getStackTrace());
}
try{
d.setKc_manztpp(FORM.getManZTP());
}catch(DataUnsetException e){
note("Manzel/ka neni drzitelem ZTP/P");
}
}catch(DataUnsetException e){
note("Sleva na manzela/-ku se neuplatnuje");
}
finally {
d=setD7(d);
}
return d;
}
private VetaD setD7(VetaD d){
try{
d.setKc_op15_1d(FORM.getInvalid());
try{
d.setM_invduch(FORM.getInvDuch());
}catch(DataUnsetException e){
error("Neni vyplnen pocet mesicu v invalidnim duchodu",e.getMessage()+"\n"+e.getStackTrace());
}
}catch(DataUnsetException e){
note("Sleva na pozivatele invalidniho duchodu pro invaliditu prvniho nebo druheho stupne se neuplatnuje");
}
finally{
d=setD8(d);
}
return d;
}
private VetaD setD8(VetaD d){
try{
d.setKc_op15_1e1(FORM.getInvalid3());
}catch(DataUnsetException e){
note("Sleva na pozivatele invalidniho duchodu pro invaliditu tretiho stupne se neuplatnuje");
}finally{
d=setD9(d);
}
return d;
}
private VetaD setD9(VetaD d){
try{
d.setKc_op15_1e2(FORM.getZTP());
}catch(DataUnsetException e){
note("Sleva na drzitele pruazu ZTP/P se neuplatnuje");
}finally{
d=setD10(d);
}
return d;
}
private VetaD setD10(VetaD d){
try{
d.setKc_pausal(FORM.getPausal());
}catch(DataUnsetException e){
note("Neni zaplacena dan pausalni castkou");
}finally{
d=setD11(d);
}
return d;
}
private VetaD setD11(VetaD d){
try{
d.setKc_pzdp(FORM.getPosledni());
}catch(DataUnsetException e){
note("Neni znama posledni dan");
}finally{
d=setD12(d);
}
return d;
}
private VetaD setD12(VetaD d){
try{
d.setKc_sraz367(FORM.getDluhopisy());
}catch(DataUnsetException e){
note("Neni srazena dan za statni dluhopisy");
}finally{
d=setD13(d);
}
return d;
}
private VetaD setD13(VetaD d){
try{
d.setKc_sraz3810(FORM.getSraz3810());
}catch(DataUnsetException e){
note("Neni srazena dan dle 38f odst. 12");
}finally{
d=setD14(d);
}
return d;
}
private VetaD setD14(VetaD d){
try{
d.setKc_sraz385(FORM.getZajistena());
}catch(DataUnsetException e){
note("Neni zajistena dan platcem podle 38e");
}finally{
d=setD15(d);
}
return d;
}
private VetaD setD15(VetaD d){
try{
d.setKc_sraz_rezehp(FORM.getSraz387());
}catch(DataUnsetException e){
note("Neni srazena dan podle 36 odst. 7");
}finally{
d=setD16(d);
}
return d;
}
private VetaD setD16(VetaD d){
try{
d.setKc_stud(FORM.getStudium());
}catch(DataUnsetException e){
note("Neni sleva na studenta");
}
finally{
try{
d.setKc_vyplbonus(FORM.getBonusy());
}catch(DataUnsetException e){
note("Nejsou vyplacene zadne mesicni danove bonusy");
}finally{
d=setD17(d);
}
}
return d;
}
private VetaD setD17(VetaD d){
try{
d.setKc_zalpred(FORM.getZalohyZaplacene());
}catch(DataUnsetException e){
note("Nezaplaceny zadne zalohy");
}finally{
d=setD18(d);
}
return d;
}
private VetaD setD18(VetaD d){
try{
d.setKc_zalzavc(FORM.getZalohySrazene());
}catch(DataUnsetException e){
note("Nebyly srazene zadne zalohy");
}finally{
d=setD19(d);
}
return d;
}
private VetaD setD19(VetaD d){
try{
d.setKod_popl(FORM.getKodPopl());
}catch(DataUnsetException e){
note("Kod statu nevyplnen - predpokladame danoveho rezidenta");
}finally{
d=setD20(d);
}
return d;
}
private VetaD setD20(VetaD d){
try{
d.setM_cinvduch(FORM.getCinDuch());
}catch(DataUnsetException e){
note("Pocet mesicu cinny v duchodu nevyplnen");//TODO: co to vlastne je??
}finally{
d=setD21(d);
}
return d;
}
private VetaD setD21(VetaD d){
try{
d.setM_deti(FORM.getDeti());
try{
d.setM_detiztpp(FORM.getDetiZTPP());
if(FORM.getDetiZTPP()>FORM.getDeti()) error("Pocet mesicu deti se ZTP/P vetsi nez pocet mesicu deti","Pocet mesicu deti se ZTP/P vetsi nez pocet mesicu deti");
}catch(DataUnsetException e){
note("Deti bez ZTP/P");
}
}catch(DataUnsetException e){
note("Bez deti");
}finally{
d=setD22(d);
}
return d;
}
private VetaD setD22(VetaD d){
try{
d.setManz(FORM.getManzID());
try{
d.setM_manz(FORM.getManzMes());
}catch(DataUnsetException e){
error("Neni vyplnen pocet mesicu manzelstvi",e.getMessage()+"\n"+e.getStackTrace());
}
}catch(DataUnsetException e){
note("Neni manzel(ka)");
}finally{
d=setD23(d);
}
return d;
}
private VetaD setD23(VetaD d){
//d.setPln_moc(FORM.getPlnMoc());
try{
d.setSleva_rp(FORM.getSlevaRP());
}catch(DataUnsetException e){
note("SlevaRP neni nastavena");//TODO wut?
}
finally{
d=setD24(d);
}
return d;
}
private VetaD setD24(VetaD d){
try{
d.setUv_vyhl(FORM.getVyhlaska());
try{
d.setUv_podpis(FORM.getUVpodpis());
}catch(DataUnsetException e){
error("Je vyplneno cislo vyhlasky, ale neni vyplnena osoba, jejiz podpisovy zaznam je k vyhlasce pripojen",e.getMessage()+"\n"+e.getStackTrace());
}
}catch(DataUnsetException e){
note("Neni cislo vyhlasky - nejspis nejde o OSVC");
}
return d;
}
private VetaP setP(VetaP p){
//p.setPoplatnik(FORM.getPoplatnik());
//p.setCpracufo(FORM.getCpracufo());
try{
p.setKrok(FORM.getKrok());
}catch(DataUnsetException e){
note("K poslednimu dni roku bydlel na soucasne adrese trvaleho pobytu");
}
try{
if(FORM.getPoplatnik().getAdresa().getStat()!=CountryCode.CZ) p.setZdrz(FORM.getZdrz());
else error("Adresa mista pobytu, kde se poplatnik obvykle ve zdanovacim obdobi zdrzoval se vyplnuje, pokud nema misto pobytu v CR","Poplatnik ma bydliste v CR a chce volat setZdrz() ve vete P");
}catch(DataUnsetException e){
note("Poplatnik bydlel v CR");
}
try{
p.setEvCislo(FORM.getEVcislo());
}catch(DataUnsetException e){
note("Nema danoveho poradce");
}
return p;
}
}
|
package com.consultorio.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.consultorio.model.Administrador;
import com.consultorio.model.Medico;
import com.consultorio.model.Paciente;
import com.consultorio.model.Pessoa;
@WebFilter(filterName = "SecurityFilter", urlPatterns = { "/faces/*" })
public class SecurityFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// Para desabilitar o filter, descomente as duas proximas linhas e comente o
// restante
// chain.doFilter(request, response);
// return;
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
// retorna a sessao corrente (false - para nao criar uma nova sessao)
HttpSession session = (HttpSession) req.getSession();
// carregando o atributo do tipo pessoa dentro da sessao
Pessoa pessoa = (Pessoa) session.getAttribute("usuarioLogado");
String link = req.getRequestURL().toString();
// Permite os recursos css img etc
if (link.contains("http://localhost:8080/Consultorio/faces/javax.faces.resource/")) {
chain.doFilter(request, response);
return;
}
// imprime o endereco da pagina
System.out.println(link);
// se nao tiver usuario logado na sessao so tera acesso a pagina de login, cadastro ou index etc
if (pessoa == null && !(link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/login.xhtml")
|| link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/cadastro.xhtml")
|| link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/index.xhtml"))) {
res.sendRedirect(req.getContextPath() + "/faces/login.xhtml");
return;
} // nao permite o usuario logado a acessar a acessar a area de login ou de cadastro etc
else if (pessoa != null && (link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/login.xhtml")
|| link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/cadastro.xhtml"))) {
res.sendRedirect(req.getContextPath() + "/faces/home.xhtml");
return;
}
// tratamento de p�ginas pelo tipo m�dico e paciente
else if (pessoa != null && pessoa.getMedico() != null && pessoa.getPaciente() != null) {
if (!(link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/medico.xhtml")
|| link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/paciente.xhtml")
|| link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/perfilAdm.xhtml")
|| link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/especialidademedica.xhtml"))) {
chain.doFilter(request, response);
} else {
res.sendRedirect(req.getContextPath() + "/faces/home.xhtml");
return;
}
}
// tratamento de p�ginas pelo tipo m�dico
else if (pessoa != null && pessoa.getMedico() != null) {
if (link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/home.xhtml")
|| link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/perfilUsuario.xhtml")
|| link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/index.xhtml")
|| link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/home.xhtml")
|| link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/prescricoes.xhtml")
|| link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/atestado.xhtml")
|| link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/agenda.xhtml")
|| link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/pacientesReport")
|| link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/financeiro.xhtml")) {
chain.doFilter(request, response);
} else {
res.sendRedirect(req.getContextPath() + "/faces/home.xhtml");
return;
}
}
// tratamento de p�ginas pelo tipo paciente
else if (pessoa != null && pessoa.getPaciente() != null) {
if (link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/home.xhtml")
|| link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/perfilUsuario.xhtml")
|| link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/home.xhtml")
|| link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/index.xhtml")
|| link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/examePaciente.xhtml")
|| link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/anamnese.xhtml")
|| link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/evolucao.xhtml")
|| link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/atestado.xhtml")
|| link.equalsIgnoreCase("http://localhost:8080/Consultorio/faces/agenda.xhtml")) {
chain.doFilter(request, response);
} else {
res.sendRedirect(req.getContextPath() + "/faces/home.xhtml");
return;
}
} else {
// CONTINUA A EXECUCAO INDO PARA A PAGINA REQUISITADA
chain.doFilter(request, response);
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("SecurityFilter Iniciado.");
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
|
package maksplo.study.ractanglemove;
public class Rectangle {
private Vector topLeftRightBottom;
public Rectangle(Vector rectangle) {
this.topLeftRightBottom = rectangle;
}
void move(Vector another) {
topLeftRightBottom.move(another);
}
String printRectangle() {
return topLeftRightBottom.printVector();
}
public boolean isInside(Point point) {
if (point.getX() >= topLeftRightBottom.getOneX() && point.getX() <= topLeftRightBottom.getTwoX() && point.getY() >= topLeftRightBottom.getOneY() && point.getY() <= topLeftRightBottom.getTwoY()) {
return true;
} else {
return false;
}
}
public boolean isInside(Point point, Vector another) {
if (point.getX() >= another.getOneX() && point.getX() <= another.getTwoX() && point.getY() >= another.getOneY() && point.getY() <= another.getTwoY()) {
return true;
} else {
return false;
}
}
}
|
package org.jinku.sync.application.server.http;
import org.jinku.sync.application.ao.ResultAo;
import org.jinku.sync.application.param.PushSyncParam;
import org.jinku.sync.domain.entity.SyncEntity;
import org.jinku.sync.domain.repository.UserSessionRepository;
import org.jinku.sync.domain.service.SyncQueueService;
import org.jinku.sync.domain.types.BizType;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
@Component
public class PushSyncReqHandler extends AbstractHttReqHandler<PushSyncParam> {
@Resource
private SyncQueueService syncQueueService;
@Resource
private UserSessionRepository userSessionRepository;
@Override
public String supportUrl() {
return "/sync/pushSync";
}
@Override
public ResultAo handReqObj(PushSyncParam param) {
SyncEntity syncEntity = new SyncEntity(param.getUserId(), BizType.get(param.getBizType()),
param.getBizUuid(), param.getDataJson());
long syncId = syncQueueService.addSync(syncEntity);
userSessionRepository.notifyUserNewSync(param.getUserId());
return ResultAo.success(syncId);
}
}
|
package domain;
import java.util.ArrayList;
import java.util.List;
import javafx.collections.ObservableList;
public class TaalContext {
private TaalInterface taalInterface;
public TaalContext(){
}
public void setTaalInterface(TaalInterface taalInterface){
this.taalInterface = taalInterface;
}
public String getAanspreking(){
return taalInterface.getAanspreking();
}
public List<String> getTaalLijst(){
List <String> taalLijst = new ArrayList<String>();
for (TaalEnum taal:TaalEnum.values()){
taalLijst.add(taal.toString());
}
return taalLijst;
}
}
|
package co.company.spring.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import co.company.spring.dao.Depts;
import co.company.spring.dao.Emp;
import co.company.spring.dao.EmpMapper;
import co.company.spring.dao.EmpSearch;
import co.company.spring.dao.Jobs;
import co.company.spring.emp.service.EmpService;
@Controller
public class EmpController {
@Autowired EmpMapper dao; //DAO 가져오기
@ModelAttribute("jobs")
public List<Jobs> jobs(){
return dao.jobSelect();
}
@ModelAttribute("depts")
public List<Depts> depts(){
return dao.deptSelect();
}
@RequestMapping("ajax/jobSelect")
@ResponseBody //RestController 없을 시 이거 해줌 @Controller + @ResponsBody = @RestController
public List<Jobs> jobSelect(){
return dao.jobSelect();
}
@RequestMapping(value="/empSelect", method = RequestMethod.GET) // <- form 메소드 넘기는거랑 같음
public ModelAndView select(EmpSearch emp) { //모델 앤 뷰
ModelAndView mav = new ModelAndView();
//조회
mav.addObject("list", dao.getEmpList(emp)); //list 이름으로 줌
mav.setViewName("emp/select"); //리턴
return mav;
}
//입력화면
@GetMapping("/empinsertForm")
public String insertForm(Model model, Emp emp) { //Emp emp 빈거라도 넘겨줘야함
// model.addAttribute("jobs", dao.jobSelect()); //jobs 이름으로 줌
// model.addAttribute("depts", dao.deptSelect()); //depts 이름 줌
return "emp/insert";
}
//수정화면(입력이랑 비슷)
@GetMapping("/empUpdateForm")
public String updateForm(Model model, Emp emp) { //Emp emp 빈거라도 넘겨줘야함
// model.addAttribute("jobs", dao.jobSelect()); //jobs 이름으로 줌
model.addAttribute("emp", dao.getEmp(emp)); //단건조회 emp 담아서 넘김
// model.addAttribute("depts", dao.deptSelect()); //depts 이름 줌
return "emp/insert";
}
//입력처리
@PostMapping("/empInsert")
public String insert(Emp emp, Errors errors) { //Emp emp로 VO 다 가져옴 //객체명 따로 주자 할때는 ModelAttribute("속성명")
new EmpValidator().validate(emp, errors); //검증 객체 생성
if(errors.hasErrors()) {
return "emp/insert";
}
if(emp.getEmployeeId() == null) //employeeId가 널이면 입력 아니면 수정
dao.insertEmp(emp); //등록 dao 가져옴
else
dao.updateEmp(emp);
// return "redirect:/empSelect";
return "emp/insertOutput";
}
// public String insert(HttpServletRequest request,
// @RequestParam(value="lastName", //변수명 다르게 해줄때 value
// required = false, //값을 안넘겼을때 required
// defaultValue = "noname") String lName, //입력안하고 기본값 주기 noname
// @RequestParam(required = false) int salary,
// Emp emp){ //vo 객체 자체를 주면 다 가져올 수 있음 개사기
// //파라미터
// String firstName = request.getParameter("firstName");
// System.out.println(lName + ":" + firstName + ":" + salary);
// System.out.println("emp\n" + emp); //emp 전체 가져오기
// //등록처리
// //조회로
// return "redirect:/empSelect";
// }
}
|
package com.yukai.monash.student_seek;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import cz.msebera.android.httpclient.Header;
/**
* Created by yukaima on 21/05/16.
*/
public class employer_applicantsFragment extends Fragment {
private Button btn_back;
private ListView applicantsLV;
private ArrayList<Applicants_model> applicantssArrayList;
private SharedPreferenceHelper sharedPreferenceHelper;
private Applicants_adapter applicants_adapter;
public static employer_applicantsFragment newInstance() {
employer_applicantsFragment employer_applicantsFragment = new employer_applicantsFragment();
return employer_applicantsFragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_applicants, container, false);
applicantsLV =(ListView)view.findViewById(R.id.listview_applicants);
applicantssArrayList = new ArrayList<Applicants_model>();
sharedPreferenceHelper = new SharedPreferenceHelper(getContext(),"Login Credentials");
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
String employerid = sharedPreferenceHelper.loadPreferences("userid");
params.add("employerid", employerid);
Log.d("empid",employerid);
client.post(getContext(), "http://173.255.245.239/jobs/get_applicants.php",params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
String response = new String(responseBody);
try {
JsonReader reader = new JsonReader(new StringReader(response));
reader.setLenient(true);
applicantssArrayList = new Gson().fromJson(reader, new TypeToken<List<Applicants_model>>() {
}.getType());
applicants_adapter = new Applicants_adapter(getContext(), applicantssArrayList);
applicantsLV.setAdapter(applicants_adapter);
applicantsLV.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(
) {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
builder.setTitle("Remove this applicant?");
builder.setMessage("Are you sure you wish to remove this applicant?");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Remove job from Database
Applicants_model applicants_model = applicantssArrayList.remove(position);
String userid = applicants_model.getUserid();
deleteApplicantsFromDataBase(userid);
// Update ListView
applicants_adapter.notifyDataSetChanged();
Toast.makeText(getActivity(),
"This applicant has been removed.",
Toast.LENGTH_SHORT)
.show();
}
}
);
builder.setNegativeButton("Exit",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Close the dialog
dialogInterface.cancel();
}
}
);
// Create and show dialog
builder.create().show();
return false;
}
});
}catch (JsonSyntaxException e){}
catch (NullPointerException e){}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
btn_back = (Button)view.findViewById(R.id.btn_back);
btn_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getFragmentManager().popBackStack();
}
});
return view;
}
public void deleteApplicantsFromDataBase(String userid)
{
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
sharedPreferenceHelper = new SharedPreferenceHelper(getContext(),"Login Credentials");
String employerid = sharedPreferenceHelper.loadPreferences("userid");
params.add("userid", userid);
params.add("empid", employerid);
client.post(getContext(), "http://173.255.245.239/jobs/employer_delete_applicants.php", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
String response = new String(responseBody);
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
}
}
|
/* Evaluators.java
Purpose:
Description:
History:
Mon Aug 25 14:06:17 2008, Created by tomyeh
Copyright (C) 2008 Potix Corporation. All Rights Reserved.
{{IS_RIGHT
This program is distributed under LGPL Version 2.1 in the hope that
it will be useful, but WITHOUT ANY WARRANTY.
}}IS_RIGHT
*/
package org.zkoss.zk.xel;
import org.zkoss.lang.Classes;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Page;
/**
* Utilities of evaluation.
*
* @author tomyeh
* @since 3.5.0
*/
public class Evaluators {
/** Evaluates the specified expression (which might or might not
* contain ${).
*
* @param comp the component to represent the self variable
*/
public static Object evaluate(Evaluator eval, Component comp,
String expr, Class expectedClass) {
if (expr != null && expr.indexOf("${") >= 0) {
return eval.evaluate(comp, eval.parseExpression(expr, expectedClass));
} else {
return Classes.coerce(expectedClass, expr);
}
}
/** Evaluates the specified expression (which might or might not
* contain ${).
*
* @param page the page to represent the self variable
*/
public static Object evaluate(Evaluator eval, Page page,
String expr, Class expectedClass) {
if (expr != null && expr.indexOf("${") >= 0) {
return eval.evaluate(page, eval.parseExpression(expr, expectedClass));
} else {
return Classes.coerce(expectedClass, expr);
}
}
}
|
package com.gtambit.gt.app.mission.obj;
public class RedeemGiftType
{
public String name;
public String phone;
public String address;
public String giftId;
public int quantity;
public String idNum;
public String lineId;
public String email;
}
|
package sample;
import javafx.fxml.FXML;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.shape.StrokeLineCap;
public class Controller {
private static final double MAX_LENGTH = 600;
private static final int exterior_angles_sum = 360; //外角和
private int polygon, level;
private GraphicsContext gc;
@FXML
public Button btnSubmit;
public Canvas canvas;
public TextField edtPolygon;
public TextField edtLevel;
public Label txtHint;
public void btnSubmitOnAction() {
System.out.println("btnSubmitOnAction");
if (verification()){
paint();
}
}
//查驗使用者輸入值
private boolean verification() {
try {
polygon = Integer.parseInt(edtPolygon.getText());
if (polygon < 3){
throw new NumberFormatException();
}
level = Integer.parseInt(edtLevel.getText());
if (level < -1){
throw new NumberFormatException();
}
txtHint.setText("");
return true;
} catch (NumberFormatException e) {
System.out.println("NumberFormatException");
edtPolygon.setText("3 ~ 6");
edtLevel.setText("0 ~ 5");
txtHint.setText("Number Invalid!");
return false;
}
}
//設定畫筆,並呼叫koch跑迴圈
private void paint() {
gc = canvas.getGraphicsContext2D();
gc.setLineCap(StrokeLineCap.BUTT);
gc.setLineWidth(1);
gc.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
koch(MAX_LENGTH - 50, 450,
MAX_LENGTH - 100, -90, level, 1);
}
/*
* 參數為座標、長度、角度、剩幾階、順/逆時針
* 若是最後一階就利用座標、長度、角度算出終點,並劃出來。
* 否則,將直線分成三個等分,一三段直接繼續遞迴
* 第二段要做一個正多變形,而第一個邊不用畫
* 每次都要轉(外角和/邊)度。
* 而下一次會轉向,所以將 * */
private void koch(double startX, double startY, double length, int angle, int leftLevel, int clockwise) {
if (leftLevel == -1) { //termination condition
gc.strokeLine(startX, startY, startX + length * Math.sin(Math.toRadians(angle)),
startY + length * Math.cos(Math.toRadians(angle)));
} else {
koch(startX, startY, length / 3, angle, leftLevel - 1, clockwise);//第一段
double x = startX + length / 3 * Math.sin(Math.toRadians(angle)); //第二點位置
double y = startY + length / 3 * Math.cos(Math.toRadians(angle));
int degree = angle;
if (clockwise < 0) {
for (int i = 0; i < polygon - 1; i++) {
x += length / 3 * Math.sin(Math.toRadians(degree));
y += length / 3 * Math.cos(Math.toRadians(degree));
degree += exterior_angles_sum / polygon;
koch(x, y, length / 3, degree, leftLevel - 1, clockwise * -1);
}
} else {
for (int i = 0; i < polygon - 1; i++) {
x += length / 3 * Math.sin(Math.toRadians(degree));
y += length / 3 * Math.cos(Math.toRadians(degree));
degree -= exterior_angles_sum / polygon;
koch(x, y, length / 3, degree, leftLevel - 1, clockwise * -1);
}
}
koch(startX + length * 2 / 3 * Math.sin(Math.toRadians(angle)),
startY + length * 2 / 3 * Math.cos(Math.toRadians(angle)),
length / 3, angle, leftLevel - 1, clockwise);//第三段
}
}
}
|
package suger.genType;/**
* Created by DELL on 2018/8/8.
*/
import java.util.List;
/**
* user is lwb
**/
public class GenOverLoad {
// public void test1(List<String> list){
//
// }
public int test1(List<Integer> list){
final String a ="1";
return 1;
}
}
|
package com.mhg.weixin.bean.msg;
import lombok.Data;
import java.util.Date;
@Data
public class MessageReceiveDO {
private String id;
private String toUserName;
private String fromUserName;
private Date createTime;
private String msgType;
private Integer msgId;
private String msgContent;
} |
package br.com.salon.carine.lima.exceptions;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class ControllerExceptionHandler {
@ExceptionHandler(ArgumentNotValidException.class)
public ResponseEntity<ValidationError> argumentNotValid(ArgumentNotValidException e,
HttpServletRequest request) {
ValidationError err = new ValidationError(System.currentTimeMillis(),
HttpStatus.UNPROCESSABLE_ENTITY.value(),
"Erro na validação dos campos", e.getMessage(),
request.getRequestURI());
for (FieldError error : e.getResult().getFieldErrors()) {
err.addError(error.getField(),
error.getDefaultMessage());
}
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(err);
}
}
|
package com.artogrid.bundle.idbbondgoods.service;
import java.io.Serializable;
import java.util.List;
import com.artogrid.framework.model.BondGoods;
import com.artogrid.framework.model.BondGoodsCompanyExtends;
import com.artogrid.framework.model.BondGoodsDetail;
import com.artogrid.framework.model.BondGoodsType;
public class BondGoodsPack implements Serializable {
private static final long serialVersionUID = 3430696762210091088L;
private BondGoods bondGoods;
private BondGoodsDetail bondGoodsDetail;
private List<BondGoodsCompanyExtends> bondGoodsCompanyExtends;
private BondGoodsType bondGoodsType;
private int rowNum;
public BondGoodsPack() {
}
public BondGoodsPack(BondGoods bondGoods, BondGoodsDetail bondGoodsDetail) {
super();
this.bondGoods = bondGoods;
this.bondGoodsDetail = bondGoodsDetail;
}
public void convertToFlex() {
bondGoods.setGoodsTerm(replaceString(bondGoods.getGoodsTerm(), ".", "-"));
bondGoods.setListingTime(replaceString(bondGoods.getListingTime(), ".", "-"));
bondGoodsDetail.setIssueTime(replaceString(bondGoodsDetail.getIssueTime(), ".", "-"));
bondGoodsDetail.setPayinterestTime(replaceString(bondGoodsDetail.getPayinterestTime(), ".", "-"));
bondGoodsDetail.setPayinterestEndtime(replaceString(bondGoodsDetail.getPayinterestEndtime(), ".", "-"));
bondGoodsDetail.setNextPayTime(replaceString(bondGoodsDetail.getNextPayTime(), ".", "-"));
}
public void convertToJava() {
bondGoods.setGoodsTerm(replaceString(bondGoods.getGoodsTerm(), "-", "."));
bondGoods.setListingTime(replaceString(bondGoods.getListingTime(), "-", "."));
bondGoodsDetail.setIssueTime(replaceString(bondGoodsDetail.getIssueTime(), "-", "."));
bondGoodsDetail.setPayinterestTime(replaceString(bondGoodsDetail.getPayinterestTime(), "-", "."));
bondGoodsDetail.setPayinterestEndtime(replaceString(bondGoodsDetail.getPayinterestEndtime(), "-", "."));
bondGoodsDetail.setNextPayTime(replaceString(bondGoodsDetail.getNextPayTime(), "-", "."));
}
private String replaceString(String str, String t, String r) {
if (str != null) {
return str.replace(t, r);
}
return null;
}
public BondGoods getBondGoods() {
return bondGoods;
}
public void setBondGoods(BondGoods bondGoods) {
this.bondGoods = bondGoods;
}
public BondGoodsDetail getBondGoodsDetail() {
return bondGoodsDetail;
}
public void setBondGoodsDetail(BondGoodsDetail bondGoodsDetail) {
this.bondGoodsDetail = bondGoodsDetail;
}
public List<BondGoodsCompanyExtends> getBondGoodsCompanyExtends() {
return bondGoodsCompanyExtends;
}
public void setBondGoodsCompanyExtends(List<BondGoodsCompanyExtends> bondGoodsCompanyExtends) {
this.bondGoodsCompanyExtends = bondGoodsCompanyExtends;
}
public int getRowNum() {
return rowNum;
}
public void setRowNum(int rowNum) {
this.rowNum = rowNum;
}
public BondGoodsType getBondGoodsType() {
return bondGoodsType;
}
public void setBondGoodsType(BondGoodsType bondGoodsType) {
this.bondGoodsType = bondGoodsType;
}
}
|
package com.fr.demo;
import java.awt.Color;
import com.fr.base.FRFont;
import com.fr.base.Style;
import com.fr.report.CellElement;
import com.fr.report.DefaultCellElement;
import com.fr.report.TemplateWorkBook;
import com.fr.report.WorkBook;
import com.fr.report.WorkSheet;
import com.fr.third.com.lowagie.text.Font;
import com.fr.web.Reportlet;
import com.fr.web.ReportletRequest;
public class CreatReportletDemo extends Reportlet{
public TemplateWorkBook createReport(ReportletRequest arg0){
//创建一个WorkBook工作薄,在工作薄中插入一个WorkSheet
WorkBook workbook = new WorkBook();
WorkSheet sheet1 = new WorkSheet();
//创建一个单元格new DefaultCellElement(int column, int row, Object value)
//列为0,行为0,值为FineReport,即A1单元格,并设置单元格的样式
CellElement CellA1 = new DefaultCellElement(0,0,"FineReport");
Style style = Style.getInstance();
//字体为Arial,粗体,字号20,红色
FRFont frfont = FRFont.getInstance("Arial",Font.BOLD,20,Color.red);
style = style.deriveFRFont(frfont);
CellA1.setStyle(style);
sheet1.addCellElement(CellA1);
//设置第0列列宽为120px,第0行行高为35px
sheet1.setColumnWidth(0, 120);
sheet1.setRowHeight(0, 35);
workbook.addReport(sheet1);
return workbook;
}
}
|
/*
import java.io.*;
import java.net.*;
import java.util.*;
/**
* A Simple Client
* Reference- Java: An Introduction to problem solving and programming,
*7th Edition
* by Walter Savitch
public class TCPClient {
public static void main(String[] args)
{
String s, tmp;
Scanner inputStream;
PrintWriter outputStream;
Scanner userinput;
try
{
// connects to port server app listesing at port 8888 in the same machine
Socket socket = new Socket("localhost", 8888);
// Create necessary streams
outputStream = new PrintWriter(new DataOutputStream(socket.getOutputStream()));
inputStream = new Scanner(new InputStreamReader(socket.getInputStream()));
userinput = new Scanner(System.in);
// send/receive messages to/from server
while(true)
{
System.out.println("Enter Text Message for Echo Server: ");
tmp = userinput.nextLine();
// Send user input message to server
outputStream.println(tmp);
//Flush to make sure message is send
outputStream.flush();
s = inputStream.nextLine();
System.out.println(s);
// Exit if message from server is "bye"
}
}
if(s.equalsIgnoreCase("bye"))
break;
}
inputStream.close();
outputStream.close();
}
catch (Exception e)
{
System.out.println("Error: " + e.getMessage());
} */
import java.util.*;
import java.io.*;
import java.net.*;
public class TCPClient {
public static void main(String[] args) {
String s, tmp;
InputStream inputStream = null ;
PrintWriter outputStream = null ;
OutputStream outfile = null;
Socket socket = null ;
try {
socket = new Socket("ucalgary.ca", 80); // host name and port
System.out.println("Connecting 1...");
}
catch(Exception e)
{
System.out.println("Error message"+ e.getMessage());
}
try{
System.out.println("Connecting 2...");
inputStream = socket.getInputStream(); // raed from text file
}
catch(Exception e)
{
System.out.println("Can't get socket input stream");
}
try{
System.out.println("Connecting 3...");
outputStream = new PrintWriter(new DataOutputStream(socket.getOutputStream()));
}
catch(Exception e)
{
System.out.println("Can't get to socket outputStream");
}
try {
System.out.println("Connecting 4 ...");
outputStream.println("GET /~mghaderi/test/test.html HTTP/1.0\n");
outputStream.flush();
outfile = new FileOutputStream("/Users/moonisahmed/Desktop/441/test.txt");
System.out.println("Connecting 5...");
byte[] bytes = new byte[55];
int count;
while ((count = inputStream.read(bytes)) > 0) {
System.out.println(bytes);
outfile.write(bytes , 0, count);
System.out.println("Connecting 6...");
}
System.out.println("Connecting 7...");
inputStream.close();
outputStream.close();
//socket.close();
}
catch(Exception e)
{
System.out.println("Can't stream");
}
}
} |
package com.ross.ui.admin;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.concurrent.atomic.AtomicBoolean;
public class TimeSkipper extends JPanel {
public TimeSkipper(AtomicBoolean tickSleep) {
JButton fastForwardButton = new JButton("fast forward");
fastForwardButton.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
tickSleep.set(false);
}
@Override
public void mouseReleased(MouseEvent e) {
tickSleep.set(true);
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
add(fastForwardButton);
}
}
|
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.jdbc.support;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.lang.Nullable;
/**
* {@link JdbcAccessor}-aligned subclass of the plain {@link DataSourceTransactionManager},
* adding common JDBC exception translation for the commit and rollback step.
* Typically used in combination with {@link org.springframework.jdbc.core.JdbcTemplate}
* which applies the same {@link SQLExceptionTranslator} infrastructure by default.
*
* <p>Exception translation is specifically relevant for commit steps in serializable
* transactions (e.g. on Postgres) where concurrency failures may occur late on commit.
* This allows for throwing {@link org.springframework.dao.ConcurrencyFailureException} to
* callers instead of {@link org.springframework.transaction.TransactionSystemException}.
*
* <p>Analogous to {@code HibernateTransactionManager} and {@code JpaTransactionManager},
* this transaction manager may throw {@link DataAccessException} from {@link #commit}
* and possibly also from {@link #rollback}. Calling code should be prepared for handling
* such exceptions next to {@link org.springframework.transaction.TransactionException},
* which is generally sensible since {@code TransactionSynchronization} implementations
* may also throw such exceptions in their {@code flush} and {@code beforeCommit} phases.
*
* @author Juergen Hoeller
* @author Sebastien Deleuze
* @since 5.3
* @see DataSourceTransactionManager
* @see #setDataSource
* @see #setExceptionTranslator
*/
@SuppressWarnings("serial")
public class JdbcTransactionManager extends DataSourceTransactionManager {
@Nullable
private volatile SQLExceptionTranslator exceptionTranslator;
private boolean lazyInit = true;
/**
* Create a new {@code JdbcTransactionManager} instance.
* A {@code DataSource} has to be set to be able to use it.
* @see #setDataSource
*/
public JdbcTransactionManager() {
super();
}
/**
* Create a new {@code JdbcTransactionManager} instance.
* @param dataSource the JDBC DataSource to manage transactions for
*/
public JdbcTransactionManager(DataSource dataSource) {
this();
setDataSource(dataSource);
afterPropertiesSet();
}
/**
* Specify the database product name for the {@code DataSource} that this
* transaction manager operates on.
* This allows for initializing a {@link SQLErrorCodeSQLExceptionTranslator} without
* obtaining a {@code Connection} from the {@code DataSource} to get the meta-data.
* @param dbName the database product name that identifies the error codes entry
* @see #setExceptionTranslator
* @see SQLErrorCodeSQLExceptionTranslator#setDatabaseProductName
* @see java.sql.DatabaseMetaData#getDatabaseProductName()
* @see JdbcAccessor#setDatabaseProductName
*/
public void setDatabaseProductName(String dbName) {
if (SQLErrorCodeSQLExceptionTranslator.hasUserProvidedErrorCodesFile()) {
this.exceptionTranslator = new SQLErrorCodeSQLExceptionTranslator(dbName);
}
else {
this.exceptionTranslator = new SQLExceptionSubclassTranslator();
}
}
/**
* Set the exception translator for this transaction manager.
* <p>A {@link SQLErrorCodeSQLExceptionTranslator} used by default if a user-provided
* `sql-error-codes.xml` file has been found in the root of the classpath. Otherwise,
* {@link SQLExceptionSubclassTranslator} serves as the default translator as of 6.0.
* @see org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator
* @see org.springframework.jdbc.support.SQLExceptionSubclassTranslator
* @see JdbcAccessor#setExceptionTranslator
*/
public void setExceptionTranslator(SQLExceptionTranslator exceptionTranslator) {
this.exceptionTranslator = exceptionTranslator;
}
/**
* Return the exception translator to use for this instance,
* creating a default if necessary.
* @see #setExceptionTranslator
*/
public SQLExceptionTranslator getExceptionTranslator() {
SQLExceptionTranslator exceptionTranslator = this.exceptionTranslator;
if (exceptionTranslator != null) {
return exceptionTranslator;
}
synchronized (this) {
exceptionTranslator = this.exceptionTranslator;
if (exceptionTranslator == null) {
if (SQLErrorCodeSQLExceptionTranslator.hasUserProvidedErrorCodesFile()) {
exceptionTranslator = new SQLErrorCodeSQLExceptionTranslator(obtainDataSource());
}
else {
exceptionTranslator = new SQLExceptionSubclassTranslator();
}
this.exceptionTranslator = exceptionTranslator;
}
return exceptionTranslator;
}
}
/**
* Set whether to lazily initialize the SQLExceptionTranslator for this transaction manager,
* on first encounter of an SQLException. Default is "true"; can be switched to
* "false" for initialization on startup.
* <p>Early initialization just applies if {@code afterPropertiesSet()} is called.
* @see #getExceptionTranslator()
* @see #afterPropertiesSet()
*/
public void setLazyInit(boolean lazyInit) {
this.lazyInit = lazyInit;
}
/**
* Return whether to lazily initialize the SQLExceptionTranslator for this transaction manager.
* @see #getExceptionTranslator()
*/
public boolean isLazyInit() {
return this.lazyInit;
}
/**
* Eagerly initialize the exception translator, if demanded,
* creating a default one for the specified DataSource if none set.
*/
@Override
public void afterPropertiesSet() {
super.afterPropertiesSet();
if (!isLazyInit()) {
getExceptionTranslator();
}
}
/**
* This implementation attempts to use the {@link SQLExceptionTranslator},
* falling back to a {@link org.springframework.transaction.TransactionSystemException}.
* @see #getExceptionTranslator()
* @see DataSourceTransactionManager#translateException
*/
@Override
protected RuntimeException translateException(String task, SQLException ex) {
DataAccessException dae = getExceptionTranslator().translate(task, null, ex);
if (dae != null) {
return dae;
}
return super.translateException(task, ex);
}
}
|
package com.git.cloud.tenant.model.po;
import com.git.cloud.common.model.base.BaseBO;
public class TenantUsersPo extends BaseBO implements java.io.Serializable{
/**
*
*/
private static final long serialVersionUID = 2667040728709093476L;
private String id;
private String tenantId;
private String userId;
private String firstName;
private String lastName;
private String loginName;
private String roleName;//0 用户管理员;1普通用户
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public TenantUsersPo() {
super();
}
@Override
public String getBizId() {
// TODO Auto-generated method stub
return null;
}
}
|
package ModeoDAO;
import Conexion.Conexion;
import Modelo.Autor;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author José Sorto
*/
public class AutorSQL extends Conexion {
public List Mostrar() {
PreparedStatement ps = null;
ResultSet rs = null;
Connection con = getConexion();
ArrayList<Autor> list = new ArrayList<>();
String sql = "SELECT* FROM autor";
try {
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
Autor autor = new Autor();
autor.setCodAutor(rs.getInt(1));
autor.setNombre(rs.getString(2));
autor.setPais(rs.getString(3));
list.add(autor);
}
} catch (SQLException e) {
System.err.println(e);
} finally {
try {
con.close();
} catch (SQLException e) {
System.err.println(e);
}
}
return list;
}
public Autor buscar(String ID) {
PreparedStatement ps = null;
ResultSet rs = null;
Connection con = getConexion();
String sql = "SELECT* FROM autor where codAutor="+ID;
Autor autor = new Autor();
try {
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
autor.setCodAutor(rs.getInt(1));
autor.setNombre(rs.getString(2));
autor.setPais(rs.getString(3));
}
} catch (SQLException e) {
System.err.println(e);
} finally {
try {
con.close();
} catch (SQLException e) {
System.err.println(e);
}
}
return autor;
}
public boolean Agregar(boolean pass, Autor autor) {
if (pass) {
PreparedStatement ps = null;
Connection con = getConexion();
String sql = "INSERT INTO autor (codAutor, Nombre, Pais) VALUES(?,?,?)";
try {
int z = 1;
ps = con.prepareStatement(sql);
ps.setInt(z++, generarCod());
ps.setString(z++, autor.getNombre());
ps.setString(z++, autor.getPais());
ps.execute();
} catch (SQLException e) {
System.err.println(e);
System.out.println("Error en Agregar de la clase AutorSQL");
return false;
} finally {
try {
con.close();
} catch (SQLException e) {
System.err.println(e);
}
}
}
return true;
}
public void Actualizar(boolean pass, Autor autor) {
if (pass) {
PreparedStatement ps = null;
Connection con = getConexion();
String sql = "UPDATE autor SET Nombre=?, Pais=? WHERE codAutor=? ";
try {
ps = con.prepareStatement(sql);
int z = 1;
ps.setString(z++, autor.getNombre());
ps.setString(z++, autor.getPais());
ps.setInt(z++, autor.getCodAutor());
ps.execute();
} catch (SQLException e) {
System.err.println(e);
System.out.println("Error en Actualizar de la clase AutorSQL");
} finally {
try {
con.close();
} catch (SQLException e) {
System.err.println(e);
}
}
}
}
public void Eliminar(boolean pass, String codLibro) {
if (pass) {
PreparedStatement ps = null;
Connection con = getConexion();
String sql = "DELETE FROM autor WHERE codAutor="+codLibro;
try {
ps = con.prepareStatement(sql);
ps.execute();
} catch (SQLException e) {
System.err.println(e);
System.out.println("Error en Eliminar de la clase AutorSQL");
} finally {
try {
con.close();
} catch (SQLException e) {
System.err.println(e);
}
}
}
}
public int generarCod() {
PreparedStatement ps = null;
ResultSet rs = null;
Connection con = getConexion();
String sql = "SELECT MAX(codAutor) as cantidad FROM autor";
try {
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
if (rs.next()) {
return Integer.parseInt(rs.getString("cantidad")) + 1;
}
return 0;
} catch (SQLException e) {
System.err.println(e);
return 0;
} finally {
try {
con.close();
} catch (SQLException e) {
System.err.println(e);
}
}
}
}
|
package com.nick.game;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Help extends JFrame implements ActionListener
{
JPanel jmain,jp1,jp2,jp3,jp4;
JLabel j1,j2,j3;
JButton b1;
public Help()
{
super("HELP");
jmain = new JPanel();
jp1 = new JPanel();
jp2 = new JPanel();
jp3 = new JPanel();
jp4 = new JPanel();
b1 = new JButton("OK");
j1 = new JLabel("WELCOME IN HELP MENU:");
j2= new JLabel("THIS FACILITY HAS NOT PROVIDED IN THIS CALCULATOR");
Icon img = new ImageIcon("images/6.GIF");
j3 = new JLabel(img);
getContentPane().add(jmain);
jmain.setLayout(new BorderLayout());
jmain.add(jp2,BorderLayout.SOUTH);
jmain.add(jp1,BorderLayout.CENTER);
jp1.setLayout(new GridLayout(1,2));
jp1.add(jp3);
jp1.add(jp4);
jp3.setLayout(new GridLayout(2,1));
jp3.add(j1);
jp3.add(j2);
jp4.add(j3);
jp2.add(b1);
b1.addActionListener(this);
setSize(400,200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent ae)
{
Object o = ae.getSource();
if (o==b1)
{
setVisible(false);
}
}
}
|
package md.tx.materialdesigndemo.complexCoordinatorLayout;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import md.tx.materialdesigndemo.R;
/**
* Created by Taxi on 2017/3/30.
*/
public class ListViewFragment extends Fragment {
private ListView mRootView;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mRootView = (ListView) inflater.inflate(R.layout.layout_listview_fragment, container, false);
return mRootView;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initData();
}
private void initData() {
mRootView.setAdapter(new MyAdapter());
}
private class MyAdapter extends BaseAdapter {
@Override
public int getCount() {
return 20;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item_card, null);
}
return convertView;
}
}
public static ListViewFragment newInstance() {
return new ListViewFragment();
}
}
|
/**
* COPYRIGHT (C) 2013 KonyLabs. All Rights Reserved.
*
* @author rbanking
*/
package com.classroom.services.web.dto.request;
import javax.xml.bind.annotation.XmlRootElement;
import org.hibernate.validator.constraints.NotEmpty;
/**
* Request for role creation
*
* JSON example:
*
* <pre>
* {"name":"rolename",
* "description":"some description"}
* </pre>
*
* XML example:
*
* <pre>
* {@code
* <role>
* <name>
* rolename
* </name>
* <description>
* some description
* </description>
* </role>
* }
* </pre>
*
* Name should not be empty
*/
@XmlRootElement(name = "role")
public class RoleRequest extends BasicRequest {
@NotEmpty
private String name;
private String description;
/**
* The Constructor.
*/
public RoleRequest() {
super();
}
/**
* The Constructor.
*
* @param name
* the name
* @param description
* the description
*/
public RoleRequest(String name, String description) {
super();
this.name = name;
this.description = description;
}
/**
* Gets the name.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Sets the name.
*
* @param name
* the name
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the description.
*
* @return the description
*/
public String getDescription() {
return description;
}
/**
* Sets the description.
*
* @param description
* the description
*/
public void setDescription(String description) {
this.description = description;
}
}
|
package org.jphototagger.program.module.search;
import javax.swing.SwingUtilities;
import org.bushe.swing.event.annotation.AnnotationProcessor;
import org.bushe.swing.event.annotation.EventSubscriber;
import org.jphototagger.lib.api.LookAndFeelChangedEvent;
import org.jphototagger.lib.swing.Dialog;
import org.jphototagger.lib.util.Bundle;
import org.jphototagger.program.resource.GUI;
/**
* Nicht modaler Dialog für eine erweiterte Suche.
*
* @author Elmar Baumann
*/
public final class AdvancedSearchDialog extends Dialog implements NameListener {
public static final AdvancedSearchDialog INSTANCE = new AdvancedSearchDialog(false);
private static final long serialVersionUID = 1L;
private AdvancedSearchDialog(boolean modal) {
super(GUI.getAppFrame(), modal);
initComponents();
postInitComponents();
}
private void postInitComponents() {
panel.addNameListener(this);
AnnotationProcessor.process(this);
}
@Override
public void setVisible(boolean visible) {
if (visible) {
panel.restore();
setSearchName(panel.getSearchName());
}
super.setVisible(visible);
}
private void beforeWindowClosing() {
panel.persist();
panel.willDispose();
setVisible(false);
}
public AdvancedSearchPanel getPanel() {
return panel;
}
@Override
protected void showHelp() {
showHelp(Bundle.getString(AdvancedSearchDialog.class, "AdvancedSearchDialog.HelpPage"));
}
@Override
protected void escape() {
beforeWindowClosing();
}
public AdvancedSearchPanel getAdvancedSearchPanel() {
return panel;
}
@Override
public void nameChanged(String name) {
if (name == null) {
throw new NullPointerException("name == null");
}
setSearchName(name);
}
private void setSearchName(String name) {
String delimiter = ": ";
setTitle(Bundle.getString(AdvancedSearchDialog.class, "AdvancedSearchDialog.TitlePrefix") + delimiter + name);
}
@EventSubscriber(eventClass = LookAndFeelChangedEvent.class)
public void lookAndFeelChanged(LookAndFeelChangedEvent evt) {
SwingUtilities.updateComponentTreeUI(this);
}
/**
* This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
private void initComponents() {//GEN-BEGIN:initComponents
panel = new org.jphototagger.program.module.search.AdvancedSearchPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("org/jphototagger/program/module/search/Bundle"); // NOI18N
setTitle(bundle.getString("AdvancedSearchDialog.title")); // NOI18N
setName("Form"); // NOI18N
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
panel.setName("panel"); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, 595, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}//GEN-END:initComponents
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
beforeWindowClosing();
}//GEN-LAST:event_formWindowClosing
// Variables declaration - do not modify//GEN-BEGIN:variables
private org.jphototagger.program.module.search.AdvancedSearchPanel panel;
// End of variables declaration//GEN-END:variables
}
|
package com.heihei.model.msg.bean;
public class TextMessage extends AbstractTextMessage {
public int giftId;
public TextMessage(String userId, String userName, String text, int gender, String converUrl, String roomId, String liveId, int giftId) {
super(userId, userName, text, MESSAGE_TYPE_TEXT, gender, converUrl, roomId, liveId);
this.giftId = giftId;
}
public TextMessage(String userId, String userName, String text, int gender, int giftId) {
super(userId, userName, text, MESSAGE_TYPE_TEXT, gender);
this.giftId = giftId;
}
}
|
package com.beike.entity.miaosha;
import java.io.Serializable;
import java.sql.Timestamp;
/**
* project:beiker
* Title:秒杀
* Description:
* Copyright:Copyright (c) 2012
* Company:Sinobo
* @author qiaowb
* @date Jul 31, 2012 3:16:39 PM
* @version 1.0
*/
public class MiaoSha implements Serializable {
private static final long serialVersionUID = 102183800755795752L;
//秒杀ID
private Long msId;
//商品ID
private Long goodsId;
//秒杀商品标题
private String msTitle;
//短标题
private String msShortTitle;
//秒杀价
private double msPayPrice;
//秒杀库存
private int msMaxCount;
//秒杀个人限购数
private int msSingleCount;
//秒杀开始时间
private Timestamp msStartTime;
//秒杀结束时间
private Timestamp msEndTime;
//秒杀显示开始时间
private Timestamp msShowStartTime;
//秒杀显示结束时间
private Timestamp msShowEndTime;
//秒杀banner图片路径
private String msBanner;
//秒杀状态 0结束 1进行中 2即将开始
private int msStatus;
//秒杀虚拟销量
private int msVirtualCount;
//秒杀结算价
private double msSettlePrice;
//商品价格
private double goodsCurrentPrice;
//商品图片
private String goodsLogo;
//购买人数
private int msSaleCount;
//距离开始秒数
private Long startSeconds;
//距离结束秒数
private Long endSeconds;
//是否需要虚拟销量(1:是 0:否)
private int needVirtual;
public Long getMsId() {
return msId;
}
public void setMsId(Long msId) {
this.msId = msId;
}
public Long getGoodsId() {
return goodsId;
}
public void setGoodsId(Long goodsId) {
this.goodsId = goodsId;
}
public String getMsTitle() {
return msTitle;
}
public void setMsTitle(String msTitle) {
this.msTitle = msTitle;
}
public String getMsShortTitle() {
return msShortTitle;
}
public void setMsShortTitle(String msShortTitle) {
this.msShortTitle = msShortTitle;
}
public double getMsPayPrice() {
return msPayPrice;
}
public void setMsPayPrice(double msPayPrice) {
this.msPayPrice = msPayPrice;
}
public int getMsMaxCount() {
return msMaxCount;
}
public void setMsMaxCount(int msMaxCount) {
this.msMaxCount = msMaxCount;
}
public int getMsSingleCount() {
return msSingleCount;
}
public void setMsSingleCount(int msSingleCount) {
this.msSingleCount = msSingleCount;
}
public Timestamp getMsStartTime() {
return msStartTime;
}
public void setMsStartTime(Timestamp msStartTime) {
this.msStartTime = msStartTime;
}
public Timestamp getMsEndTime() {
return msEndTime;
}
public void setMsEndTime(Timestamp msEndTime) {
this.msEndTime = msEndTime;
}
public Timestamp getMsShowStartTime() {
return msShowStartTime;
}
public void setMsShowStartTime(Timestamp msShowStartTime) {
this.msShowStartTime = msShowStartTime;
}
public Timestamp getMsShowEndTime() {
return msShowEndTime;
}
public void setMsShowEndTime(Timestamp msShowEndTime) {
this.msShowEndTime = msShowEndTime;
}
public String getMsBanner() {
return msBanner;
}
public void setMsBanner(String msBanner) {
this.msBanner = msBanner;
}
public int getMsStatus() {
return msStatus;
}
public void setMsStatus(int msStatus) {
this.msStatus = msStatus;
}
public int getMsVirtualCount() {
return msVirtualCount;
}
public void setMsVirtualCount(int msVirtualCount) {
this.msVirtualCount = msVirtualCount;
}
public double getMsSettlePrice() {
return msSettlePrice;
}
public void setMsSettlePrice(double msSettlePrice) {
this.msSettlePrice = msSettlePrice;
}
public double getGoodsCurrentPrice() {
return goodsCurrentPrice;
}
public void setGoodsCurrentPrice(double goodsCurrentPrice) {
this.goodsCurrentPrice = goodsCurrentPrice;
}
public String getGoodsLogo() {
return goodsLogo;
}
public void setGoodsLogo(String goodsLogo) {
this.goodsLogo = goodsLogo;
}
public int getMsSaleCount() {
return msSaleCount;
}
public void setMsSaleCount(int msSaleCount) {
this.msSaleCount = msSaleCount;
}
public Long getStartSeconds() {
return startSeconds;
}
public void setStartSeconds(Long startSeconds) {
this.startSeconds = startSeconds;
}
public Long getEndSeconds() {
return endSeconds;
}
public void setEndSeconds(Long endSeconds) {
this.endSeconds = endSeconds;
}
public int getNeedVirtual() {
return needVirtual;
}
public void setNeedVirtual(int needVirtual) {
this.needVirtual = needVirtual;
}
}
|
package com.wrathOfLoD.Utility;
/**
* Created by zach on 4/17/16.
*/
public class FileExtensionExtractor {
public static String getFileExtension(String fileName) {
String ext = "";
int i = fileName.lastIndexOf('.');
if (i >= 0)
ext = fileName.substring(i+1);
return ext;
}
}
|
package py.edu.unican.facitec.formulario;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Panel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class formDeuda extends JDialog {
private JPanel contentPane;
private JTextField TfNroDeuda;
private JTextField TfNroEstadia;
private JTextField TfCodCliente;
private JTextField TfMontoDeuda;
private JTextField TfMontoPagado;
private JButton btnNuevo;
private JButton btnModificar;
private JButton btnEliminar;
private JButton btnDetalle;
private JButton btnCierre;
private JButton btnGuardar;
private JButton btnCancelar;
private JButton btnSalir;
private JLabel lblBuscar;
private JTextField tfBuscar;
private Panel panel;
private JScrollPane scrollPane;
private JTable tableDeuda;
public formDeuda() {
setTitle("Deuda");
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setBounds(100, 100, 794, 541);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
btnNuevo = new JButton("Nuevo");
btnNuevo.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnNuevo.setBounds(332, 47, 89, 32);
contentPane.add(btnNuevo);
btnModificar = new JButton("Modificar");
btnModificar.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnModificar.setBounds(332, 124, 89, 32);
contentPane.add(btnModificar);
btnEliminar = new JButton("Eliminar");
btnEliminar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnEliminar.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnEliminar.setBounds(332, 197, 89, 32);
contentPane.add(btnEliminar);
btnDetalle = new JButton("Detalle");
btnDetalle.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnDetalle.setBounds(332, 259, 89, 32);
contentPane.add(btnDetalle);
btnCierre = new JButton("Cierre");
btnCierre.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnCierre.setBounds(332, 321, 89, 34);
contentPane.add(btnCierre);
btnGuardar = new JButton("Guardar");
btnGuardar.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnGuardar.setBounds(435, 408, 89, 30);
contentPane.add(btnGuardar);
btnCancelar = new JButton("Cancelar");
btnCancelar.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnCancelar.setBounds(550, 408, 89, 30);
contentPane.add(btnCancelar);
btnSalir = new JButton("Salir");
btnSalir.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnSalir.setBounds(649, 408, 99, 30);
contentPane.add(btnSalir);
lblBuscar = new JLabel("Buscar");
lblBuscar.setFont(new Font("Tahoma", Font.PLAIN, 14));
lblBuscar.setBounds(26, 410, 46, 20);
contentPane.add(lblBuscar);
tfBuscar = new JTextField();
tfBuscar.setColumns(10);
tfBuscar.setBounds(78, 406, 245, 32);
contentPane.add(tfBuscar);
panel = new Panel();
panel.setLayout(null);
panel.setBounds(435, 33, 333, 344);
contentPane.add(panel);
JLabel lblNroDeuda = new JLabel("Nro. Deuda");
lblNroDeuda.setBounds(19, 11, 103, 26);
panel.add(lblNroDeuda);
lblNroDeuda.setFont(new Font("Tahoma", Font.PLAIN, 14));
TfNroDeuda = new JTextField();
TfNroDeuda.setBounds(132, 16, 191, 26);
panel.add(TfNroDeuda);
TfNroDeuda.setColumns(10);
TfNroEstadia = new JTextField();
TfNroEstadia.setBounds(132, 75, 191, 31);
panel.add(TfNroEstadia);
TfNroEstadia.setColumns(10);
JLabel lblNroEstadia = new JLabel("Nro. Estad\u00EDa");
lblNroEstadia.setBounds(19, 70, 87, 26);
panel.add(lblNroEstadia);
lblNroEstadia.setFont(new Font("Tahoma", Font.PLAIN, 14));
JLabel lblCodigoCliente = new JLabel("C\u00F3digo Cliente");
lblCodigoCliente.setBounds(19, 125, 103, 26);
panel.add(lblCodigoCliente);
lblCodigoCliente.setFont(new Font("Tahoma", Font.PLAIN, 14));
TfCodCliente = new JTextField();
TfCodCliente.setBounds(132, 130, 191, 31);
panel.add(TfCodCliente);
TfCodCliente.setColumns(10);
JLabel lblMontoDeuda = new JLabel("Monto Deuda");
lblMontoDeuda.setBounds(19, 183, 87, 26);
panel.add(lblMontoDeuda);
lblMontoDeuda.setFont(new Font("Tahoma", Font.PLAIN, 14));
TfMontoDeuda = new JTextField();
TfMontoDeuda.setBounds(132, 183, 191, 31);
panel.add(TfMontoDeuda);
TfMontoDeuda.setColumns(10);
TfMontoPagado = new JTextField();
TfMontoPagado.setBounds(132, 237, 191, 31);
panel.add(TfMontoPagado);
TfMontoPagado.setColumns(10);
JLabel lblMontoPagado = new JLabel("Monto Pagado");
lblMontoPagado.setBounds(19, 237, 103, 26);
panel.add(lblMontoPagado);
lblMontoPagado.setFont(new Font("Tahoma", Font.PLAIN, 14));
scrollPane = new JScrollPane();
scrollPane.setBounds(297, 11, -285, 330);
contentPane.add(scrollPane);
tableDeuda = new JTable();
tableDeuda.setBounds(11, 25, 311, 370);
contentPane.add(tableDeuda);
}
}
|
package io.nuls.provider.api.resources;
import io.nuls.base.api.provider.Result;
import io.nuls.base.api.provider.ServiceManager;
import io.nuls.base.api.provider.network.NetworkProvider;
import io.nuls.base.api.provider.network.facade.NetworkInfo;
import io.nuls.core.constant.CommonCodeConstanst;
import io.nuls.core.core.annotation.Component;
import io.nuls.core.core.annotation.Controller;
import io.nuls.core.core.annotation.RpcMethod;
import io.nuls.provider.model.jsonrpc.RpcResult;
import io.nuls.v2.model.annotation.Api;
import io.nuls.v2.model.annotation.ApiOperation;
import io.nuls.v2.model.annotation.ApiType;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
/**
* @Author: zhoulijun
* @Time: 2020-06-03 17:40
* @Description: 功能描述
*/
@Path("/api/network")
@Component
@Api
public class NetworkResource {
NetworkProvider networkProvider = ServiceManager.get(NetworkProvider.class);
@GET
@Path("/info")
@Produces(MediaType.APPLICATION_JSON)
public RpcResult info() {
Result<NetworkInfo> result = networkProvider.getInfo();
if (result.isFailed()) {
return RpcResult.failed(CommonCodeConstanst.FAILED, result.getMessage());
}
return RpcResult.success(result.getData());
}
@GET
@Path("/nodes")
@Produces(MediaType.APPLICATION_JSON)
public RpcResult nodes() {
Result<String> result = networkProvider.getNodes();
if (result.isFailed()) {
return RpcResult.failed(CommonCodeConstanst.FAILED, result.getMessage());
}
return RpcResult.success(result.getList());
}
@GET
@Path("/ip")
@Produces(MediaType.APPLICATION_JSON)
public RpcResult ip() {
Result<String> result = networkProvider.getNodeExtranetIp();
if (result.isFailed()) {
return RpcResult.failed(CommonCodeConstanst.FAILED, result.getMessage());
}
return RpcResult.success(result.getData());
}
}
|
package com.netcracker.app.domain.info.repositories.resumes;
import com.netcracker.app.domain.info.entities.resumes.Resume;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.NoRepositoryBean;
@NoRepositoryBean
public interface ResumeRepository<E extends Resume> extends JpaRepository<E, Integer> {
}
|
package com.culturaloffers.maps.repositories;
import com.culturaloffers.maps.model.Guest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface GuestRepository extends JpaRepository<Guest, Integer> {
Guest findByUsername(String username);
Guest findByEmailAddress(String emailAddress);
Page<Guest> findAll(Pageable pageable);
} |
package com.company.recursionanddynamic;
import sun.security.krb5.internal.PAData;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RobotGrid {
/*
Cracking the coding interview Question 8.2
------------------------------------------
Imagine a robot sitting on the upper left corner of a grid with r rows
and c columns. The robot can only move in two directions, right and down,
but certain cells are "off limits" such that the robot cannot step on them.
Design and algorithm to find a path for the robot from top left to the
bottom right.
*/
/*
Consider grid:
0 X 0
0 0 x
0 0 E
Right solution(s): down, right, down, right
down , down, right, right
Not sure if we need to find most efficient version of the path.
Seems like we could find this through recursion. Going right will increase
our minimum value of r, and and going down will increase minimum value of
c.
Base case:
left or down is the end of the matrix - return direction.
left and down are both blocked or outside of bounds - return null;
left or down is open and not the end return direction + recursive call
of next direction
*/
public static Path robotGridPath(char[][] grid){
Path path = new Path(new ArrayList<Character>());
if(grid.length==1 && grid[0].length == 1){
/*
i.e. if we have [ [ E ] ] we start at the END, so just do nothing
*/
path.pathDown.add('E');
return path;
}
path = robotGridPath_(grid, path, 0, 0);
if(path.toEnd){
path.pathDown.add('E');
}
return path;
}
public static Path robotGridPath_(char[][] grid, Path path, int row, int col){
if(grid.length==row+1 && grid[0].length == col+1){
path.toEnd=true;
return path;
}
Path downPath = null;
Path rightPath = null;
if(row + 1 < grid.length){
if(grid[row+1][col] != 'X') {
downPath = robotGridPath_(grid, new Path(path, 'd'), row + 1, col);
}
}
if(col + 1 < grid[0].length){
if(grid[row][col+1] != 'X') {
rightPath = robotGridPath_(grid, new Path(path, 'r'), row, col + 1);
}
}
if(downPath!=null && downPath.toEnd){
return downPath;
}
if(rightPath!=null && rightPath.toEnd){
return rightPath;
}
return null;
}
public static class Path{
List<Character> pathDown;
Boolean toEnd;
Path(List<Character> pathDown){
this.pathDown = pathDown;
}
Path(Path p, Character direction){
if(p != null){
this.pathDown = new ArrayList<>();
this.pathDown.addAll(p.pathDown);
}
else{
this.pathDown = new ArrayList<>();
}
this.pathDown.add(direction);
}
}
public static List<Point> robotPath(boolean[][] grid){
if(grid == null || grid.length == 0){
return null;
}
Set<Point> visited = new HashSet<>();
List<Point> path = new ArrayList<>();
if(hasPath(grid,grid.length-1,grid[0].length-1,visited,path)){
return path;
}
return null;
}
public static boolean hasPath(boolean[][] grid, int row, int col, Set<Point> visited,List<Point> path){
if(row < 0 || col < 0 || grid[row][col]){ return false;}
boolean atOrigin = (row==0) && (col==0);
Point currentPoint = new Point(row,col);
if(atOrigin
|| hasPath(grid,row-1, col,visited,path)
|| hasPath(grid,row, col-1,visited,path)){
path.add(currentPoint);
visited.add(currentPoint);
return true;
}
else{
visited.add(currentPoint);
return false;
}
}
public static class Point{
int row;
int column;
Point(int row, int column){
this.row = row;
this.column = column;
}
}
}
|
package view;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;
import model.Board;
/**
* ScorePanel class is a panel on the Main Gui
* that listens to the amount of lines cleared and
* calculates the current score.
*
* @author Lindsee Purnell
* @version Tetris1.0
*/
public class ScorePanel extends JPanel implements Observer {
/** Generated ID. */
private static final long serialVersionUID = 6535364451262812255L;
/** Magic number 4. */
private static final int FOUR = 4;
/** Magic number 2. */
private static final int TWO = 2;
/** Magic number 100. */
private static final int ONE_HUNDRED = 100;
/** Magic number 200. */
private static final int TWO_HUNDRED = 200;
/** The default size for this JPanel. */
private static final Dimension DEFAULT_SIZE = new Dimension(300, 400);
/** Background Color of GUI and Panels. */
private static final Color DARK_PURPLE = new Color(28, 0, 38);
/** Border Color. */
private static final Color WHITE = new Color(255, 255, 255);
/** Font size. */
private static final int FONT_SIZE = 12;
/** Default font used. */
private final Font myFont = new Font("Monospace", Font.BOLD, FONT_SIZE);
/** Empty border for padding. */
private final Border myEmptyBorder = BorderFactory.createEmptyBorder(10, 10, 10, 10);
/** Line Border. */
private final Border myLineBorder = BorderFactory.createLineBorder(WHITE, 3);
/** Title Border. */
private final TitledBorder myTitleBorder = BorderFactory.createTitledBorder(myLineBorder,
" Score: ", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.CENTER);
/** Integer variable to hold score. */
private int myScore;
/**
* Constructor of score panel holds and explains score.
*/
public ScorePanel() {
super();
setPreferredSize(DEFAULT_SIZE);
setBackground(DARK_PURPLE);
setVisible(true);
myTitleBorder.setTitleColor(WHITE);
myTitleBorder.setTitleFont(myFont);
setBorder(BorderFactory.createCompoundBorder(myEmptyBorder, myTitleBorder));
myScore = 0;
}
/** Paints the current score and score algorithm. */
@Override
public void paintComponent(final Graphics theGraphics) {
super.paintComponent(theGraphics);
final Graphics2D g2d = (Graphics2D) theGraphics;
g2d.setFont(myFont);
g2d.setColor(WHITE);
g2d.drawString("Current Score: " + myScore, getWidth() / FOUR, getHeight() / TWO);
}
/** Holds the Integer array and passes it to calculate. */
@Override
public void update(final Observable theObs, final Object theArg) {
final ArrayList<Integer> integers = new ArrayList<>();
if (theObs instanceof Board) {
if (theArg instanceof Integer[]) {
final Integer[] arrayInts = (Integer[]) theArg;
for (int i = 0; i < arrayInts.length; i++) {
integers.add(i);
}
calculateScore(integers);
repaint();
}
}
}
/**
* Get the users Score.
*
* @return int myScore
*/
public int getScore() {
return myScore;
}
/**
* Private method to calculate the score based on lines cleared.
*
* @param theIntegers arraylist of lines cleared.
*/
private void calculateScore(final ArrayList<Integer> theIntegers) {
if (theIntegers.size() > 0) {
myScore = (theIntegers.size() * ONE_HUNDRED) + myScore;
if (theIntegers.size() == FOUR) {
myScore = (theIntegers.size() * TWO_HUNDRED) + myScore;
}
}
}
}
|
package com.unit.impl;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.unit.PropertyHandler;
public class PropertyHandlerImpl implements PropertyHandler {
@Override
public Map<String, Method> getSetterMethodsMap(Object obj) {
List<Method> methods = getSetterMethodList(obj);
Map<String,Method> result = new HashMap<String,Method>();
for(Method m:methods){
String propertyName = getMethodNameWithOutSet(m.getName());
result.put(propertyName, m);
}
return result;
}
/**
* 将set方法还原,返回属性名称
* @param Methodname
* @return
*/
private String getMethodNameWithOutSet(String Methodname) {
String propertyName = Methodname.replaceFirst("set", "");
String firstword = propertyName.substring(0, 1);
String lowerFirstWord = firstword.toLowerCase();
return propertyName.replaceFirst(firstword, lowerFirstWord);
}
/**
* 获得所有的setter方法
* @param obj
* @return
*/
private List<Method> getSetterMethodList(Object obj) {
Class clazz = obj.getClass();
Method[] methods = clazz.getMethods();
List<Method> result = new ArrayList<Method>();
for(Method m:methods){
if(m.getName().startsWith("set"));
result.add(m);
}
return result;
}
@Override
public void executeMethod(Object object, Object argBean, Method method) throws BeanCreateException {
//获取方法的参数类型
Class[] parameterTypes =method.getParameterTypes();
//如果参数数量不为1,则不执行该方法
try{
if(parameterTypes.length==1){
//判断参数类型是否一致
if(isMethodArgs(method,parameterTypes[0])){
method.invoke(object, argBean);
}
}
}catch(Exception e){
throw new BeanCreateException("autowire faild" + e.getMessage());
}
}
@Override
public Object setProperties(Object obj, Map<String, Object> properties)
throws NoSuchMethodException {
// 获得参数obj对应的类类型
Class clazz = obj.getClass();
try {
for (String key : properties.keySet()) {
// 获得方法名
String setterName = getSetterMethodName(key);
// 获得参数类型
Class argClass = getClass(properties.get(key));
// 获得set方法的对象
Method setterMethod = getSetterMethod(clazz, setterName,
argClass);
// 通过反射调用对应的set()方法
setterMethod.invoke(obj, properties.get(key));
}
return obj;
} catch (Exception e) {
return null;
}
}
/**
* 得到setter方法的Method对象
*
* @param clazz
* @param setterName
* @param argClass
* @return
* @throws NoSuchMethodException
*/
private Method getSetterMethod(Class clazz, String setterName,
Class argClass) throws NoSuchMethodException {
Method argClassMethod = getMethod(clazz, setterName, argClass);
if (argClassMethod == null) {
List<Method> methods = getMethods(clazz, setterName);
Method method = findMethod(clazz, methods);
if (method == null) {
throw new NoSuchMethodException(setterName);
}
return method;
} else
return argClassMethod;
}
/**
* 遍历所有的方法,判断方法中的参数与argClass是否是同一类型
*
* @param clazz
* @param methods
* @return
*/
private Method findMethod(Class clazz, List<Method> methods) {
for (Method m : methods) {
// 判断参数类型与方法的参数类型是否一致
if (isMethodArgs(m, clazz)) {
return m;
}
}
return null;
}
/**
* 判断一个方法的参数类型是否与clazz类型一样,有可能clazz是方法参数类型的实现类型
*
* @param m
* @param clazz
* @return
*/
private boolean isMethodArgs(Method m, Class clazz) {
// 得到方法的所有参数类型
Class[] c = m.getParameterTypes();
// 如果方法的参数不是1个,则表示该方法不是我们需要的
if (c.length == 1) {
try {
// 将参数类型clazz,与方法中的参数类型进行强制转换,成功就返回true
clazz.asSubclass(c[0]);
return true;
} catch (ClassCastException e) {
return false;
}
}
return false;
}
/**
* 得到所有名字为setterName并且只有一个参数的方法
*
* @param clazz
* @param setterName
* @return
*/
private List<Method> getMethods(Class clazz, String setterName) {
List<Method> result = new ArrayList<Method>();
for (Method m : clazz.getMethods()) {
if (m.getName().equals(setterName)) {
Class[] c = m.getParameterTypes();
if (c.length == 1) {
result.add(m);
}
}
}
return result;
}
/**
* 根据方法名和参数类型获得方法,如果没有就返回null
*
* @param clazz
* @param setterName
* @param argClass
* @return
*/
private Method getMethod(Class clazz, String setterName, Class argClass) {
try {
Method method = clazz.getMethod(setterName, argClass);
return method;
} catch (NoSuchMethodException | SecurityException e) {
return null;
}
}
/**
* 返会对应的set()函数的函数全称
*
* @param propertyName
* @return
*/
private String getSetterMethodName(String propertyName) {
return "set" + upperCaseFirstWord(propertyName);
}
/**
* 将字符变为大写
*
* @param s
* @return
*/
private String upperCaseFirstWord(String s) {
String firstWord = s.substring(0, 1);
String UpperWord = firstWord.toUpperCase();
return s.replaceFirst(firstWord, UpperWord);
}
private Class getClass(Object obj) {
if (obj instanceof Integer) {
return Integer.TYPE;
} else if (obj instanceof Long) {
return Long.TYPE;
} else if (obj instanceof Boolean) {
return Boolean.TYPE;
} else if (obj instanceof Short) {
return Short.TYPE;
} else if (obj instanceof Double) {
return Double.TYPE;
} else if (obj instanceof Float) {
return Float.TYPE;
} else if (obj instanceof Character) {
return Character.TYPE;
} else if (obj instanceof Byte) {
return Byte.TYPE;
}
return obj.getClass();
}
}
|
package com.cg.osce.apibuilder.pojo;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"200",
"400",
"404",
"405"
})
public class Responses {
@JsonProperty("200")
private com.cg.osce.apibuilder.pojo.Response200 response200;
@JsonProperty("400")
private com.cg.osce.apibuilder.pojo.Response400 response400;
@JsonProperty("404")
private com.cg.osce.apibuilder.pojo.Response404 response404;
@JsonProperty("405")
private com.cg.osce.apibuilder.pojo.Response405 response405;
public com.cg.osce.apibuilder.pojo.Response200 getResponse200() {
return response200;
}
public void setResponse200(com.cg.osce.apibuilder.pojo.Response200 response200) {
this.response200 = response200;
}
public com.cg.osce.apibuilder.pojo.Response400 getResponse400() {
return response400;
}
public void setResponse400(com.cg.osce.apibuilder.pojo.Response400 response400) {
this.response400 = response400;
}
public com.cg.osce.apibuilder.pojo.Response404 getResponse404() {
return response404;
}
public void setResponse404(com.cg.osce.apibuilder.pojo.Response404 response404) {
this.response404 = response404;
}
public com.cg.osce.apibuilder.pojo.Response405 getResponse405() {
return response405;
}
public void setResponse405(com.cg.osce.apibuilder.pojo.Response405 response405) {
this.response405 = response405;
}
@JsonProperty("200")
public com.cg.osce.apibuilder.pojo.Response200 get200() {
return response200;
}
@JsonProperty("200")
public void set200(com.cg.osce.apibuilder.pojo.Response200 response200) {
this.response200 = response200;
}
@JsonProperty("400")
public com.cg.osce.apibuilder.pojo.Response400 get400() {
return response400;
}
@JsonProperty("400")
public void set400(com.cg.osce.apibuilder.pojo.Response400 response400) {
this.response400 = response400;
}
}
|
public class QuickSort {
static void sort(int[] arr, int low, int high) {
int mid = (high + low) / 2;
int pivot = arr[mid];
int l = low;
int r = high;
while(true) {
while(arr[pivot] < arr[l]) l++;
while(arr[pivot] > arr[r]) r--;
}
}
public static void main(String[] args) {
}
}
|
package com.spart.io.Controller;
import com.spart.io.Model.Employee;
import java.sql.Date;
public class DAODriver {
public static void main(String[] args) {
DAO obj = new CRUD();
Date dob= new Date(17/7/1998);
Date doj= new Date(20/8/2020);
Employee emp1=new Employee(133453,"Mr.","Halil","C","Kale","M","Halil@hotmail.co.uk",dob,doj,3432);
// obj.addNewEmployee(emp1); //testing adding new Employee
// obj.deleteEmployee(802800); //testing the delete Employee
// obj.getEmployee(emp1); //testing the get Employee
obj.updateEmployeeSalary(802800,500000); //testing updating an Employee's salary
}
}
|
package exception_handling;
import java.io.IOException;
import java.io.File;
public class Exception_Handling3
{
public static void main(String[] args)
{
try
{
File f=new File("C:\\Users\\vishal\\Documents\\java\\Demo.java");
System.out.println("file exist "+f.exists());
System.out.println("create new class "+f.createNewFile());
System.out.println("hello jio");
}
catch (IOException e) {
System.out.println("this is exception "+e.getMessage());
}
}
}
|
package com.splwg.cm.domain.batch;
import java.io.File;
import java.io.FilenameFilter;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.examples.CellTypes;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import com.splwg.base.api.batch.CommitEveryUnitStrategy;
import com.splwg.base.api.batch.JobWork;
import com.splwg.base.api.batch.RunAbortedException;
import com.splwg.base.api.batch.ThreadAbortedException;
import com.splwg.base.api.batch.ThreadExecutionStrategy;
import com.splwg.base.api.batch.ThreadWorkUnit;
import com.splwg.base.api.businessObject.BusinessObjectDispatcher;
import com.splwg.base.api.businessObject.BusinessObjectInstance;
import com.splwg.base.api.businessObject.COTSFieldDataAndMD;
import com.splwg.base.api.businessObject.COTSInstanceNode;
import com.splwg.base.api.datatypes.Date;
import com.splwg.cm.domain.common.businessComponent.CmPersonSearchComponent;
import com.splwg.cm.domain.common.businessComponent.CmXLSXReaderComponent;
import com.splwg.cm.domain.customMessages.CmMessageRepository90002;
import com.splwg.shared.logging.Logger;
import com.splwg.shared.logging.LoggerFactory;
import com.splwg.tax.domain.admin.cisDivision.CisDivision_Id;
import com.splwg.tax.domain.admin.formType.FormType;
import com.splwg.tax.domain.admin.formType.FormType_Id;
import com.splwg.tax.domain.admin.idType.IdType_Id;
import com.splwg.tax.domain.customerinfo.person.Person;
import com.splwg.base.api.datatypes.Lookup;
import com.splwg.base.domain.common.businessObject.BusinessObject_Id;
import com.splwg.base.domain.common.extendedLookupValue.ExtendedLookupValue_Id;
/**
* @author CISSYS
*
@BatchJob (modules = { },
* softParameters = { @BatchJobSoftParameter (name = formType, required = true, type = string)
* , @BatchJobSoftParameter (name = filePaths, required = true, type = string)})
*/
public class CmProcessRegistrationExcelFileBatch extends CmProcessRegistrationExcelFileBatch_Gen {
@Override
public void validateSoftParameters(boolean isNewRun) {
System.out.println("File path"+this.getParameters().getFilePaths());
System.out.println("Form Type"+this.getParameters().getFormType());
}
private final static int EMPLOYER_UNIQUE_ID_ROW = 1;
private final static int EMPLOYER_UNIQUE_ID_CELL = 2;
private final static Logger log = LoggerFactory.getLogger(CmProcessRegistrationExcelFileBatch.class);
// private File[] getNewTextFiles() {
// File dir = new File(this.getParameters().getFilePaths());
// return dir.listFiles(new FilenameFilter() {
// @Override
// public boolean accept(File dir, String name) {
// return name.toLowerCase().endsWith(".xlsx");
// }
// });
// }
public JobWork getJobWork() {
log.info("*****Starting getJobWork");
System.out.println("######################## Demarrage JobWorker ############################");
ArrayList<ThreadWorkUnit> list = new ArrayList<ThreadWorkUnit>();
// File[] files = this.getNewTextFiles();
//String a = this.getParameters().getFilePath();
// for (File file : files) {
// if (file.isFile()) {
ThreadWorkUnit unit = new ThreadWorkUnit();
// A unit must be created for every file in the path, this will represent a row to be processed.
unit.addSupplementalData("fileName", this.getParameters().getFilePaths());
list.add(unit);
log.info("***** getJobWork ::::: " + this.getParameters().getFilePaths());
// }
// }
JobWork jobWork = createJobWorkForThreadWorkUnitList(list);
System.out.println("######################## Terminer JobWorker ############################");
return jobWork;
}
public Class<CmProcessRegistrationExcelFileBatchWorker> getThreadWorkerClass() {
return CmProcessRegistrationExcelFileBatchWorker.class;
}
public static class CmProcessRegistrationExcelFileBatchWorker extends CmProcessRegistrationExcelFileBatchWorker_Gen {
private CmXLSXReaderComponent cmXLSXReader = CmXLSXReaderComponent.Factory.newInstance();
private Person employerPer;
XSSFSheet spreadsheet;
private int cellId = 0;
// CisDivision_Id cisDivisionId = new CisDivision_Id("SNSS");
public ThreadExecutionStrategy createExecutionStrategy() {
return new CommitEveryUnitStrategy(this);
}
@Override
public void initializeThreadWork(boolean initializationPreviouslySuccessful)
throws ThreadAbortedException, RunAbortedException {
log.info("*****initializeThreadWork");
}
private Person getPersonId(String idNumber, String IdType){
log.info("*****Starting getpersonId");
CmPersonSearchComponent perSearch = new CmPersonSearchComponent.Factory().newInstance();
IdType_Id idType = new IdType_Id(IdType);
log.info("*****ID Type: " + idType.getTrimmedValue());
return perSearch.searchPerson(idType.getEntity(), idNumber);
}
private BusinessObjectInstance createFormBOInstance(String formTypeString, String documentLocator) {
FormType formType = new FormType_Id(formTypeString).getEntity();
String formTypeBo = formType.getRelatedTransactionBOId().getTrimmedValue();
log.info("#### Creating BO for " + formType);
BusinessObjectInstance boInstance = BusinessObjectInstance.create(formTypeBo);
log.info("#### Form Type BO MD Schema: " + boInstance.getSchemaMD());
boInstance.set("bo", formTypeBo);
boInstance.set("formType", formType.getId().getTrimmedValue());
boInstance.set("receiveDate", getSystemDateTime().getDate());
boInstance.set("documentLocator", documentLocator);
return boInstance;
}
@SuppressWarnings("unchecked")
public void formCreator(String fileName,List<Object> valeurs) {
BusinessObjectInstance boInstance = null;
boInstance = createFormBOInstance(this.getParameters().getFormType() ,"T-DNSU-" + getSystemDateTime().toString());
COTSInstanceNode employerQuery = boInstance.getGroup("employerQuery");
COTSInstanceNode mainRegistrationForm = boInstance.getGroup("mainRegistrationForm");
/* COTSInstanceNode mainRegistrationForm = boInstance.getGroup("mainRegistrationForm");
COTSInstanceNode legalForm = boInstance.getGroup("legalForm");
COTSInstanceNode legalRepresentativeForm = boInstance.getGroup("legalRepresentativeForm");
COTSInstanceNode personContactForm = boInstance.getGroup("personContactForm");
COTSInstanceNode bankInformationForm = boInstance.getGroup("bankInformationForm");
// COTSInstanceNode documentsForm = boInstance.getGroup("documentsForm");
COTSInstanceNode employerStatus = boInstance.getGroup("employerStatus");
COTSInstanceNode employeeRegistrationForm = boInstance.getGroup("employeeRegistrationForm");*/
/* boInstance.set("", new Lookup(new BusinessObjectInstance(info, w3cElement)));
boInstance = BusinessObjectDispatcher.execute(instance);*/
employerQuery.getGroupFromPath("regType").set("asCurrent",
new ExtendedLookupValue_Id(new BusinessObject_Id("CmRegistrationType"), valeurs.get(0).toString()));//cmRegistrationType-javaname
employerQuery.getGroupFromPath("employerType").set("asCurrent",
new ExtendedLookupValue_Id(new BusinessObject_Id("CmEmployerType"), valeurs.get(1).toString()));//cmRegistrationType-javaname
//employerQuery.getGroupFromPath("employerType").set("asCurrent",valeurs.get(1).toString());//cmEmployerType-javaname
//COTSFieldDataAndMD<Character> employerType = employerQuery.getFieldAndMDForPath("employerType/asCurrent");
// employerType.setValue((Character)valeurs.get(1));
employerQuery.getGroupFromPath("estType").set("asCurrent",
new ExtendedLookupValue_Id(new BusinessObject_Id("CmEstablishmentType"), valeurs.get(2).toString()));//cmEstablishmentType-javaname
/*COTSFieldDataAndMD<Character> estType = employerQuery.getFieldAndMDForPath("estType/asCurrent");
estType.setValue((Character)valeurs.get(2));*/
/*BigDecimal bd = new BigDecimal(valeurs.get(3).toString());
employerQuery.getGroupFromPath("nineaNumber").set("asCurrent", "");*/
employerQuery.getGroupFromPath("nineaNumber").set("asCurrent",
new com.ibm.icu.math.BigDecimal(valeurs.get(3).toString()));
/* COTSFieldDataAndMD<?> nineaNumber = employerQuery.getFieldAndMDForPath("nineaNumber/asCurrent");
nineaNumber.setXMLValue(valeurs.get(3).toString());*/
employerQuery.getGroupFromPath("ninetNumber").set("asCurrent",
new com.ibm.icu.math.BigDecimal(valeurs.get(4).toString()));
/*COTSFieldDataAndMD<?> ninetNumber = employerQuery.getFieldAndMDForPath("ninetNumber/asCurrent");
ninetNumber.setXMLValue(valeurs.get(4).toString());*/
employerQuery.getGroupFromPath("hqId").set("asCurrent", valeurs.get(5).toString());
/*COTSFieldDataAndMD<Character> hqId = employerQuery.getFieldAndMDForPath("hqId/asCurrent");
hqId.setValue((Character)valeurs.get(5));*/
employerQuery.getGroupFromPath("companyOriginId").set("asCurrent", valeurs.get(6).toString());
/*COTSFieldDataAndMD<Character> companyOriginId = employerQuery.getFieldAndMDForPath("companyOriginId/asCurrent");
companyOriginId.setValue((Character)valeurs.get(6));*/
employerQuery.getGroupFromPath("taxId").set("asCurrent",
new com.ibm.icu.math.BigDecimal(valeurs.get(7).toString()));
/*COTSFieldDataAndMD<?> taxId = employerQuery.getFieldAndMDForPath("taxId/asCurrent");
taxId.setXMLValue(valeurs.get(4).toString());*/
//employerQuery.getGroupFromPath("taxIdDate").set("asCurrent", new Date(year, month, day));
String txnDate = getDateString(valeurs.get(8).toString());
COTSFieldDataAndMD<?> taxIdDate = employerQuery.getFieldAndMDForPath("taxIdDate/asCurrent");
taxIdDate.setXMLValue(txnDate);
employerQuery.getGroupFromPath("tradeRegisterNumber").set("asCurrent",
new com.ibm.icu.math.BigDecimal(valeurs.get(9).toString()));
/* COTSFieldDataAndMD<?> tradeRegisterNumber = employerQuery.getFieldAndMDForPath("tradeRegisterNumber/asCurrent");
tradeRegisterNumber.setXMLValue(valeurs.get(9).toString());*/
//employerQuery.getGroupFromPath("tradeRegisterDate").set("asCurrent", (Date)valeurs.get(10));
String tradeDate = getDateString(valeurs.get(10).toString());
COTSFieldDataAndMD<?> tradeRegisterDate = employerQuery.getFieldAndMDForPath("tradeRegisterDate/asCurrent");
tradeRegisterDate.setXMLValue(tradeDate);
//******Main Registration Form BO Creation
mainRegistrationForm.getGroupFromPath("employerName").set("asCurrent", (String)valeurs.get(11));
// COTSFieldDataAndMD<Character> employerName = employerQuery.getFieldAndMDForPath("employerName/asCurrent");
// employerName.setValue((Character)valeurs.get(11));
mainRegistrationForm.getGroupFromPath("shortName").set("asCurrent", (String)valeurs.get(12));
/*COTSFieldDataAndMD<Character> shortName = employerQuery.getFieldAndMDForPath("shortName/asCurrent");
shortName.setValue((Character)valeurs.get(12));*/
String submissionDate = getDateString(valeurs.get(13).toString());
COTSFieldDataAndMD<?> dateOfSubmission = mainRegistrationForm.getFieldAndMDForPath("dateOfSubmission/asCurrent");
dateOfSubmission.setXMLValue(submissionDate);
mainRegistrationForm.getGroupFromPath("region").set("asCurrent",
new ExtendedLookupValue_Id(new BusinessObject_Id("CmRegion"), valeurs.get(14).toString()));
/*COTSFieldDataAndMD<Character> region = employerQuery.getFieldAndMDForPath("region/asCurrent");
region.setValue((Character)valeurs.get(14));*/
String inspectionDate = getDateString(valeurs.get(15).toString());
COTSFieldDataAndMD<?> dateOfInspection = mainRegistrationForm.getFieldAndMDForPath("dateOfInspection/asCurrent");
dateOfInspection.setXMLValue(inspectionDate);
mainRegistrationForm.getGroupFromPath("department").set("asCurrent",
new ExtendedLookupValue_Id(new BusinessObject_Id("CmDepartement"), valeurs.get(16).toString()));
/*COTSFieldDataAndMD<Character> department = mainRegistrationForm.getFieldAndMDForPath("department/asCurrent");
department.setValue((Character)valeurs.get(16));*/
mainRegistrationForm.getGroupFromPath("city").set("asCurrent",
new ExtendedLookupValue_Id(new BusinessObject_Id("CmCity"), valeurs.get(17).toString()));
/* COTSFieldDataAndMD<Character> city = mainRegistrationForm.getFieldAndMDForPath("city/asCurrent");
city.setValue((Character)valeurs.get(17));*/
String firstHireDate = getDateString(valeurs.get(18).toString());
COTSFieldDataAndMD<?> dateOfFirstHire = mainRegistrationForm.getFieldAndMDForPath("dateOfFirstHire/asCurrent");
dateOfFirstHire.setXMLValue(firstHireDate);
mainRegistrationForm.getGroupFromPath("district").set("asCurrent",
new ExtendedLookupValue_Id(new BusinessObject_Id("CmDistrict"), valeurs.get(19).toString()));
/*COTSFieldDataAndMD<Character> district = mainRegistrationForm.getFieldAndMDForPath("district/asCurrent");
district.setValue((Character)valeurs.get(19));*/
String effectiveDate = getDateString(valeurs.get(20).toString());
COTSFieldDataAndMD<?> dateOfEffectiveMembership = mainRegistrationForm.getFieldAndMDForPath("dateOfEffectiveMembership/asCurrent");
dateOfEffectiveMembership.setXMLValue(effectiveDate);
mainRegistrationForm.getGroupFromPath("address").set("asCurrent", valeurs.get(21).toString());
/*COTSFieldDataAndMD<Character> address = mainRegistrationForm.getFieldAndMDForPath("address/asCurrent");
address.setValue((Character)valeurs.get(21));*/
String hiringFirstExecutiveDate = getDateString(valeurs.get(22).toString());
COTSFieldDataAndMD<?> dateOfHiringFirstExecutiveEmpl = mainRegistrationForm.getFieldAndMDForPath("dateOfHiringFirstExecutiveEmpl/asCurrent");
dateOfHiringFirstExecutiveEmpl.setXMLValue(hiringFirstExecutiveDate);
/* COTSFieldDataAndMD<Character> dateOfHiringFirstExecutiveEmpl = employerQuery.getFieldAndMDForPath("dateOfHiringFirstExecutiveEmpl/asCurrent");
dateOfHiringFirstExecutiveEmpl.setValue((Character)valeurs.get(22));
*/
mainRegistrationForm.getGroupFromPath("postbox").set("asCurrent", valeurs.get(23).toString());
/*
COTSFieldDataAndMD<?> postbox = mainRegistrationForm.getFieldAndMDForPath("postbox/asCurrent");
postbox.setXMLValue(valeurs.get(23).toString());*/
mainRegistrationForm.getGroupFromPath("businessSector").set("asCurrent",
new ExtendedLookupValue_Id(new BusinessObject_Id("CmBusinessSector"), valeurs.get(24).toString()));
/* COTSFieldDataAndMD<Character> businessSector = mainRegistrationForm.getFieldAndMDForPath("businessSector/asCurrent");
businessSector.setValue((Character)valeurs.get(24));*/
mainRegistrationForm.getGroupFromPath("atRate").set("asCurrent",
new com.ibm.icu.math.BigDecimal(valeurs.get(25).toString()));
/*COTSFieldDataAndMD<Number> atRate = mainRegistrationForm.getFieldAndMDForPath("atRate/asCurrent");
atRate.setValue((Number)valeurs.get(25));*/
mainRegistrationForm.getGroupFromPath("telephone").set("asCurrent", valeurs.get(26).toString());
/*COTSFieldDataAndMD<Character> telephone = mainRegistrationForm.getFieldAndMDForPath("telephone/asCurrent");
telephone.setValue((Character)valeurs.get(26)); */
mainRegistrationForm.getGroupFromPath("mainLineOfBusiness").set("asCurrent",
new ExtendedLookupValue_Id(new BusinessObject_Id("CmMainLine"), valeurs.get(27).toString()));
/* COTSFieldDataAndMD<Character> mainLineOfBusiness = mainRegistrationForm.getFieldAndMDForPath("mainLineOfBusiness/asCurrent");
mainLineOfBusiness.setValue((Character)valeurs.get(27));*/
mainRegistrationForm.getGroupFromPath("email").set("asCurrent", valeurs.get(28).toString());
/*COTSFieldDataAndMD<Character> email = mainRegistrationForm.getFieldAndMDForPath("email/asCurrent");
email.setValue((Character)valeurs.get(28));*/
mainRegistrationForm.getGroupFromPath("secondaryLineOfBusiness").set("asCurrent",
new ExtendedLookupValue_Id(new BusinessObject_Id("CmMainLine"), valeurs.get(29).toString()));
/*COTSFieldDataAndMD<Character> secondaryLineOfBusiness = mainRegistrationForm.getFieldAndMDForPath("secondaryLineOfBusiness/asCurrent");
secondaryLineOfBusiness.setValue((Character)valeurs.get(29));*/
mainRegistrationForm.getGroupFromPath("website").set("asCurrent", valeurs.get(30).toString());
/* COTSFieldDataAndMD<Character> website = mainRegistrationForm.getFieldAndMDForPath("website/asCurrent");
website.setValue((Character)valeurs.get(30));*/
mainRegistrationForm.getGroupFromPath("branchAgreement").set("asCurrent",
new ExtendedLookupValue_Id(new BusinessObject_Id("CmBranchAgreement"), valeurs.get(31).toString()));
/*COTSFieldDataAndMD<Character> branchAgreement = mainRegistrationForm.getFieldAndMDForPath("branchAgreement/asCurrent");//cmBranchAgreement
branchAgreement.setValue((Character)valeurs.get(31));*/
mainRegistrationForm.getGroupFromPath("sector").set("asCurrent", valeurs.get(32).toString());
/*COTSFieldDataAndMD<Character> sector = mainRegistrationForm.getFieldAndMDForPath("sector/asCurrent");
sector.setValue((Character)valeurs.get(32));*/
mainRegistrationForm.getGroupFromPath("paymentMethod").set("asCurrent",
new ExtendedLookupValue_Id(new BusinessObject_Id("CmPaymentMethod"), valeurs.get(33).toString()));
/* COTSFieldDataAndMD<Character> paymentMethod = mainRegistrationForm.getFieldAndMDForPath("paymentMethod/asCurrent");
paymentMethod.setValue((Character)valeurs.get(33));*/
mainRegistrationForm.getGroupFromPath("zone").set("asCurrent", valeurs.get(34).toString());
/*COTSFieldDataAndMD<Character> zone = mainRegistrationForm.getFieldAndMDForPath("zone/asCurrent");
zone.setValue((Character)valeurs.get(34));*/
mainRegistrationForm.getGroupFromPath("dnsDeclaration").set("asCurrent",
new ExtendedLookupValue_Id(new BusinessObject_Id("CmDnsDeclaration"), valeurs.get(35).toString()));
/* COTSFieldDataAndMD<Character> dnsDeclaration = mainRegistrationForm.getFieldAndMDForPath("dnsDeclaration/asCurrent");
dnsDeclaration.setValue((Character)valeurs.get(35));*/
mainRegistrationForm.getGroupFromPath("cssAgency").set("asCurrent", valeurs.get(36).toString());
/* COTSFieldDataAndMD<Character> cssAgency = mainRegistrationForm.getFieldAndMDForPath("cssAgency/asCurrent");
cssAgency.setValue((Character)valeurs.get(36));*/
mainRegistrationForm.getGroupFromPath("noOfWorkersInGenScheme").set("asCurrent", valeurs.get(37).toString());
/*COTSFieldDataAndMD<Character> noOfWorkersInGenScheme = mainRegistrationForm.getFieldAndMDForPath("noOfWorkersInGenScheme/asCurrent");
noOfWorkersInGenScheme.setValue((Character)valeurs.get(37));*/
mainRegistrationForm.getGroupFromPath("ipresAgency").set("asCurrent", valeurs.get(38).toString());
/*COTSFieldDataAndMD<Character> ipresAgency = mainRegistrationForm.getFieldAndMDForPath("ipresAgency/asCurrent");
ipresAgency.setValue((Character)valeurs.get(38));*/
mainRegistrationForm.getGroupFromPath("noOfWorkersInBasicScheme").set("asCurrent",
new com.ibm.icu.math.BigDecimal(valeurs.get(39).toString()));
/*COTSFieldDataAndMD<Character> noOfWorkersInBasicScheme = mainRegistrationForm.getFieldAndMDForPath("noOfWorkersInBasicScheme/asCurrent");
noOfWorkersInBasicScheme.setValue((Character)valeurs.get(39));*/
mainRegistrationForm.getGroupFromPath("legalStatus").set("asCurrent",
new ExtendedLookupValue_Id(new BusinessObject_Id("CmLegalStatus"), valeurs.get(40).toString()));
/* COTSFieldDataAndMD<Character> legalStatus = mainRegistrationForm.getFieldAndMDForPath("legalStatus/asCurrent");
legalStatus.setValue((Character)valeurs.get(40));*/
String custStartDate = getDateString(valeurs.get(41).toString());
COTSFieldDataAndMD<?> startDate = mainRegistrationForm.getFieldAndMDForPath("startDate/asCurrent");
startDate.setXMLValue(custStartDate);
/*COTSFieldDataAndMD<Character> startDate = mainRegistrationForm.getFieldAndMDForPath("startDate/asCurrent");
startDate.setValue((Character)valeurs.get(41));
*/
/* COTSFieldDataAndMD<Character> dateOfHiringFirstExecutiveEmpl = employerQuery.getFieldAndMDForPath("dateOfHiringFirstExecutiveEmpl/asCurrent");
dateOfHiringFirstExecutiveEmpl.setValue((Character)valeurs.get(43));
for(int i=0; i<10; i++){
COTSFieldDataAndMD<?> dateOfHiringFirstExecutiveEmpl = employerQuery.getFieldAndMDForPath("dateOfHiringFirstExecutiveEmpl/asCurrent");
dateOfHiringFirstExecutiveEmpl.setValue(valeurs.get(44));
}
COTSFieldDataAndMD<Character> dateOfHiringFirstExecutiveEmpl = employerQuery.getFieldAndMDForPath("dateOfHiringFirstExecutiveEmpl/asCurrent");
dateOfHiringFirstExecutiveEmpl.setValue((Character)valeurs.get(44));*/
if (boInstance != null) {
boInstance = validateAndPostForm(boInstance);
}
}
private String getDateString(String dateObject) {
String parsedDate = "";
try {
String appDate = dateObject;
DateFormat inputFormat = new SimpleDateFormat("E MMM dd HH:mm:ss 'GMT' yyyy");
java.util.Date date = inputFormat.parse(appDate);
DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
//outputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
parsedDate = outputFormat.format(date);
System.out.println(parsedDate);
} catch(Exception exception) {
exception.printStackTrace();
}
return parsedDate;
}
private BusinessObjectInstance validateAndPostForm(BusinessObjectInstance boInstance) {
log.info("#### BO Instance Schema before ADD: " + boInstance.getDocument().asXML());
boInstance = BusinessObjectDispatcher.add(boInstance);
log.info("#### BO Instance Schema after ADD: " + boInstance.getDocument().asXML());
boInstance.set("boStatus", "VALIDATE");
boInstance = BusinessObjectDispatcher.update(boInstance);
log.info("#### BO Instance Schema after VALIDATE: " + boInstance.getDocument().asXML());
boInstance.set("boStatus", "READYFORPOST");
boInstance = BusinessObjectDispatcher.update(boInstance);
log.info("#### BO Instance Schema after READYFORPOST: " + boInstance.getDocument().asXML());
boInstance.set("boStatus", "POSTED");
boInstance = BusinessObjectDispatcher.update(boInstance);
log.info("#### BO Instance Schema after POSTED: " + boInstance.getDocument().asXML());
/*boInstance.set("boStatus", "CREATE");
boInstance = BusinessObjectDispatcher.update(boInstance);*/
return boInstance;
}
public boolean executeWorkUnit(ThreadWorkUnit unit) throws ThreadAbortedException, RunAbortedException {
System.out.println("######################## Demarrage executeWorkUnit ############################");
int rowId = 0;
boolean foundNinea = false;
log.info("*****Starting Execute Work Unit");
String fileName = unit.getSupplementallData("fileName").toString();
log.info("*****executeWorkUnit : " + fileName );
cmXLSXReader.openXLSXFile(fileName);
spreadsheet = cmXLSXReader.openSpreadsheet(0, null);
int rowCount = spreadsheet.getLastRowNum()-spreadsheet.getFirstRowNum();
System.out.println("rowCount:: " + rowCount);
Iterator<Row> rowIterator = spreadsheet.iterator();
int cellCount = spreadsheet.getRow(0).getLastCellNum();
System.out.println("CellCount:: " + cellCount);
while(rowIterator.hasNext()){
XSSFRow row = (XSSFRow) rowIterator.next();
if(row.getRowNum() == 0) {
continue;
}
//rowId++;
cellId = 1;
Iterator<Cell> cellIterator = row.cellIterator();
List<Object>listesValues=new ArrayList<Object>();
while (cellIterator.hasNext() && !foundNinea) {
while (cellId <= cellCount) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
/*if(cell.getStringCellValue().contains("@")) {
validateEmail(cell.getStringCellValue());
}*/
listesValues.add(cell.getStringCellValue());
System.out.println(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
//validateDate(cell.getDateCellValue());
listesValues.add(cell.getDateCellValue());
System.out.println(cell.getDateCellValue());
} else {
listesValues.add(cell.getNumericCellValue());
System.out.println(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BLANK:
listesValues.add("");
System.out.println("Blank:");
break;
default:
System.out.println("Blank:");
break;
}
log.info("*****Iterated through One Employee Details***");
cellId++;
}
log.info("*****Search Person from Business Service****");
String regType = "";
if (listesValues.get(0).toString().equalsIgnoreCase("Immatriculation Volontaire")) {
regType = "BVOLN";
} else {
regType = "CMPL";
}
listesValues.set(0, regType);
String empType = "";
if (listesValues.get(1).toString().equalsIgnoreCase("Société Privée")) {
empType = "PVT";
} else {
empType = "COOP";
}
listesValues.set(1, empType);
String estType = "";
if (listesValues.get(2).toString().equalsIgnoreCase("Siége")) {
estType = "HDQT";
} else {
estType = "BRNC";
}
listesValues.set(2, estType);
foundNinea = true;
try {
formCreator(fileName, listesValues);
// foundNinea = false;
} catch (Exception e) {
// rename file to *.err
File file = new File(fileName);
// file = this.changeExtension(file, "err");
System.out.println("*****Issue in Processing file*****" + fileName + "IdNumber:: "
+ listesValues.get(3) + "IdValue:: " + listesValues.get(2));
log.info("*****Issue in Processing file*****" + fileName + "IdNumber:: " + listesValues.get(3)
+ "IdValue:: " + listesValues.get(2));
e.printStackTrace();
//ssaddError(CmMessageRepository90002.MSG_800(fileName));
}
// rename file to .ok
// }
}
foundNinea = false;
}
File file = new File(fileName);
// file = this.changeExtension(file, "ok");
System.out.println("######################## Terminer executeWorkUnit ############################");
return true;
}
private void convertDate(String date) {
String dateOfb = "";
try {
String date_s = date;
SimpleDateFormat dt = new SimpleDateFormat("dd/mm/yyyy");
java.util.Date formateddate = dt.parse(date_s);
SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-mm-dd");
dateOfb = dt1.format(formateddate);
System.out.println(dt1.format(formateddate));
} catch(Exception exception) {
exception.printStackTrace();
}
}
/**
* Validate Email Address
*
* @param stringCellValue
* @return
*/
private boolean validateEmail(String stringCellValue) {
// TODO Auto-generated method stub
Pattern pattern;
Matcher matcher;
String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(stringCellValue);
return matcher.matches();
}
private File changeExtension(File file, String extension) {
String filename = file.getName();
String filePath = file.getAbsolutePath();
log.info("*****changeExtension start:" + filename);
if (filename.contains(".")) {
filename = filename.substring(0, filename.lastIndexOf('.'));
}
filename += "." + extension;
String strFileRenamed = filePath;
if (strFileRenamed.contains(".")) {
strFileRenamed = strFileRenamed.substring(0, strFileRenamed.lastIndexOf('.'));
}
strFileRenamed += "." + extension;
log.info("*****to rename File:" + strFileRenamed);
File fileRenamed = new File(strFileRenamed);
if (fileRenamed.exists()) {
log.info("The " + filename + " exist" );
}
else
{
log.info("The " + filename + " does not exist" );
}
if (fileRenamed.delete())
{
log.info("The " + filename + " was deleted" );
}
file.renameTo(new File(file.getParentFile(), filename));
return file;
}
}
}
|
package com.apssouza.mytrade.trading.misc.observer;
import java.io.Serializable;
import java.io.ObjectStreamField;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Map.Entry;
/**
* This is a utility class that can be used by beans that support bound properties. It manages a list of listeners and
* dispatches {@link PropertyChangeEvent}s to them. You can use an instance of this class as a member field of your
* bean and delegate these types of work to it. The {@link PropertyChangeListener} can be registered for all properties
* or for a property specified by name.
* <p>
* Here is an example of {@code PropertyChangeSupport} usage that follows the rules and recommendations laid out in the
* JavaBeans™ specification:
*/
public class PropertyChangeSupport implements Serializable {
private PropertyChangeListenerMap map = new PropertyChangeListenerMap();
/**
* Constructs a {@code PropertyChangeSupport} object.
*
* @param sourceBean The bean to be given as the source for any events.
*/
public PropertyChangeSupport(Object sourceBean) {
if (sourceBean == null) {
throw new NullPointerException();
}
source = sourceBean;
}
/**
* Add a PropertyChangeListener to the listener list. The listener is registered for all properties. The same
* listener object may be added more than once, and will be called as many times as it is added. If {@code listener}
* is null, no exception is thrown and no action is taken.
*
* @param listener The PropertyChangeListener to be added
*/
public void addPropertyChangeListener(PropertyChangeListener listener) {
if (listener == null) {
return;
}
this.map.add(null, listener);
}
/**
* Remove a PropertyChangeListener from the listener list. This removes a PropertyChangeListener that was registered
* for all properties. If {@code listener} was added more than once to the same event source, it will be notified
* one less time after being removed. If {@code listener} is null, or was never added, no exception is thrown and no
* action is taken.
*
* @param listener The PropertyChangeListener to be removed
*/
public void removePropertyChangeListener(PropertyChangeListener listener) {
if (listener == null) {
return;
}
this.map.remove(null, listener);
}
/**
* Returns an array of all the listeners that were added to the PropertyChangeSupport object with
* addPropertyChangeListener().
* <p>
* If some listeners have been added with a named property, then the returned array will be a mixture of
* PropertyChangeListeners and {@code PropertyChangeListenerProxy}s. If the calling method is interested in
* distinguishing the listeners then it must test each element to see if it's a {@code PropertyChangeListenerProxy},
* perform the cast, and examine the parameter.
*
* <pre>{@code
* PropertyChangeListener[] listeners = bean.getPropertyChangeListeners();
* for (int i = 0; i < listeners.length; i++) {
* if (listeners[i] instanceof PropertyChangeListenerProxy) {
* PropertyChangeListenerProxy proxy =
* (PropertyChangeListenerProxy)listeners[i];
* if (proxy.getPropertyName().equals("foo")) {
* // proxy is a PropertyChangeListener which was associated
* // with the property named "foo"
* }
* }
* }
* }</pre>
*
* @return all of the {@code PropertyChangeListeners} added or an empty array if no listeners have been added
* @since 1.4
*/
public PropertyChangeListener[] getPropertyChangeListeners() {
return this.map.getListeners();
}
/**
* Add a PropertyChangeListener for a specific property. The listener will be invoked only when a call on
* firePropertyChange names that specific property. The same listener object may be added more than once. For each
* property, the listener will be invoked the number of times it was added for that property. If {@code
* propertyName} or {@code listener} is null, no exception is thrown and no action is taken.
*
* @param propertyName The name of the property to listen on.
* @param listener The PropertyChangeListener to be added
* @since 1.2
*/
public void addPropertyChangeListener(
String propertyName,
PropertyChangeListener listener
) {
if (listener == null || propertyName == null) {
return;
}
listener = this.map.extract(listener);
if (listener != null) {
this.map.add(propertyName, listener);
}
}
/**
* Remove a PropertyChangeListener for a specific property. If {@code listener} was added more than once to the same
* event source for the specified property, it will be notified one less time after being removed. If {@code
* propertyName} is null, no exception is thrown and no action is taken. If {@code listener} is null, or was never
* added for the specified property, no exception is thrown and no action is taken.
*
* @param propertyName The name of the property that was listened on.
* @param listener The PropertyChangeListener to be removed
* @since 1.2
*/
public void removePropertyChangeListener(
String propertyName,
PropertyChangeListener listener
) {
if (listener == null || propertyName == null) {
return;
}
listener = this.map.extract(listener);
if (listener != null) {
this.map.remove(propertyName, listener);
}
}
/**
* Returns an array of all the listeners which have been associated with the named property.
*
* @param propertyName The name of the property being listened to
* @return all of the {@code PropertyChangeListeners} associated with the named property. If no such listeners have
* been added, or if {@code propertyName} is null, an empty array is returned.
* @since 1.4
*/
public PropertyChangeListener[] getPropertyChangeListeners(String propertyName) {
return this.map.getListeners(propertyName);
}
/**
* Reports a bound property update to listeners that have been registered to track updates of all properties or a
* property with the specified name.
* <p>
* No event is fired if old and new values are equal and non-null.
* <p>
* This is merely a convenience wrapper around the more general {@link #firePropertyChange(PropertyChangeEvent)}
* method.
*
* @param propertyName the programmatic name of the property that was changed
* @param oldValue the old value of the property
* @param newValue the new value of the property
*/
public void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
if (oldValue == null || newValue == null || !oldValue.equals(newValue)) {
firePropertyChange(new PropertyChangeEvent(this.source, propertyName, oldValue, newValue));
}
}
/**
* Reports an integer bound property update to listeners that have been registered to track updates of all
* properties or a property with the specified name.
* <p>
* No event is fired if old and new values are equal.
* <p>
* This is merely a convenience wrapper around the more general {@link #firePropertyChange(String, Object, Object)}
* method.
*
* @param propertyName the programmatic name of the property that was changed
* @param oldValue the old value of the property
* @param newValue the new value of the property
* @since 1.2
*/
public void firePropertyChange(String propertyName, int oldValue, int newValue) {
if (oldValue != newValue) {
firePropertyChange(propertyName, Integer.valueOf(oldValue), Integer.valueOf(newValue));
}
}
/**
* Reports a boolean bound property update to listeners that have been registered to track updates of all properties
* or a property with the specified name.
* <p>
* No event is fired if old and new values are equal.
* <p>
* This is merely a convenience wrapper around the more general {@link #firePropertyChange(String, Object, Object)}
* method.
*
* @param propertyName the programmatic name of the property that was changed
* @param oldValue the old value of the property
* @param newValue the new value of the property
* @since 1.2
*/
public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {
if (oldValue != newValue) {
firePropertyChange(propertyName, Boolean.valueOf(oldValue), Boolean.valueOf(newValue));
}
}
/**
* Fires a property change event to listeners that have been registered to track updates of all properties or a
* property with the specified name.
* <p>
* No event is fired if the given event's old and new values are equal and non-null.
*
* @param event the {@code PropertyChangeEvent} to be fired
* @since 1.2
*/
public void firePropertyChange(PropertyChangeEvent event) {
Object oldValue = event.getOldValue();
Object newValue = event.getNewValue();
if (oldValue == null || newValue == null || !oldValue.equals(newValue)) {
String name = event.getPropertyName();
PropertyChangeListener[] common = this.map.get(null);
PropertyChangeListener[] named = (name != null)
? this.map.get(name)
: null;
fire(common, event);
fire(named, event);
}
}
private static void fire(PropertyChangeListener[] listeners, PropertyChangeEvent event) {
if (listeners != null) {
for (PropertyChangeListener listener : listeners) {
listener.propertyChange(event);
}
}
}
/**
* Check if there are any listeners for a specific property, including those registered on all properties. If
* {@code propertyName} is null, only check for listeners registered on all properties.
*
* @param propertyName the property name.
* @return true if there are one or more listeners for the given property
* @since 1.2
*/
public boolean hasListeners(String propertyName) {
return this.map.hasListeners(propertyName);
}
/**
* @serialData Null terminated list of {@code PropertyChangeListeners}.
* <p>
* At serialization time we skip non-serializable listeners and only serialize the serializable listeners.
*/
private void writeObject(ObjectOutputStream s) throws IOException {
Hashtable<String, PropertyChangeSupport> children = null;
PropertyChangeListener[] listeners = null;
synchronized (this.map) {
for (Entry<String, PropertyChangeListener[]> entry : this.map.getEntries()) {
String property = entry.getKey();
if (property == null) {
listeners = entry.getValue();
} else {
if (children == null) {
children = new Hashtable<>();
}
PropertyChangeSupport pcs = new PropertyChangeSupport(this.source);
pcs.map.set(null, entry.getValue());
children.put(property, pcs);
}
}
}
ObjectOutputStream.PutField fields = s.putFields();
fields.put("children", children);
fields.put("source", this.source);
fields.put("propertyChangeSupportSerializedDataVersion", 2);
s.writeFields();
if (listeners != null) {
for (PropertyChangeListener l : listeners) {
if (l instanceof Serializable) {
s.writeObject(l);
}
}
}
s.writeObject(null);
}
private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException {
this.map = new PropertyChangeSupport.PropertyChangeListenerMap();
ObjectInputStream.GetField fields = s.readFields();
@SuppressWarnings("unchecked")
Hashtable<String, PropertyChangeSupport> children =
(Hashtable<String, PropertyChangeSupport>) fields.get("children", null);
this.source = fields.get("source", null);
fields.get("propertyChangeSupportSerializedDataVersion", 2);
Object listenerOrNull;
while (null != (listenerOrNull = s.readObject())) {
this.map.add(null, (PropertyChangeListener) listenerOrNull);
}
if (children != null) {
for (Entry<String, PropertyChangeSupport> entry : children.entrySet()) {
for (PropertyChangeListener listener : entry.getValue().getPropertyChangeListeners()) {
this.map.add(entry.getKey(), listener);
}
}
}
}
/**
* The object to be provided as the "source" for any generated events.
*/
private Object source;
/**
* @serialField children Hashtable
* @serialField source Object
* @serialField propertyChangeSupportSerializedDataVersion int
*/
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("children", Hashtable.class),
new ObjectStreamField("source", Object.class),
new ObjectStreamField("propertyChangeSupportSerializedDataVersion", Integer.TYPE)
};
/**
* Serialization version ID, so we're compatible with JDK 1.1
*/
static final long serialVersionUID = 6401253773779951803L;
/**
* This is a {@link ChangeListenerMap ChangeListenerMap} implementation that works with {@link
* PropertyChangeListener PropertyChangeListener} objects.
*/
private static final class PropertyChangeListenerMap extends ChangeListenerMap<PropertyChangeListener> {
private static final PropertyChangeListener[] EMPTY = {};
/**
* Creates an array of {@link PropertyChangeListener PropertyChangeListener} objects. This method uses the same
* instance of the empty array when {@code length} equals {@code 0}.
*
* @param length the array length
* @return an array with specified length
*/
@Override
protected PropertyChangeListener[] newArray(int length) {
return (0 < length)
? new PropertyChangeListener[length]
: EMPTY;
}
/**
* Creates a {@link PropertyChangeListenerProxy PropertyChangeListenerProxy} object for the specified property.
*
* @param name the name of the property to listen on
* @param listener the listener to process events
* @return a {@code PropertyChangeListenerProxy} object
*/
@Override
protected PropertyChangeListener newProxy(String name, PropertyChangeListener listener) {
return new PropertyChangeListenerProxy(name, listener);
}
/**
* {@inheritDoc}
*/
public PropertyChangeListener extract(PropertyChangeListener listener) {
while (listener instanceof PropertyChangeListenerProxy) {
listener = ((PropertyChangeListenerProxy) listener).getListener();
}
return listener;
}
}
}
|
package common.util;
import common.environment.driver.Browser;
import org.assertj.core.api.Assertions;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesUtil {
public static final String PATH_PROPERTY_CHROME_DRIVER = "webdriver.chrome.driver";
public static final String PATH_PROPERTY_FIREFOX_DRIVER = "webdriver.gecko.driver";
public static final String FIREFOX_NETWORK_COOKIE_BEHAVIOR = "network.cookie.cookieBehavior";
public static final String CHROME_NETWORK_COOKIES_BEHAVIOR = "profile.default_content_settings.cookies";
private PropertiesUtil() {
}
public static String getProperty(Browser browser) throws IOException {
Properties properties = new Properties();
InputStream resourceAsStream = PropertiesUtil.class.getClassLoader().getResourceAsStream("driver.properties");
properties.load(resourceAsStream);
switch (browser) {
case chrome:
return properties.getProperty(PATH_PROPERTY_CHROME_DRIVER);
case fireFox:
return properties.getProperty(PATH_PROPERTY_FIREFOX_DRIVER);
}
Assertions.fail(String.format("Provided choice %s is not valid", browser));
return null;
}
}
|
package com.phoosop.gateway.config;
import com.phoosop.gateway.filter.LoggingGatewayFilterFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.route.builder.Buildable;
import org.springframework.cloud.gateway.route.builder.PredicateSpec;
import org.springframework.context.annotation.Configuration;
@Configuration
@RequiredArgsConstructor
public class ActivityRoutes {
private final LoggingGatewayFilterFactory loggingGatewayFilterFactory;
public Buildable<Route> normal(PredicateSpec spec) {
return spec.path("/api/activity")
.uri("http://localhost:9100");
}
public Buildable<Route> stripprefix(PredicateSpec spec) {
return spec.path("/stripprefix/addprefix/activity")
.filters(gatewayFilterSpec -> {
gatewayFilterSpec.stripPrefix(2);
gatewayFilterSpec.prefixPath("/api");
return gatewayFilterSpec;
})
.uri("http://localhost:9100");
}
public Buildable<Route> rewrite(PredicateSpec spec) {
return spec.path("/rewrite")
.filters(gatewayFilterSpec -> {
gatewayFilterSpec.rewritePath("/rewrite", "/api/activity");
return gatewayFilterSpec;
})
.uri("http://localhost:9100");
}
public Buildable<Route> logging(PredicateSpec spec) {
return spec.path("/logging")
.filters(gatewayFilterSpec -> {
gatewayFilterSpec.rewritePath("/logging", "/api/activity")
.filter(loggingGatewayFilterFactory.apply(new LoggingGatewayFilterFactory.Config(true, true)));
return gatewayFilterSpec;
})
.uri("http://localhost:9100");
}
public Buildable<Route> circuit(PredicateSpec spec) {
return spec.path("/circuit")
.filters(gatewayFilterSpec -> {
gatewayFilterSpec.rewritePath("/circuit", "/api/activity")
.circuitBreaker(config -> config.setName("circuit")
.setFallbackUri("forward:/fallback/unavailable-fallback"));
return gatewayFilterSpec;
})
.uri("http://localhost:9100");
}
}
|
/**
*
*/
package org.apache.hadoop.mapreduce.lib.output;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.util.Iterator;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.util.ByteUtil;
import org.apache.hadoop.util.TreeMultiMap;
/**
* This is a BS class at the moment
*
* @author tim
*/
public class IntTextRecordReader extends RecordReader<IntWritable, Text> {
protected DataInputStream is;
private IntWritable k;
private Text v;
private Iterator iterator;
private byte[] input;
private int offset;
private int offsetArrayIndex;
private StringBuilder builder;
private byte[] inputOffsets;
private int inputOffsetsSize;
private int previousKeyEle;
private int currentKeyEle;
private final static int MASK = 0x000000FF;
@Override
public IntWritable getCurrentKey() {
return k;
}
@Override
public String getKeyDataValue() {
return k.toString();
}
@Override
public final Text getCurrentValue() {
return v;
}
@Override
public final void initialize(final byte[] input) {
}
private String decodeUTF16BE(final byte[] bytes, int startByte, final int byteCount) {
final StringBuilder builder = new StringBuilder(byteCount);
for (int i = 0; i < byteCount; i++) {
final byte low = bytes[startByte++];
final int ch = (low & MASK);
builder.append((char) ch);
}
return builder.toString();
}
public String readString(final byte[] a, final int i, final int j) throws CharacterCodingException {
return decodeUTF16BE(a, i, (j - i) + 1);
}
public static int fromByteArray(final byte[] a, final int i) {
return a[i] << 24 | (a[i + 1] & MASK) << 16 | (a[i + 2] & MASK) << 8 | (a[i + 3] & MASK);
}
public final void initialize(final byte[] input, final byte[] inputOffsets, int inputOffsetsSize) {
// make a read only copy just in case
this.input = input;
this.inputOffsets = inputOffsets;
this.inputOffsetsSize = inputOffsetsSize;
builder = new StringBuilder(100);
offsetArrayIndex = 0;
}
@Override
public void initialize(final TreeMultiMap<WritableComparable, WritableComparable> input) {
iterator = input.entrySet().iterator();
}
@Override
public final boolean nextKeyValue() {
try {
if (k == null) {
k = new IntWritable(-1);
}
v = new Text("");
if (offsetArrayIndex != inputOffsetsSize) {
offset = ByteUtil.readInt(inputOffsets, offsetArrayIndex);
offsetArrayIndex += 4;
} else {
input = null;
inputOffsets = null;
return false;
}
currentKeyEle = ByteUtil.readInt(input, offset);
if (previousKeyEle != -1 && (previousKeyEle != currentKeyEle)) {
k = new IntWritable(currentKeyEle);
}
previousKeyEle = currentKeyEle;
k.set(currentKeyEle);
v.set(readString(input, offset + 4 + v.getOffset(), offset + 4 + v.getOffset() + (input[offset + 4 + v.getOffset() - 1] & MASK) - 1));
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
@Override
public final boolean nextKeyValue(final int ind) {
try {
if (ind == inputOffsets.length) {
input = null;
inputOffsets = null;
return false;
}
k = new IntWritable(-1);
v = new Text("");
offset = ByteUtil.readInt(inputOffsets, ind);
k.set(ByteUtil.readInt(input, offset));
v.set(readString(input, offset + 4 + k.getOffset(), input[offset + 4 + k.getOffset() - 1] & MASK));
return true;
} catch (Exception e) { //e.printStackTrace(); return false;
}
return false;
}
// Returns an input stream for a ByteBuffer.
// The read() methods use the relative ByteBuffer get() methods.
public static InputStream newInputStream(final ByteBuffer buf) {
return new InputStream() {
@Override
public synchronized int read() throws IOException {
if (!buf.hasRemaining()) {
return -1;
}
return buf.get();
}
@Override
public synchronized int read(final byte[] bytes, final int off, int len) throws IOException {
// Read only what's left
len = Math.min(len, buf.remaining());
buf.get(bytes, off, len);
return len;
}
};
}
@Override
public void initialize(final ByteBuffer input) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
|
package com.example.rshikkal.icafe.DBHandler;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.view.Menu;
import com.example.rshikkal.icafe.Models.MenuItem;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
* Created by rshikkal on 5/14/2017.
*/
public class CartDatabase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "itemmanager";
private static final String TABLE_ITEMS= "items";
// menu item Table Columns names
private static final String KEY_ID = "itemid";
private static final String KEY_NAME = "itemname";
private static final String KEY_DESCRIPTION = "itemdescription";
private static final String KEY_ITEMTYPE = "itemtype";
private static final String KEY_PRICE = "itemprice";
private static final String KEY_ITEMSTATUS = "itemstatus";
private static final String KEY_RATINGS = "itemratings";
public CartDatabase(Context context){
super(context,DATABASE_NAME,null,DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS + "("
+ KEY_ID + " TEXT PRIMARY KEY," + KEY_NAME + " TEXT,"+ KEY_DESCRIPTION + " TEXT,"+ KEY_ITEMTYPE + " TEXT,"
+ KEY_PRICE + " TEXT," + KEY_ITEMSTATUS + " TEXT," + KEY_RATINGS + " TEXT" + ")";
db.execSQL(CREATE_ITEMS_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEMS);
onCreate(db);
}
public void addProduct(MenuItem item) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, item.getItemid());
values.put(KEY_NAME, item.getItemname());
values.put(KEY_DESCRIPTION, item.getItemdescription());
values.put(KEY_ITEMTYPE, item.getItemtype());
values.put(KEY_PRICE, item.getItemprice());
values.put(KEY_ITEMSTATUS, item.getItemstatus());
values.put(KEY_RATINGS,item.getItemrating());
db.insert(TABLE_ITEMS, null, values);
db.close();
}
public List<MenuItem> getAllProducts() {
List<MenuItem> menuItemList = new ArrayList<MenuItem>();
String selectQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
MenuItem menuItem = new MenuItem();
menuItem.setItemid(cursor.getString(0));
menuItem.setItemname(cursor.getString(1));
menuItem.setItemdescription(cursor.getString(2));
menuItem.setItemtype(cursor.getString(3));
menuItem.setItemprice(cursor.getString(4));
menuItem.setItemstatus(cursor.getString(5));
menuItem.setItemrating(cursor.getString(6));
menuItemList.add(menuItem);
} while (cursor.moveToNext());
}
return menuItemList;
}
public void deleteProduct(MenuItem menuItem) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_ITEMS, KEY_ID + " = ?",
new String[] { String.valueOf(menuItem.getItemid()) });
db.close();
}
public int getProductCount() {
String countQuery = "SELECT * FROM " + TABLE_ITEMS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
return count;
}
}
|
package com.bits.securityapp.Adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.bits.securityapp.R;
import java.util.ArrayList;
public class VolunteersListAdapter extends RecyclerView.Adapter<VolunteersListAdapter.MyViewHolder> {
private Context context;
private ArrayList<String> dataSet;
private DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
public int setUserIds(ArrayList<String> dataSet){
this.dataSet = dataSet;
return dataSet.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
private TextView name;
public MyViewHolder(View itemView){
super(itemView);
name = itemView.findViewById(R.id.name);
}
}
public VolunteersListAdapter(Context context, ArrayList<String> dataSet){
this.dataSet = dataSet;
this.context = context;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int listPositon) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.volunteers_item,parent,false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
@Override
public void onBindViewHolder(@NonNull final MyViewHolder holder, int listPosition) {
String userId = dataSet.get(listPosition);
databaseReference.child("users").child(userId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
holder.name.setText(dataSnapshot.child("name").getValue(String.class));
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
@Override
public int getItemCount() {
return dataSet.size();
}
}
|
package com.esum.as2.msh;
import java.io.ByteArrayOutputStream;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import javax.mail.internet.ContentType;
import javax.mail.internet.MimeBodyPart;
import org.bouncycastle.cms.jcajce.ZlibExpanderProvider;
import org.bouncycastle.mail.smime.SMIMECompressed;
import org.bouncycastle.mail.smime.SMIMEUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.esum.as2.AS2Exception;
import com.esum.as2.message.AS2Message;
import com.esum.as2.message.AS2MessageException;
import com.esum.as2.message.MDNMessage;
import com.esum.as2.message.MessageUtil;
import com.esum.as2.message.disposition.DispositionException;
import com.esum.as2.message.disposition.DispositionOptions;
import com.esum.as2.message.disposition.DispositionType;
import com.esum.as2.storage.PartnerInfoRecord;
import com.esum.as2.storage.RoutingException;
import com.esum.as2.storage.RoutingManager;
import com.esum.as2.transaction.TransactionEvent;
import com.esum.as2.transaction.TransactionException;
import com.esum.as2.transaction.TransactionLog;
import com.esum.as2.util.MDNUtil;
import com.esum.as2.util.MimeUtil;
import com.esum.framework.security.pki.manager.PKIException;
import com.esum.framework.security.pki.manager.PKIStoreManager;
import com.esum.framework.security.pki.manager.info.PKIStoreInfo;
import com.esum.framework.security.smime.encrypt.SMIMEEncrypt;
/**
* 수신한 AS2 Message에 대한 복호화/서명검증작업을 수행하고, 트랜잭션에 대한 로그를 기록한다.
*
* Copyrights(c) eSum Technologies., Inc. All rights reserved.
*/
public class InboundProcessor {
private Logger log = LoggerFactory.getLogger(InboundProcessor.class);
private TransactionEvent event;
private String traceId;
private TransactionLog transLog;
/**
* InboundProcessor를 생성한다.
*/
public InboundProcessor(String traceId, TransactionEvent event, TransactionLog transLog){
this.traceId = traceId;
this.event = event;
this.transLog = transLog;
}
/**
* 수신한 AS2Message가 암호화 되어 있다면 복호화하고 서명되되어 있다면 서명검증을 한다.
*/
public MDNMessage process(AS2Message msg) throws AS2InboundException{
try {
readCompressedMail(msg, new ContentType(msg.getContentType()));
}catch(Exception e){
log.error(traceId+"read compressed message error.", e);
DispositionType disposition = new DispositionType(DispositionType.AUTOMATIC_ACTION,
DispositionType.MDN_SENT_AUTOMATICALLY,
DispositionType.PROCESSED,
DispositionType.ERROR, "decompression-failed");
return createMDN(disposition, new ReportMessage(msg).DISP_DECRYPTION_ERROR(), null, msg);
}
String mic = null;
try{
decryptAndVerify(msg, new ContentType(msg.getContentType()));
DispositionOptions dispOptions = new DispositionOptions(msg.getDispositionNotificationOptions());
mic = MDNUtil.calculateMIC(traceId, msg, dispOptions.getMicalg());
}catch(DispositionException e){
ReportMessage reportMessage = new ReportMessage(msg); //.DISP_DECRYPTION_ERROR()
String report = null;
if (e.getErrorCode().equals(DispositionException.ERROR_VERIFY_FAILED))
report = reportMessage.DISP_VERIFY_SIGNATURE_FAILED();
else
report = reportMessage.DISP_DECRYPTION_ERROR();
try {
transLog.insertMessageLog(traceId, event, null);
log.info(traceId + "Logged Transaction into file, DB. Normal Message: true");
} catch (TransactionException ex) {
throw new AS2InboundException(ex.getErrorCode(), ex.getErrorLocation(), ex.getMessage(), ex);
}
return createMDN(e.getDisposition(), report, mic, msg);
}catch(Exception e){
log.error(traceId+"decrypt and verify error.", e);
DispositionType disposition = new DispositionType(DispositionType.AUTOMATIC_ACTION,
DispositionType.MDN_SENT_AUTOMATICALLY,
DispositionType.PROCESSED,
DispositionType.ERROR, "decryption-failed");
return createMDN(disposition, new ReportMessage(msg).DISP_DECRYPTION_ERROR(), mic, msg);
}
// etc mime parsing
try {
msg = (AS2Message)MessageUtil.unMarshal(traceId, msg);
} catch (DispositionException e) {
return createMDN(e.getDisposition(), new ReportMessage(msg).DISP_DECRYPTION_ERROR(), mic, msg);
}
byte[] docData = null;
ByteArrayOutputStream dataOutStream = null;
try{
dataOutStream = new ByteArrayOutputStream();
MimeUtil.getContentData(msg.getData(), dataOutStream);
docData = dataOutStream.toByteArray();
transLog.insertMessageLog(traceId, event, docData);
log.debug(traceId + "Logged Transaction into file, DB. Normal Message: true");
}catch(Exception e){
log.error(traceId+"as2 message parsing completed. but post processing(messageLog) writing error.", e);
DispositionType disposition = new DispositionType(DispositionType.AUTOMATIC_ACTION,
DispositionType.MDN_SENT_AUTOMATICALLY,
DispositionType.PROCESSED,
DispositionType.ERROR, "unexpected-processing-error");
return createMDN(disposition, new ReportMessage(msg).DISP_UNEXPECTED_ERROR(), mic, msg);
} finally {
if (dataOutStream != null) {
try {dataOutStream.close();}catch (Exception e){}
}
}
log.debug(traceId + "Sending AS2 Message to Adapter...");
AdapterFactory.getInstance().getAdapter().onReceivedMessage(msg);
log.info(traceId + "Sent AS2 Message to Adapter.");
try {
log.info(traceId + "Does sender request MDN? " + msg.isRequestingMDN());
if(!msg.isRequestingMDN()){
log.info(traceId + "Don't need MDN. So, processed Inbound message successfully.");
return null;
}
return createMDN(new DispositionType(DispositionType.AUTOMATIC_ACTION,
DispositionType.MDN_SENT_AUTOMATICALLY, DispositionType.PROCESSED),
new ReportMessage(msg).DISP_SUCCESS(), mic, msg);
} catch (AS2InboundException e) {
throw new AS2InboundException(e.getErrorCode(),e.getErrorLocation(),e.getErrorMessage(),e);
}
}
/**
* 특정 Disposition정보를 이용하여 MDN Message를 생성한다.
*
* @param disposition 수신한 Message 처리 결과에 대한 Disposition.
* @param report 처리 결과에 대한 report message.
* @return
* @throws AS2InboundException
*/
private MDNMessage createMDN(DispositionType disposition, String report, String mic, AS2Message msg) throws AS2InboundException{
MDNMessage mdn = null;
try{
log.debug(traceId + "Creating MDN message...");
mdn = MDNUtil.createMDN(traceId, msg, disposition, mic, report);
log.info(traceId + "Created MDN message. MDN Message ID: " + mdn.getMessageId());
}catch(AS2Exception e){
throw new AS2InboundException(e.getErrorCode(), e.getErrorLocation(), e.getMessage(),e);
}
return mdn;
}
/**
* to decrypt and verify with message.
*
* @param msg
* @param receivedContentType
* @throws DispositionException
*/
protected void decryptAndVerify(AS2Message msg, ContentType receivedContentType) throws DispositionException {
PartnerInfoRecord sender = null;
PartnerInfoRecord receiver = null;
try {
log.debug(traceId + "Searching Partner info. From: " + msg.getAS2From()+", To : "+msg.getAS2To());
sender = RoutingManager.getInstance().getPartnerInfo(msg.getAS2From());
receiver = RoutingManager.getInstance().getPartnerInfo(msg.getAS2To());
} catch (RoutingException e) {
throw new DispositionException(e.getErrorCode(),
e.getErrorLocation(), e.getMessage(),
new DispositionType(DispositionType.AUTOMATIC_ACTION,
DispositionType.MDN_SENT_AUTOMATICALLY, DispositionType.PROCESSED,
DispositionType.ERROR, e.toString()));
}
String smimeType = receivedContentType.getParameter("smime-type");
if(smimeType == null)
smimeType = "";
if(!smimeType.equals(com.esum.as2.message.ContentType.COMPRESSED_DATA)){
try {
if (receivedContentType.getBaseType().equalsIgnoreCase(com.esum.as2.message.ContentType.APPLICATION_PKCS7_MIME)) {
log.debug(traceId + "This message is encrypted. So, must need receiver's private key and certificate.");
PKIStoreInfo pkiStoreInfo = null;
try {
log.debug(traceId + "Searching PKI information... PKI alias: " + receiver.getEncPKIAlias());
pkiStoreInfo = PKIStoreManager.getInstance().getPKIStoreInfo(receiver.getEncPKIAlias());
log.debug(traceId + "Searched PKI information. " + pkiStoreInfo);
} catch (PKIException e) {
throw new AS2Exception(AS2Exception.ERROR_SECURITY, "process()",
"PKI Load Error!! Please check the PKI store table. PKI Alias: " + receiver.getEncPKIAlias(),e);
}
X509Certificate receiverCert = pkiStoreInfo.getCertificate();
PrivateKey receiverKey = pkiStoreInfo.getPrivateKey();
MimeBodyPart decryptedPart = SMIMEEncrypt.getInstance().decrypt(traceId, msg.getData(), receiverCert, receiverKey);
msg.setData(decryptedPart);
receivedContentType = new ContentType(msg.getData().getContentType());
log.info(traceId + "Decrypted the encrypted message successfully.");
}
} catch (Exception e) {
log.error(traceId + "Decryption Error. " + e.toString(), e);
throw new DispositionException(DispositionException.ERROR_DECRYPTION_FAILED,
"decryptAndVerity()", e.getMessage(),
new DispositionType(DispositionType.AUTOMATIC_ACTION,
DispositionType.MDN_SENT_AUTOMATICALLY, DispositionType.PROCESSED,
DispositionType.ERROR, "decryption-failed"));
}
smimeType = receivedContentType.getParameter("smime-type");
if(smimeType == null)
smimeType = "";
if(smimeType.equals(com.esum.as2.message.ContentType.COMPRESSED_DATA)){
log.info(traceId+"message decrypted. but compressed.");
try {
readCompressedMail(msg, new ContentType(msg.getContentType()));
} catch (Exception e) {
throw new DispositionException(DispositionException.ERROR_READ_COMPRESSED_MAIL_FAILED,
"decryptAndVerify()", e.getMessage(), new DispositionType(DispositionType.AUTOMATIC_ACTION,
DispositionType.MDN_SENT_AUTOMATICALLY,
DispositionType.PROCESSED,
DispositionType.ERROR, "decompression-failed"));
}
return;
}
if (receivedContentType.getBaseType().equalsIgnoreCase(com.esum.as2.message.ContentType.MULTIPART_SIGNED)) {
log.info(traceId + "This message is signed. So, must need sender's certificate.");
try {
X509Certificate senderCert = null;
try {
PKIStoreInfo senderPKI = PKIStoreManager.getInstance().getPKIStoreInfo(sender.getSigPKIAlias());
if(senderPKI==null)
throw new PKIException("process()", "Can not found PKIStoreInfo. alias : "+sender.getSigPKIAlias());
senderCert = senderPKI.getCertificate();
} catch (PKIException e) {
throw new AS2Exception(AS2Exception.ERROR_SECURITY, "process()",
"PKI Load Error!! Please check the PKI store table. PKI Alias: " + sender.getSigPKIAlias(),e);
}
MimeBodyPart verifiedContent = SMIMEEncrypt.getInstance().verifySignature(traceId, senderCert, msg.getData());
msg.setData(verifiedContent);
} catch (Exception e) {
log.error(traceId + "Verify Error. " + e.toString(), e);
throw new DispositionException(DispositionException.ERROR_VERIFY_FAILED,
"decryptAndVerity()",e.getMessage(),
new DispositionType(DispositionType.AUTOMATIC_ACTION,
DispositionType.MDN_SENT_AUTOMATICALLY, DispositionType.PROCESSED,
DispositionType.ERROR, "integrity-check-failed"));
}
log.info(traceId + "Verified the signed message successfully.");
}
}
}
protected void readCompressedMail(AS2Message msg, ContentType receivedContentType) throws AS2InboundException{
String smimeType = receivedContentType.getParameter("smime-type");
if(smimeType == null)
smimeType = "";
if(smimeType.equals(com.esum.as2.message.ContentType.COMPRESSED_DATA)){
try {
MimeBodyPart mbp = msg.getData();
SMIMECompressed smimeComp = new SMIMECompressed(mbp);
MimeBodyPart mimeBody = SMIMEUtil.toMimeBodyPart(smimeComp.getContent(new ZlibExpanderProvider()));
msg.setData(mimeBody);
} catch (AS2MessageException e) {
throw new AS2InboundException(e.getErrorCode(),e.getErrorLocation(),e.getMessage(),e);
} catch (Exception e) {
throw new AS2InboundException(DispositionException.ERROR_READ_COMPRESSED_MAIL_FAILED,
"readCompressedMail()", e.getMessage(), e);
}
}
}
/**
* MDN메시지가 서명되어 있다면 검증한다.
*
* @param mdn
* @throws AS2Exception 검증중에 발생하는 에러.
*/
public void checkMDN(MDNMessage mdn) throws AS2Exception{
log.debug(traceId+"check MDNMessage.");
MDNUtil.parseMDN(traceId, mdn, mdn.getAS2From());
}
/**
* MDNMessage를 수신했을때 처리하는 루틴.
* @param mdn
*/
public void processMDN(MDNMessage mdn){
log.debug(traceId+"enter processMDN()");
try {
checkMDN(mdn);
} catch (AS2Exception e) {
log.error(traceId+"invalid mdn message.", e);
AdapterFactory.getInstance().getAdapter().onSentError(mdn, e);
return;
}
String orgMessageId = MessageUtil.trim(mdn.getAttribute(MDNMessage.MDNA_ORIG_MESSAGEID));
if(!transLog.isSentMessage(orgMessageId)){
log.error(traceId+"Not found original message id : "+orgMessageId);
return;
}
String disposition = mdn.getAttribute(MDNMessage.MDNA_DISPOSITION);
log.info(traceId+"Disposition : "+disposition);
try {
new DispositionType(disposition).validate();
transLog.updateMessageLog(TransactionEvent.INBOUND_TRANSACTION, orgMessageId, mdn, null, null, null, 0);
} catch (AS2Exception e) {
log.error(traceId + "MDN Validation Error", e);
try {
transLog.updateMessageLog(TransactionEvent.INBOUND_TRANSACTION, orgMessageId, mdn,
e.getErrorCode(), e.getErrorLocation(), e.getMessage(), 0);
} catch (TransactionException ex) {
log.error(traceId+"transaction update error.", ex);
}
AdapterFactory.getInstance().getAdapter().onSentError(mdn, e);
return;
}
log.info(traceId+"MDN Message processing completed.");
AdapterFactory.getInstance().getAdapter().onReceivedMDN(mdn);
log.info(traceId+"Sent to Adapter.");
}
}
|
import java.awt.*;
import java.awt.geom.Point2D;
import java.io.*;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
/**
* Solution to RoboTreasureHunt problem by Nuro.ai
*
* @author Tejasvi Nareddy
* @version 07/16/17
*/
public class RoboTreasureHunt {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new FileReader("inputs_sample.txt"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("input_sample.out")));
int problems = Integer.parseInt(f.readLine());
StringTokenizer st;
for (int problem = 0; problem < problems; problem++) {
st = new StringTokenizer(f.readLine());
int width = Integer.parseInt(st.nextToken());
int height = Integer.parseInt(st.nextToken());
int goldCount = Integer.parseInt(st.nextToken());
int[] colsVal = new int[width];
for (int i = 0; i < colsVal.length; i++) {
colsVal[i] = 1;
}
int[] rowsVal = new int[height];
for (int i = 0; i < rowsVal.length; i++) {
rowsVal[i] = 1;
}
int[][] grid = new int[height][width];
for (int h = 0; h < height; h++) {
st = new StringTokenizer(f.readLine());
for (int w = 0; w < width; w++) {
int val = Integer.parseInt(st.nextToken());
colsVal[w] *= (val);
rowsVal[h] *= (val);
grid[h][w] = val;
}
}
PriorityQueue<Point2D> priorityQueue = new PriorityQueue<>(new Comparator<Point2D>() {
@Override
public int compare(Point2D o1, Point2D o2) {
if (o1.getY() == o2.getY()) {
return new Double(o1.getX()).compareTo(o2.getX());
} else {
return new Double(o1.getY()).compareTo(o2.getY());
}
}
});
int max = -1;
int maxX = -1;
int maxY = -1;
for (int count = goldCount; count > 0; count--) {
if (count != goldCount) {
int val = grid[maxY][maxX];
for (int i = 0; i < rowsVal.length; i++) {
rowsVal[i] = rowsVal[i] / val * (val - 1);
}
for (int i = 0; i < colsVal.length; i++) {
colsVal[i] = colsVal[i] / val * (val - 1);
}
}
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int product = colsVal[x] * rowsVal[y];
if (product > max) {
max = product;
maxX = x;
maxY = y;
}
}
}
priorityQueue.add(new Point(maxX, height - maxY - 1));
}
while (priorityQueue.size() > 0) {
Point2D point = priorityQueue.poll();
System.out.println(point.getX() + " " + point.getY());
}
}
out.close();
}
}
|
package fj.swsk.cn.eqapp.subs.more.V;
import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import java.util.List;
import fj.swsk.cn.eqapp.R;
import fj.swsk.cn.eqapp.conf.IConstants;
import fj.swsk.cn.eqapp.main.Common.CommonAdapter;
import fj.swsk.cn.eqapp.main.Common.ViewHolder;
import fj.swsk.cn.eqapp.subs.more.M.DocFile;
import fj.swsk.cn.eqapp.util.FileUtils;
/**
* Created by apple on 16/7/21.
*/
public class EmergencyAdapter extends CommonAdapter<DocFile> {
public View.OnClickListener mListener;
public EmergencyAdapter(Context context, List<DocFile> datas) {
super(context, datas,R.layout.item4lv_emergencylv);
}
@Override
public void convert(ViewHolder holder, DocFile docFile) {
holder.setText(R.id.title,docFile.name);
holder.setText(R.id.size, FileUtils.formatFileSize(docFile.size));
holder.setText(R.id.time, IConstants.TIMESDF.format(docFile.genTime));
holder.setText(R.id.btn, TextUtils.isEmpty(docFile.path)?"下载":"查看");
holder.setTag(R.id.btn, holder.getPosition());
holder.setOnClickListener(R.id.btn,mListener);
}
}
|
package com.pakkalocal.cardmakerui;
import android.app.Application;
import com.google.android.gms.ads.MobileAds;
import com.pakkalocal.cardmakerui.utilsdata.ConnectivityReceiver;
/**
* Created by 2117 on 4/17/2018.
*/
public class Myapplication extends Application {
private static Myapplication mInstance;
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
try {
Class.forName("android.os.AsyncTask");
} catch (Throwable ignore) {
}
MobileAds.initialize(getApplicationContext(), getResources().getString(R.string.App_id));
mInstance = this;
}
public static synchronized Myapplication getInstance() {
return mInstance;
}
public void setConnectivityListener(ConnectivityReceiver.ConnectivityReceiverListener listener) {
ConnectivityReceiver.connectivityReceiverListener = listener;
}
}
|
package com.sys;
import oa.sys.*;
import oa.data.*;
import java.io.*;
import java.sql.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
****************************************************
*类名称: View<br>
*类功能: 浏览公告发布人信息<br>
****************************************************
*/
public class View extends HttpServlet{
private Statement stmt=null;
private ResultSet rs=null;
private Statement stmt1=null;
private ResultSet rs1=null;
private String name,dep,state,tel,sql="SELECT * FROM eminfo where limit=1";
private RequestDispatcher dispatcher=null;
private HttpSession session=null;
private int deid,stateid,id;
private PrintWriter out=null;
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
request.setCharacterEncoding("gb2312");
response.setContentType("text/html; charset=gb2312");
out=response.getWriter();
session=request.getSession();
Collection coll=new ArrayList();
//获取数据
Db db=new Db();
Str str=new Str();
try{
stmt=db.getStmtread();
rs=stmt.executeQuery(sql);
while(rs.next()){
id=rs.getInt(1);
name=rs.getString(2);
deid=rs.getInt(7);
tel=rs.getString(9);
stateid=rs.getInt(11);
dep=db.IdtoDo("Name","department WHERE departmentid="+deid);
state=db.IdtoDo("Name","emstate WHERE stateid="+stateid);
//字符转换
name=str.outStr(name);
dep=str.outStr(dep);
state=str.outStr(state);
tel=str.outStr(tel);
Eminfo eminfo=new Eminfo();
eminfo.setId(id);
eminfo.setName(name);
eminfo.setDepartment(dep);
eminfo.setTel(tel);
eminfo.setState(state);
coll.add(eminfo);
}
}catch(Exception e){
e.printStackTrace();
}finally{
db.close();
request.setAttribute("msg",coll);
dispatcher=request.getRequestDispatcher("view.jsp");
dispatcher.forward(request,response);
}
}
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
doPost(request,response);
}
} |
package com.beanpai.egr.shopping.view;
import com.beanpai.egr.shopping.utils.Common;
import com.mgle.shopping.R;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
/**
* 支付密码
* @author WGQ
*/
public class PaymentPasswordView extends FrameLayout implements View.OnClickListener {
private Context mContext;
private Handler mHandler;
private EditText mEtPayPasswordEditText,mEtPayPasswordsEditText;
private TextView mTvPayNextStepTextView;
public PaymentPasswordView(Context context,Handler mHandler)
{
super(context);
this.mContext = context;
this.mHandler = mHandler;
initView();
}
//初始化布局
@SuppressLint("InflateParams")
private void initView()
{
View localView = LayoutInflater.from(mContext).inflate(R.layout.paypwd_view,null);
addView(localView);
mEtPayPasswordEditText = (EditText) localView.findViewById(R.id.et_pay_password);
mEtPayPasswordsEditText = (EditText) localView.findViewById(R.id.et_pay_passwords);
mTvPayNextStepTextView = (TextView) localView.findViewById(R.id.tv_pay_next_step);
initListener();
}
//绑定事件
private void initListener()
{
mEtPayPasswordEditText.requestFocus();
mTvPayNextStepTextView.setOnClickListener(this);
}
@Override
public void onClick(View view)
{
String password = mEtPayPasswordEditText.getText().toString().trim();
String passwords = mEtPayPasswordsEditText.getText().toString().trim();
if(password.length() == 6)
{
if(password.equals(passwords))
{
mHandler.sendEmptyMessage(Common.SET_PAYMENT_PASSWORD);
}else{
Common.showMessage(mContext, "两次输入的密码不一致!");
}
}else{
Common.showMessage(mContext, "请输入6为纯数字的密码!");
}
}
} |
//designpatterns.state.screen.NormalState.java
package designpatterns.state.screen;
//正常状态类:具体状态类
public class NormalState extends ScreenState{
public void display() {
System.out.println("正常大小!");
}
} |
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.support;
import java.lang.reflect.Method;
import org.junit.jupiter.api.Test;
import org.springframework.aop.ClassFilter;
import org.springframework.aop.MethodMatcher;
import org.springframework.aop.Pointcut;
import org.springframework.aop.interceptor.ExposeInvocationInterceptor;
import org.springframework.aop.target.EmptyTargetSource;
import org.springframework.aop.testfixture.interceptor.NopInterceptor;
import org.springframework.beans.testfixture.beans.TestBean;
import org.springframework.core.testfixture.io.SerializationTestUtils;
import org.springframework.lang.Nullable;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Rod Johnson
* @author Chris Beams
* @author Sebastien Deleuze
*/
public class AopUtilsTests {
@Test
public void testPointcutCanNeverApply() {
class TestPointcut extends StaticMethodMatcherPointcut {
@Override
public boolean matches(Method method, @Nullable Class<?> clazzy) {
return false;
}
}
Pointcut no = new TestPointcut();
assertThat(AopUtils.canApply(no, Object.class)).isFalse();
}
@Test
public void testPointcutAlwaysApplies() {
assertThat(AopUtils.canApply(new DefaultPointcutAdvisor(new NopInterceptor()), Object.class)).isTrue();
assertThat(AopUtils.canApply(new DefaultPointcutAdvisor(new NopInterceptor()), TestBean.class)).isTrue();
}
@Test
public void testPointcutAppliesToOneMethodOnObject() {
class TestPointcut extends StaticMethodMatcherPointcut {
@Override
public boolean matches(Method method, @Nullable Class<?> clazz) {
return method.getName().equals("hashCode");
}
}
Pointcut pc = new TestPointcut();
// will return true if we're not proxying interfaces
assertThat(AopUtils.canApply(pc, Object.class)).isTrue();
}
/**
* Test that when we serialize and deserialize various canonical instances
* of AOP classes, they return the same instance, not a new instance
* that's subverted the singleton construction limitation.
*/
@Test
public void testCanonicalFrameworkClassesStillCanonicalOnDeserialization() throws Exception {
assertThat(SerializationTestUtils.serializeAndDeserialize(MethodMatcher.TRUE)).isSameAs(MethodMatcher.TRUE);
assertThat(SerializationTestUtils.serializeAndDeserialize(ClassFilter.TRUE)).isSameAs(ClassFilter.TRUE);
assertThat(SerializationTestUtils.serializeAndDeserialize(Pointcut.TRUE)).isSameAs(Pointcut.TRUE);
assertThat(SerializationTestUtils.serializeAndDeserialize(EmptyTargetSource.INSTANCE)).isSameAs(EmptyTargetSource.INSTANCE);
assertThat(SerializationTestUtils.serializeAndDeserialize(Pointcuts.SETTERS)).isSameAs(Pointcuts.SETTERS);
assertThat(SerializationTestUtils.serializeAndDeserialize(Pointcuts.GETTERS)).isSameAs(Pointcuts.GETTERS);
assertThat(SerializationTestUtils.serializeAndDeserialize(ExposeInvocationInterceptor.INSTANCE)).isSameAs(ExposeInvocationInterceptor.INSTANCE);
}
@Test
public void testInvokeJoinpointUsingReflection() throws Throwable {
String name = "foo";
TestBean testBean = new TestBean(name);
Method method = ReflectionUtils.findMethod(TestBean.class, "getName");
Object result = AopUtils.invokeJoinpointUsingReflection(testBean, method, new Object[0]);
assertThat(result).isEqualTo(name);
}
}
|
package com.concurrent.features;
import com.concurrent.gateway.SiteReader;
import com.concurrent.gateway.SiteWriter;
import com.concurrent.retreiver.ConcurrentHttpSiteProcessor;
import com.concurrent.retreiver.HttpSiteProcessor;
import com.concurrent.usecase.SiteProcessor;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import cucumber.annotation.en.Given;
import cucumber.annotation.en.Then;
import cucumber.annotation.en.When;
import cucumber.table.DataTable;
import gherkin.formatter.model.DataTableRow;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.core.Is.is;
@RunWith(Enclosed.class)
public class SiteLoaderStepDefs {
public static class A_website_is_retrieved_and_saved {
private SiteReader reader = new FakeReader("/example.html");
private MockWriter writer = new MockWriter();
private SiteProcessor siteProcessor = new HttpSiteProcessor(reader, writer);
private String url;
@Given("^the website \"([^\"]*)\"$")
public void the_website(String url) {
this.url = url;
}
@When("^the site is retrieved$")
public void the_site_is_retrieved() {
siteProcessor.process(url);
}
@Then("^the content is saved$")
public void the_content_is_saved() {
Element h1 = writer.getDocuments().get(0).getElementsByTag("h1").first();
assertThat(h1.text(), is(equalTo("Example Domain")));
}
}
public static class Multiple_websites_are_retrieved_and_saved {
private SiteReader reader = new FakeReader("/example.html");
private MockWriter writer = new MockWriter();
private SiteProcessor siteProcessor = new HttpSiteProcessor(reader, writer);
private ImmutableList<String> urls;
@Given("^the following websites$")
public void the_following_websites(DataTable urlTable) {
urls = ImmutableList.copyOf(Lists.transform(urlTable.getGherkinRows(), new DataTableMapper()));
}
@When("^the sites are retrieved$")
public void the_sites_are_retrieved() {
siteProcessor.process(urls);
}
@Then("^all content is saved$")
public void all_content_is_saved() {
assertThat(writer.getDocuments().size(), is(equalTo(urls.size())));
}
}
public static class Multiple_websites_are_retrieved_and_saved_concurrently {
private SiteReader reader = new FakeReader("/example.html");
private MockWriter writer = new MockWriter();
private SiteProcessor siteProcessor = new ConcurrentHttpSiteProcessor(reader, writer, 2);
private ImmutableList<String> urls;
@Given("^the websites$")
public void the_websites(DataTable urlTable) {
urls = ImmutableList.copyOf(Lists.transform(urlTable.getGherkinRows(), new DataTableMapper()));
}
@When("^the sites are retrieved concurrently$")
public void the_sites_are_retrieved_concurrently() {
siteProcessor.process(urls);
}
@Then("^content is saved concurrently$")
public void content_is_saved_concurrently() {
assertThat(writer.getDocuments().size(), is(equalTo(urls.size())));
}
}
}
class DataTableMapper implements Function<DataTableRow, String> {
@Override
public String apply(DataTableRow dataTableRow) {
return dataTableRow.getCells().get(0);
}
}
class FakeReader implements SiteReader {
private final String filename;
FakeReader(String filename) {
this.filename = filename;
}
@Override
public Document retrieve(String url) {
StringBuffer html = new StringBuffer("");
try {
InputStream stream = getClass().getResourceAsStream(filename);
InputStreamReader isr = new InputStreamReader(stream);
BufferedReader ir = new BufferedReader(isr);
String line;
while ((line = ir.readLine()) != null) {
html.append(line);
}
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}
return Jsoup.parse(html.toString());
}
}
class MockWriter implements SiteWriter {
private List<Document> documents = new ArrayList<>();
@Override
public void write(Document d) {
documents.add(d);
}
List<Document> getDocuments() {
return ImmutableList.copyOf(documents);
}
} |
package com.sherry.epaydigital.controller;
import com.sherry.epaydigital.bussiness.domain.CardDomain;
import com.sherry.epaydigital.bussiness.service.CardService;
import com.sherry.epaydigital.bussiness.service.CustomerService;
import com.sherry.epaydigital.data.model.Customer;
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.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/card")
public class CardController {
CustomerService customerService;
CardService cardService;
@Autowired
public CardController(CustomerService customerService, CardService cardService) {
this.customerService = customerService;
this.cardService = cardService;
}
@GetMapping
public ModelAndView addCard(Model model, HttpSession session){
if (session.getAttribute("isLoggedIn") != null){
ModelAndView modelAndView = new ModelAndView("pages/card/addCard");
model.addAttribute("cardDomain" , new CardDomain());
return modelAndView;
}
else{
return new ModelAndView("redirect:/login");
}
}
@PostMapping
public String addCard(@ModelAttribute("cardDomain") CardDomain cardDomain, HttpSession session){
Customer customer = customerService.getCustomer(session.getAttribute("email").toString());
cardDomain.setCustomer(customer);
cardService.addcard(cardDomain);
return "redirect:card/success";
}
@GetMapping("/success")
public String page(){
return "success";
}
}
|
package com.angular.angular.service;
import com.angular.angular.entity.RoleEntity;
import com.angular.angular.entity.UserEntity;
import com.angular.angular.repository.RoleRepository;
import com.angular.angular.repository.UserRepository;
import com.angular.angular.dto.UserDto;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import javax.management.relation.Role;
import java.util.ArrayList;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private RoleRepository roleRepository;
@Autowired
private PasswordEncoder passwordEncoder;
private ModelMapper modelMapper = new ModelMapper();
@Override
public UserDto createUser(UserDto userDto) {
// Check if username is already taken
UserEntity userEntity = userRepository.findByUsername(userDto.getUsername());
if (userEntity != null) throw new UsernameNotFoundException("User is already exists");
UserEntity userEntity1 = modelMapper.map(userDto, UserEntity.class);
userEntity1.setPassword(passwordEncoder.encode(userDto.getPassword()));
RoleEntity roleEntity = roleRepository.findByRoleName("ROLE_ADMIN");
userEntity1.setRole(roleEntity);
UserEntity savedEntity = userRepository.save(userEntity1);
UserDto userDto1 = modelMapper.map(savedEntity, UserDto.class);
userDto1.setUuid(savedEntity.getId());
return userDto1;
}
}
|
package com.geek._03;
/**
* 思路1:
* 1.暴力法求解,两层loop,只要=target,就返回对应的下标数组
* 2.定义left、right指针,分别从两边向中间收敛,如果和>target,
*/
public class TwoSum {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return null;
}
}
|
package edu.harvard.hms.dbmi.avillach.auth.data.entity;
import java.io.Serializable;
import java.security.Principal;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import javax.persistence.*;
import org.hibernate.annotations.Type;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import edu.harvard.dbmi.avillach.data.entity.BaseEntity;
import edu.harvard.hms.dbmi.avillach.auth.data.entity.*;
/**
* Defines a model of User behavior.
*/
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@Entity(name = "user")
public class User extends BaseEntity implements Serializable, Principal {
@Column(unique = true)
private String subject;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_role",
joinColumns = {@JoinColumn(name = "user_id", nullable = false, updatable = false)},
inverseJoinColumns = {@JoinColumn(name = "role_id", nullable = false, updatable = false)})
private Set<Role> roles;
private String email;
/**
* <p>NOTICE</p>
* <br><p>
* When you update or create a user,
* please use connection.id as the input. The UserService is specifically using connection.id.
* </p>
* <br>
* <p><b>
* Note: This is because of the checkAssociation() method in UserService.
* </b></p><br>
* @see edu.harvard.hms.dbmi.avillach.auth.rest.UserService
*/
@ManyToOne
@JoinColumn(name = "connectionId")
private Connection connection;
private boolean matched;
private Date acceptedTOS;
@Column(name = "auth0_metadata")
@Type(type = "text")
private String auth0metadata;
@Column(name = "general_metadata")
@Type(type = "text")
private String generalMetadata;
@Column(name = "is_active")
private boolean active = true;
@Column(name = "long_term_token")
private String token;
@OneToOne
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name = "credentialId")
private Credential credential;
/**
* This is just so we can pass the password to the access email
*/
@Transient
private String initialPassword;
public String getSubject() {
return subject;
}
public User setSubject(String subject) {
this.subject = subject;
return this;
}
public Set<Role> getRoles() {
return roles;
}
public User setRoles(Set<Role> roles) {
this.roles = roles;
return this;
}
/**
* return all privileges in the roles as a set
* @return
*/
@JsonIgnore
public Set<Privilege> getTotalPrivilege(){
if (roles == null)
return null;
Set<Privilege> privileges = new HashSet<>();
roles.stream().forEach(r -> privileges.addAll(r.getPrivileges()));
return privileges;
}
/**
* return all privileges in the roles as a set
* @return
*/
@JsonIgnore
public Set<AccessRule> getTotalAccessRule(){
if (roles == null)
return null;
Set<AccessRule> accessRules = new HashSet<>();
roles.stream().
forEach(r -> r.getPrivileges().stream().
forEach(p -> accessRules.addAll(p.getAccessRules())));
return accessRules;
}
/**
* return all privilege name in each role as a set.
*
* @return
*/
@JsonIgnore
public Set<String> getPrivilegeNameSet(){
Set<Privilege> totalPrivilegeSet = getTotalPrivilege();
if (totalPrivilegeSet == null)
return null;
Set<String> nameSet = new HashSet<>();
totalPrivilegeSet.stream().forEach(p -> nameSet.add(p.getName()));
return nameSet;
}
/**
* return privilege names in each role as a set based on Application given.
*
* @return
*/
@JsonIgnore
public Set<String> getPrivilegeNameSetByApplication(Application application){
Set<Privilege> totalPrivilegeSet = getTotalPrivilege();
if (totalPrivilegeSet == null)
return null;
Set<String> nameSet = new HashSet<>();
if (application == null)
return nameSet;
for (Privilege appPrivilege : application.getPrivileges()) {
for (Privilege userPrivilege : totalPrivilegeSet) {
if (appPrivilege.equals(userPrivilege))
nameSet.add(userPrivilege.getName());
}
}
return nameSet;
}
/**
* return privileges in each role as a set based on Application given.
*
* @return
*/
@JsonIgnore
public Set<Privilege> getPrivilegesByApplication(Application application){
if (application == null || application.getUuid() == null){
return getTotalPrivilege();
}
if (roles == null)
return null;
Set<Privilege> privileges = new HashSet<>();
roles.stream().
forEach(r -> privileges.addAll(r.getPrivileges()
.stream()
.filter(p -> application.getUuid()
.equals((p.getApplication()==null)?
null:
p.getApplication().getUuid()))
.collect(Collectors.toSet())));
return privileges;
}
@JsonIgnore
public String getPrivilegeString(){
Set<Privilege> totalPrivilegeSet = getTotalPrivilege();
if (totalPrivilegeSet == null)
return null;
return totalPrivilegeSet.stream().map(p -> p.getName()).collect(Collectors.joining(","));
}
@JsonIgnore
public String getRoleString(){
return (roles==null)?null:roles.stream().map(r -> r.getName())
.collect(Collectors.joining(","));
}
public String getAuth0metadata() {
return auth0metadata;
}
public User setAuth0metadata(String auth0metadata) {
this.auth0metadata = auth0metadata;
return this;
}
public String getGeneralMetadata() {
return generalMetadata;
}
public User setGeneralMetadata(String generalMetadata) {
this.generalMetadata = generalMetadata;
return this;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Connection getConnection() {
return connection;
}
public User setConnection(Connection connection) {
this.connection = connection;
return this;
}
public boolean isMatched() {
return matched;
}
public void setMatched(boolean matched) {
this.matched = matched;
}
public Date getAcceptedTOS() {
return acceptedTOS;
}
public void setAcceptedTOS(Date acceptedTOS) {
this.acceptedTOS = acceptedTOS;
}
@JsonIgnore
@Override
public String getName() {
return this.subject;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
/**
* <p>Inner class defining limited user attributes returned from the User endpoint.</p>
*/
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public static class UserForDisplay {
String uuid;
String email;
Set<String> privileges;
String token;
Set<String> queryScopes;
public UserForDisplay() {
}
public String getEmail() {
return email;
}
public UserForDisplay setEmail(String email) {
this.email = email;
return this;
}
public Set<String> getPrivileges() {
return privileges;
}
public UserForDisplay setPrivileges(Set<String> privileges) {
this.privileges = privileges;
return this;
}
public String getUuid() {
return uuid;
}
public UserForDisplay setUuid(String uuid) {
this.uuid = uuid;
return this;
}
public String getToken() {
return token;
}
public UserForDisplay setToken(String token) {
this.token = token;
return this;
}
public Set<String> getQueryScopes() {
return queryScopes;
}
public void setQueryScopes(Set<String> queryScopes) {
this.queryScopes = queryScopes;
}
}
public String toString() {
return uuid.toString() + " ___ " + subject + " ___ " + email + " ___ " + generalMetadata + " ___ " + auth0metadata + " ___ {" + ((connection==null)?null:connection.toString()) + "}";
}
public Credential getCredential() {
return credential;
}
public void setCredential(Credential credential) {
this.credential = credential;
}
public String getInitialPassword() {
return initialPassword;
}
public void setInitialPassword(String initialPassword) {
this.initialPassword = initialPassword;
}
}
|
package com.knoldus.supervisor;
import akka.actor.*;
import akka.testkit.JavaTestKit;
import akka.util.Timeout;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import scala.PartialFunction;
import scala.runtime.BoxedUnit;
import java.util.concurrent.TimeUnit;
import static akka.pattern.PatternsCS.ask;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* Created by Harmeet Singh(Taara) on 30/9/16.
*/
public class ActorSupervisorTest {
private static ActorSystem system;
@BeforeClass
public static void init() {
system = ActorSystem.create();
}
@AfterClass
public static void destroy() {
JavaTestKit.shutdownActorSystem(system);
system = null;
}
@Test
public void testProps() {
Props props = ActorSupervisor.props();
assertThat(props.actorClass(), is(equalTo(ActorSupervisor.class)));
}
@Test
public void testReceiveMessage() throws Exception {
final Props props = Props.create(TestActor.class);
final Props supervisorProps = ActorSupervisor.props();
final ActorRef supervisor = system.actorOf(supervisorProps, "ActorSupervisor");
ActorRef childActor = (ActorRef) ask(supervisor, props, Timeout.apply(1, TimeUnit.SECONDS))
.toCompletableFuture().get(2, TimeUnit.SECONDS);
assertTrue(childActor.path().parent().name().equals("ActorSupervisor"));
}
final static class TestActor extends AbstractLoggingActor {
public TestActor() {}
}
}
|
package net.awesomekorean.podo.lesson.lessons;
public interface LessonSpecial {
String getLessonId();
String getLessonTitle();
String getLessonSubTitle();
int getContents();
}
|
package org.techtown.mycheck;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.goodiebag.protractorview.ProtractorView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import org.w3c.dom.Text;
import java.io.IOException;
import java.net.CookieManager;
import java.net.Socket;
import static android.content.Context.MODE_PRIVATE;
/**
* A simple {@link Fragment} subclass.
*/
public class homeFragment extends Fragment {
private FirebaseDatabase firebaseDatabase=FirebaseDatabase.getInstance();
private DatabaseReference androidDatabase=firebaseDatabase.getReference();
private DatabaseReference arduinoDatabase=firebaseDatabase.getReference();
private DatabaseReference rasDatabase=firebaseDatabase.getReference();
private ChildEventListener mChildEventListener;
String msg;
String shared="Nodata";
private ToggleButton VideoButton;
private ToggleButton fireballButton;
//ProtractorView protractorView1=new ProtractorView(getContext());
private ProtractorView protractorView1;
private ProtractorView protractorView2;
private Animation fab_open,fab_close;
private Boolean isFabOpen=false;
private FloatingActionButton fab,fab0,fab1,fab2;
public homeFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
((MainActivity)getActivity()).settingActionBarTitle("홈");
View v=inflater.inflate(R.layout.fragment_home, container, false);
initDatabase();
fab_open= AnimationUtils.loadAnimation(getActivity(),R.anim.fab_open);
fab_close=AnimationUtils.loadAnimation(getActivity(),R.anim.fab_close);
fab=(FloatingActionButton)v.findViewById(R.id.fab);
fab0=(FloatingActionButton)v.findViewById(R.id.fab0);
fab1=(FloatingActionButton)v.findViewById(R.id.fab1);
fab2=(FloatingActionButton)v.findViewById(R.id.fab2);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isFabOpen) {
button_close();
} else {
button_open();
}
}
});
fab0.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
arduinoDatabase.child("fireball").setValue("3");
Vibrator myVib;
myVib=(Vibrator)getActivity().getSystemService(Context.VIBRATOR_SERVICE);
myVib.vibrate(50);
button_close();
}
});
fab1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
arduinoDatabase.child("fireball").setValue("1");
Vibrator myVib;
myVib=(Vibrator)getActivity().getSystemService(Context.VIBRATOR_SERVICE);
myVib.vibrate(50);
button_close();
}
});
fab2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
arduinoDatabase.child("fireball").setValue("2");
Vibrator myVib;
myVib=(Vibrator)getActivity().getSystemService(Context.VIBRATOR_SERVICE);
myVib.vibrate(50);
button_close();
}
});
//final TextView TEST_EditText=(TextView)v.findViewById(R.id.TEST_TextView);
//firebase에서 android 폴더 안 데이터 읽기
androidDatabase=firebaseDatabase.getReference("android");
androidDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot messageData:dataSnapshot.getChildren()){
msg=messageData.getValue().toString();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
//firebase에서 arduino 폴더 안 데이터 읽기
arduinoDatabase=firebaseDatabase.getReference("arduino");
arduinoDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot messageData:dataSnapshot.getChildren()){
msg=messageData.getValue().toString();
if(msg.equals("01")){
protractorView1.setAngle(0);
arduinoDatabase.child("firepower1").setValue("W");
arduinoDatabase.child("arduino").setValue("null");
}
if(msg.equals("02")){
protractorView2.setAngle(0);
arduinoDatabase.child("firepower2").setValue("W");
arduinoDatabase.child("arduino").setValue("null");
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
//firebase에서 ras 폴더 안 데이터 읽기
rasDatabase=firebaseDatabase.getReference("ras");
rasDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot messageData:dataSnapshot.getChildren()){
msg=messageData.getValue().toString();
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
//가스벨브 버튼 선택 제어
fireballButton=(ToggleButton)v.findViewById(R.id.fireball_button);
fireballButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
protractorView1.setVisibility(View.VISIBLE);
protractorView2.setVisibility(View.INVISIBLE);
fireballButton.setSelected(true);
}
else{
protractorView1.setVisibility(View.INVISIBLE);
protractorView2.setVisibility(View.VISIBLE);
fireballButton.setSelected(false);
}
}
});
//가스벨브 1번 제어
protractorView1=(ProtractorView)v.findViewById(R.id.protractorView1);
protractorView1.setOnProtractorViewChangeListener(new ProtractorView.OnProtractorViewChangeListener() {
@Override
public void onProgressChanged(ProtractorView protractorView, int i, boolean b) {
if(i>0 && i<30){
arduinoDatabase.child("firepower1").setValue("W");
}
if(i>=30 && i<90){
arduinoDatabase.child("firepower1").setValue("X");
}
if(i>=90 && i<150){
arduinoDatabase.child("firepower1").setValue("Y");
}
if(i>=150 && i<=180){
arduinoDatabase.child("firepower1").setValue("Z");
}
if(i==2|i==60||i==120||i==179){
Vibrator myVib;
myVib=(Vibrator)getActivity().getSystemService(Context.VIBRATOR_SERVICE);
myVib.vibrate(30);
}
}
@Override
public void onStartTrackingTouch(ProtractorView protractorView) {
}
@Override
public void onStopTrackingTouch(ProtractorView protractorView) {
}
});
//가스벨브 2번 제어
protractorView2=(ProtractorView)v.findViewById(R.id.protractorView2);
protractorView2.setOnProtractorViewChangeListener(new ProtractorView.OnProtractorViewChangeListener() {
@Override
public void onProgressChanged(ProtractorView protractorView, int i, boolean b) {
if(i>0 && i<30){
arduinoDatabase.child("firepower2").setValue("W");
}
if(i>=30 && i<90){
arduinoDatabase.child("firepower2").setValue("X");
}
if(i>=90 && i<150){
arduinoDatabase.child("firepower2").setValue("Y");
}
if(i>=150 && i<=180){
arduinoDatabase.child("firepower2").setValue("Z");
}
if(i==2|i==60||i==120||i==179){
Vibrator myVib;
myVib=(Vibrator)getActivity().getSystemService(Context.VIBRATOR_SERVICE);
myVib.vibrate(30);
}
}
@Override
public void onStartTrackingTouch(ProtractorView protractorView) {
}
@Override
public void onStopTrackingTouch(ProtractorView protractorView) {
}
});
SharedPreferences prefs=this.getActivity().getSharedPreferences("firepower",MODE_PRIVATE);
int protra1=prefs.getInt("protra1",0);
int protra2=prefs.getInt("protra2",0);
protractorView1.setAngle(protra1);
protractorView2.setAngle(protra2);
Boolean check=prefs.getBoolean("check",true);
fireballButton.setChecked(check);
//비디오 재생 & 전원버튼
final WebView VideoView=(WebView)v.findViewById(R.id.videoView);
VideoButton=(ToggleButton)v.findViewById(R.id.powerButton);
VideoButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
//getActivity().startService(new Intent(getActivity(),MyService.class));
rasDatabase.child("ras").setValue("O");
//비디오 스트리밍
VideoView.getSettings().setJavaScriptEnabled(true);
VideoView.getSettings().setLoadWithOverviewMode(true);
VideoView.getSettings().setUseWideViewPort(true);
VideoView.setInitialScale(370);
VideoView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
VideoView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
VideoView.setScrollbarFadingEnabled(true);
String url="http://223.194.171.105:8090/javascript_simple.html";
VideoView.loadUrl(url);
//줌 인 or 줌 아웃
VideoView.getSettings().setBuiltInZoomControls(true);
VideoView.getSettings().setSupportZoom(true);
Toast.makeText(getContext(),"ON",Toast.LENGTH_SHORT).show();
VideoButton.setSelected(true);
}else{
arduinoDatabase.child("fireball").setValue("0");
arduinoDatabase.child("firepower1").setValue("W");
arduinoDatabase.child("firepower2").setValue("W");
rasDatabase.child("ras").setValue("0");
VideoView.getSettings().setJavaScriptEnabled(false);
VideoView.getSettings().setLoadWithOverviewMode(false);
VideoView.getSettings().setUseWideViewPort(false);
String url1="about:blank";
VideoView.loadUrl(url1);
Toast.makeText(getContext(),"OFF",Toast.LENGTH_SHORT).show();
VideoButton.setSelected(false);
//getActivity().stopService(new Intent(getActivity().getApplicationContext(),MyService.class));
}
}
});
//기억생성
SharedPreferences sharedPreferences=this.getActivity().getSharedPreferences(shared,Context.MODE_PRIVATE);
Boolean memory=sharedPreferences.getBoolean("Video",false);
VideoButton.setChecked(memory);
return v;
}
private void initDatabase(){
/* firebaseDatabase=FirebaseDatabase.getInstance();
databaseReference=firebaseDatabase.getReference("user");
databaseReference.child("user").setValue("check");*/
mChildEventListener=new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
};
androidDatabase.addChildEventListener(mChildEventListener);
}
public void button_open(){
fab0.startAnimation(fab_open);
fab1.startAnimation(fab_open);
fab2.startAnimation(fab_open);
fab1.setClickable(true);
fab1.setClickable(true);
fab2.setClickable(true);
isFabOpen = true;
}
public void button_close(){
fab0.startAnimation(fab_close);
fab1.startAnimation(fab_close);
fab2.startAnimation(fab_close);
fab1.setClickable(false);
fab1.setClickable(false);
fab2.setClickable(false);
isFabOpen = false;
}
@Override
public void onDestroy() {
super.onDestroy();
//기억 하기
SharedPreferences sharedPreferences=this.getActivity().getSharedPreferences(shared,0);
SharedPreferences.Editor editor=sharedPreferences.edit();
Boolean memory=VideoButton.isChecked();
editor.putBoolean("Video",memory);
SharedPreferences prefs=this.getActivity().getSharedPreferences("firepower",MODE_PRIVATE);
SharedPreferences.Editor editor1=prefs.edit();
int protra1=protractorView1.getAngle();
editor1.putInt("protra1",protra1);
int protra2=protractorView2.getAngle();
editor1.putInt("protra2",protra2);
Boolean check=fireballButton.isChecked();
editor1.putBoolean("check",check);
editor.commit();
editor1.commit();
getActivity().startService(new Intent(getActivity(),MyService.class));
}
}
|
package core.heroes.original;
import core.heroes.skills.HuangZhongSharpshooterHeroSkill;
public class HuangZhong extends AbstractHero {
private static final long serialVersionUID = 1L;
public HuangZhong() {
super(4, Faction.SHU, Gender.MALE, "Huang Zhong", new HuangZhongSharpshooterHeroSkill());
}
}
|
package resources.todo;
import java.io.IOException;
import java.io.StringReader;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.websocket.CloseReason;
import javax.websocket.DecodeException;
import javax.websocket.EncodeException;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ws.AbstractSocket;
import ws.Action;
import ws.Message;
@Stateless
@ServerEndpoint(value = "/todo", encoders = { Message.MessageCoder.class }, decoders = { Message.MessageCoder.class })
public class TodoSocket extends AbstractSocket implements Observer {
protected final Logger log = LoggerFactory.getLogger(this.getClass());
Session currentSession = null;
Message.MessageCoder coder = new Message.MessageCoder();
Actions actions = new Actions();
@EJB
private TodoItemDAO dao;
@OnOpen
public void onOpen(Session session, EndpointConfig ec) {
currentSession = session;
coder.init(ec);
actions.init(ec);
}
@OnMessage
public void receiveMessage(String message, final Session session) {
try {
Message msg = coder.decode(new StringReader(message));
log.debug("Received message " + message);
for (Action<?> action : actions.values()) {
if (action.decodes(msg)) {
if (action.equals(Actions.LIST)) {
dao.addObserver(this);
sendMessage(Actions.LIST, new TodoItem.TodoItems(dao.list()));
}
}
}
} catch (DecodeException | IOException e) {
e.printStackTrace();
}
}
/**
* Send a message to all clients in the same room as this client.
*
* @param message
*/
public <T> void sendMessage(Action<T> action, T obj) {
try {
if (this.currentSession.isOpen()) {
this.currentSession.getBasicRemote().sendObject(action.encode(obj));
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (EncodeException e) {
e.printStackTrace();
}
}
@OnClose
public void onClose(Session session, CloseReason reason) {
log.debug("Session closed.");
try {
this.dao.deleteObserver(this);
} catch (Exception e) {
// ignore ...
}
}
@OnError
public void onError(Throwable t) {
// no error processing will be done for this sample
t.printStackTrace();
}
@Override
@SuppressWarnings("unchecked")
public void update(Observable o, Object object) {
if (object instanceof List) {
log.debug("Update List on session...");
this.sendMessage(Actions.LIST, new TodoItem.TodoItems((List<TodoItem>) object));
}
}
}
|
package com.camila.web.DTO.inp.cliente;
import java.util.List;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import com.camila.web.dominio.models.Carrinho;
import com.camila.web.dominio.models.Compra;
public class clienteInputDTO {
private String nome;
private String email;
private Long CPF;
private String senha;
//private Carrinho carrinho;
//private List<Compra> compras;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Long getCPF() {
return CPF;
}
public void setCPF(Long cPF) {
CPF = cPF;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
}
|
package com.arthur.leetcode;
import java.util.Arrays;
/**
* @program: leetcode
* @description: 跳跃游戏
* @title: No55_2
* @Author hengmingji
* @Date: 2021/12/22 21:19
* @Version 1.0
*/
public class No55_2 {
public boolean canJump(int[] nums) {
int max = 0;
int i = 0;
while (i <= max) {
max = Math.max(max, i + nums[i]);
if(max >= nums.length - 1) {
return true;
}
i++;
}
return false;
}
}
|
package com.bofsoft.laio.customerservice.DataClass.index;
import com.bofsoft.laio.data.BaseData;
/**
* 招生产品价格
*
* @author yedong
*/
public class EnrollProPriceData extends BaseData {
public int RegType; // 招生产品分类,0一费制,1计时计程
public float Price; // 指导价
public float SalePrice; // 售价
}
|
package mx.com.otss.barbershopapp.activities.menu_inferior;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import mx.com.otss.barbershopapp.R;
import mx.com.otss.barbershopapp.activities.citas.MenuCitasActivity;
import mx.com.otss.barbershopapp.activities.clientes.PrincipalClientesActivity;
import mx.com.otss.barbershopapp.activities.comisiones.MenuComisionesActivity;
import mx.com.otss.barbershopapp.activities.cortesias.MenuCortesiasActivity;
import mx.com.otss.barbershopapp.activities.pagos.MenuPagosActivity;
import mx.com.otss.barbershopapp.activities.promociones.MenuPromocionesActivity;
public class ListadosActivity extends AppCompatActivity {
private String nombreFranquicia;
private Menu menu;
private MenuItem menuItem;
private BottomNavigationView navigation;
private Button btn1, btn2, btn3, btn4, btn5, btn6;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
/**
*
* @param item
* @return
*/
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_inferior_empleados:
Intent intentPrincipalEmpleados=new Intent(getApplication(),PrincipalEmpleadosActivity.class);
intentPrincipalEmpleados.putExtra("nombreFranquicia", getNombreFranquicia());
finish();
startActivity(intentPrincipalEmpleados);
return true;
case R.id.menu_inferior_servicios:
Intent intentPrincipalServicios=new Intent(getApplication(),PrincipalServiciosActivity.class);
intentPrincipalServicios.putExtra("nombreFranquicia", getNombreFranquicia());
finish();
startActivity(intentPrincipalServicios);
return true;
case R.id.menu_inferior_franquicias:
Intent intentPrincipalFranquicias = new Intent(getApplicationContext(), PrincipalFranquiciasActivity.class);
intentPrincipalFranquicias.putExtra("nombreFranquicia", getNombreFranquicia());
finish();
startActivity(intentPrincipalFranquicias);
return true;
case R.id.menu_inferior_listados:
Intent intentPrincipalClientes = new Intent(getApplicationContext(), ListadosActivity.class);
intentPrincipalClientes.putExtra("nombreFranquicia", getNombreFranquicia());
finish();
startActivity(intentPrincipalClientes);
return true;
case R.id.menu_inferior_reportes:
Intent intentReportes = new Intent(getApplicationContext(), ReportesActivity.class);
intentReportes.putExtra("nombreFranquicia", getNombreFranquicia());
finish();
startActivity(intentReportes);
return true;
}
return false;
}
};
/**
*
* @param savedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listados);
Intent intent_receptor = getIntent();
nombreFranquicia = intent_receptor.getStringExtra("nombreFranquicia");
setNombreFranquicia(nombreFranquicia);
navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
menu = navigation.getMenu();
menuItem = menu.getItem(3);
menuItem.setChecked(true);
btn1 = (Button)findViewById(R.id.btnClientes);
btn2 = (Button)findViewById(R.id.btnCitas);
btn3 = (Button)findViewById(R.id.btnComisiones);
btn4 = (Button)findViewById(R.id.btnCortesia);
btn5 = (Button)findViewById(R.id.btnPagos);
btn6 = (Button)findViewById(R.id.btnPromociones);
btn1.setOnClickListener(new View.OnClickListener() {
/**
*
* @param v
*/
@Override
public void onClick(View v) {
Intent intent1 = new Intent(getApplicationContext(), PrincipalClientesActivity.class);
intent1.putExtra("nombreFranquicia", getNombreFranquicia());
finish();
startActivity(intent1);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
/**
*
* @param v
*/
@Override
public void onClick(View v) {
Intent intent2 = new Intent(getApplicationContext(), MenuCitasActivity.class);
intent2.putExtra("nombreFranquicia", getNombreFranquicia());
finish();
startActivity(intent2);
}
});
btn3.setOnClickListener(new View.OnClickListener() {
/**
*
* @param v
*/
@Override
public void onClick(View v) {
Intent intent3 = new Intent(getApplicationContext(), MenuComisionesActivity.class);
intent3.putExtra("nombreFranquicia", getNombreFranquicia());
finish();
startActivity(intent3);
}
});
btn4.setOnClickListener(new View.OnClickListener() {
/**
*
* @param v
*/
@Override
public void onClick(View v) {
Intent intent4 = new Intent(getApplicationContext(), MenuCortesiasActivity.class);
intent4.putExtra("nombreFranquicia", getNombreFranquicia());
finish();
startActivity(intent4);
}
});
btn5.setOnClickListener(new View.OnClickListener() {
/**
*
* @param v
*/
@Override
public void onClick(View v) {
Intent intent5 = new Intent(getApplicationContext(), MenuPagosActivity.class);
intent5.putExtra("nombreFranquicia", getNombreFranquicia());
finish();
startActivity(intent5);
}
});
btn6.setOnClickListener(new View.OnClickListener() {
/**
*
* @param v
*/
@Override
public void onClick(View v) {
Intent intent6 = new Intent(getApplicationContext(), MenuPromocionesActivity.class);
intent6.putExtra("nombreFranquicia", getNombreFranquicia());
finish();
startActivity(intent6);
}
});
}
/**
*
* @param menu
* @return
*/
//menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_superior, menu);
return true;
}
/**
*
* @param item
* @return
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.menu_superior_otros){
Intent intentMenuComisiones = new Intent(getApplicationContext(), MenuComisionesActivity.class);
startActivity(intentMenuComisiones);
}
if (id == R.id.menu_superior_salir) {
finish();
}
return super.onOptionsItemSelected(item);
}
/**
*
* @return
*/
public String getNombreFranquicia() {
return nombreFranquicia;
}
/**
*
* @param nombreFranquicia
*/
public void setNombreFranquicia(String nombreFranquicia) {
this.nombreFranquicia = nombreFranquicia;
}
}
|
package racingcar.domain;
import racingcar.random.PositiveIntUnder10Generator;
import racingcar.random.RandomIntGenerator;
import java.util.Collections;
import java.util.List;
public class RacingCarGroup {
private List<Car> cars;
private RandomIntGenerator randomIntGenerator;
public RacingCarGroup(List<Car> cars) {
this(cars, new PositiveIntUnder10Generator());
}
public RacingCarGroup(List<Car> cars, RandomIntGenerator randomIntGenerator) {
this.cars = cars;
this.randomIntGenerator = randomIntGenerator;
}
public List<Car> getCars() {
return Collections.unmodifiableList(cars);
}
public void go() {
this.cars.forEach(car -> {
int randomInt = this.randomIntGenerator.getRandomInt();
car.goWhenGreaterThanThreshold(randomInt);
});
}
public void initialize() {
this.cars.forEach(Car::initialize);
}
}
|
package netistrar.clientapi.objects.transaction;
import java.util.Map;
/**
* Domain name error object
*/
public class TransactionError {
/**
* Either set to VALIDATION or OPERATION according to the type of error which this object represents.
*/
protected String type;
/**
* The following error codes can occur when the type is set to <b>OPERATION</b><br />
* <b>PAYMENT_ERROR:</b> If it has not been possible to collect payment for a costed transaction. This will be qualified with a reason message.
* <b>DOMAIN_UNAVAILABLE_FOR_REGISTRATION:</b> When an attempt is made to register a domain which is not available.
* <b>DOMAIN_ALREADY_IN_ACCOUNT:</b> When an attempt is made to register a domain which is already in your account.
* <b>DOMAIN_NOT_IN_ACCOUNT:</b> When an attempt is made to utilise a domain which is not in your account.
* <b>DOMAIN_INVALID_FOR_CANCELLATION:</b> When an attempt is made to cancel a domain which is not in a valid state for cancellation
* <b>DOMAIN_INVALID_FOR_RENEWAL:</b> An attempt has been made to renew a domain which is not valid for renewal. Only domains with a status value of <b>ACTIVE</b> or <b>EXPIRED</b> can be renewed.
* <b>DOMAIN_INVALID_FOR_GLUE_RECORD:</b> An attempt has been made to manage glue records for a domain which is not in <b>ACTIVE</b> status.
* <b>DOMAIN_MISSING_GLUE_RECORD:</b> An attempt has been made to remove a glue record for a domain where the glue record has not been defined.
* <b>DOMAIN_TRANSFER_NOT_PENDING_CONFIRMATION:</b> An attempt has been made to resend an owner confirmation for a domain which is not currently pending confirmation.
* <b>DOMAIN_TRANSFER_INVALID_REGISTRAR_IDENTIFIER:</b> An attempt has been made to transfer a domain out using a push transfer using a registrar identifier which does not exist.
* <b>DOMAIN_TRANSFER_NONE_PUSH_DOMAIN:</b> An attempt has been made to initiate a transfer out for a domain which does not support push transfers.
* <b>DOMAIN_TRANSFER_NOT_CANCELLABLE:</b> An attempt has been made to cancel a domain transfer for a domain which is not currently either pending confirmation or awaiting response.
* <b>DOMAIN_REGISTRATION_ERROR:</b> An unexpected error occurred when attempting to register this domain at the registry. This will be qualified with a registry specific message giving further details.
* <b>DOMAIN_TRANSFER_ERROR:</b> An unexpected error occurred when attempting a transfer operation. This will be qualified with a registry specific message giving further details.
* <b>DOMAIN_OWNER_NOT_PENDING_CHANGES:</b> An attempt was made to cancel owner verification changes for a domain name owner which has no pending changes.
* <b>GSUITE_DOMAIN_NOT_AVAILABLE:</b> When the domain supplied for a G Suite create operation is already attached to another subscription externally.
* <b>GSUITE_DOMAIN_ALREADY_ATTACHED:</b> When the domain supplied for a G Suite create operation is already attached to a G Suite subscription in your account.
* <b>UNEXPECTED_TRANSACTION_ERROR:</b> When a general unexpected error occurs with a transaction. This will be qualified with a reason message where possible.
* <br>
* The following error codes can occur when the type is set to <b>VALIDATION</b><br />
* For Domain name Validation errors the following codes can occur.<br />
* <b>DOMAIN_MISSING_OWNER_CONTACT:</b> When a blank owner contact has been supplied to a domain operation
* <b>DOMAIN_INVALID_OWNER_CONTACT:</b> When the owner contact supplied for an operation is invalid. In this case the <b>relatedValidationErrors</b> member will be populated with an array of
* contact specific errors from the list of contact validation errors below.
* <b>DOMAIN_MISSING_ADMIN_CONTACT:</b> When a blank admin contact has been supplied to a domain operation for which the TLD for that domain requires an admin contact.
* <b>DOMAIN_INVALID_ADMIN_CONTACT:</b> When the admin contact supplied for an operation is invalid. In this case the <b>relatedValidationErrors</b> member will be populated with an array of
* contact specific errors from the list of contact validation errors below.
* <b>DOMAIN_MISSING_TECHNICAL_CONTACT:</b> When a blank technical contact has been supplied to a domain operation for which the TLD for that domain requires a technical contact.
* <b>DOMAIN_INVALID_TECHNICAL_CONTACT:</b> When the technical contact supplied for an operation is invalid. In this case the <b>relatedValidationErrors</b> member will be populated with an array of
* contact specific errors from the list of contact validation errors below.
* <b>DOMAIN_MISSING_BILLING_CONTACT:</b> When a blank billing contact has been supplied to a domain operation for which the TLD for that domain requires a billing contact.
* <b>DOMAIN_INVALID_BILLING_CONTACT:</b> When the billing contact supplied for an operation is invalid. In this case the <b>relatedValidationErrors</b> member will be populated with an array of
* contact specific errors from the list of contact validation errors below.
* <b>DOMAIN_TOO_FEW_NAMESERVERS:</b> When the set of nameservers supplied for a domain operation is fewer than is required for the TLD for the domain name in question.
* <b>DOMAIN_INVALID_NAMESERVER_FORMAT:</b> When one or more of the array of nameservers supplied for a domain operation is not in valid nameserver format. In this case the <a href="#extraData">extraData</a> member will be populated with an
* array of integers representing the index(es) of the problematic nameserver(s) in the supplied nameserver array.
* <b>DOMAIN_TOO_MANY_REGISTRATION_YEARS:</b> When the number of years supplied to a domain name operation exceeds the maximum allowed for that domain name.<br>
* The following Contact Validation error codes can occur for Domain Transfer operations<br />
* <b>TRANSFER_DOMAIN_IN_ACCOUNT:</b> The domain name requested for transfer is already in your account
* <b>TRANSFER_DOMAIN_NOT_REGISTERED:</b> If the domain name requested for transfer has not yet been registered
* <b>TRANSFER_DOMAIN_MISSING_AUTHCODE:</b> If an authorisation code was not supplied for a domain name requested for transfer
* <b>TRANSFER_DOMAIN_INVALID_AUTHCODE:</b> If an invalid authorisation code was supplied for a domain name requested for transfer
* <b>TRANSFER_DOMAIN_LOCKED:</b> If a request is made for a domain which is currently locked for transfer. In order to proceed with a transfer it is necessary to unlock the domain via the existing Registrar.
* <b>TRANSFER_DOMAIN_60_DAY_REG_LOCK:</b> If a request is made for a domain which was registered less than 60 days ago.
* <b>TRANSFER_ALREADY_STARTED:</b> If a request is made for a domain which is already in the middle of a transfer operation to another Registrar
* <b>TRANSFER_DOMAIN_NOT_ASSIGNED:</b> If the transfer for a given domain requires a push operation and the domain has not yet been pushed (assigned) to Netistrar.<br>
* The following Contact Validation error codes can occur for Contact and Domain operations<br />
* <b>CONTACT_MISSING_NAME:</b> When a blank name is supplied for a domain contact.
* <b>CONTACT_MISSING_EMAIL:</b> When a blank email address is supplied for a domain contact.
* <b>CONTACT_INVALID_EMAIL_FORMAT:</b> When the contact email address is supplied in none email address format.
* <b>CONTACT_MISSING_STREET_1:</b> When a blank street 1 value is supplied for a domain contact.
* <b>CONTACT_MISSING_CITY:</b> When a blank city value is supplied for a domain contact.
* <b>CONTACT_MISSING_COUNTY:</b> When a blank county value is supplied for a domain contact.
* <b>CONTACT_MISSING_POSTCODE:</b> When a blank postcode value is supplied for a domain contact.
* <b>CONTACT_INVALID_COUNTRY:</b> When an invalid country value (i.e. not in ISO 2 digit country code format) is supplied for a domain contact.
* <b>CONTACT_UNSUPPORTED_COUNTRY:</b> When the TLD represented by a domain contact only allows contact within certain countries e.g. .EU and another country code is supplied
* <b>CONTACT_MISSING_TELEPHONE:</b> When the TLD represented by a domain contact requires a telephone number to be supplied and it is blank.
* <b>CONTACT_INVALID_TELEPHONE:</b> When an invalid telephone number is supplied for a domain contact (i.e. should be a local number without spaces).
* <b>CONTACT_MISSING_TELEPHONE_DIALLING_CODE:</b> When a blank telephone dialling code is supplied for a domain contact when a telephone number has also been supplied.
* <b>CONTACT_INVALID_TELEPHONE_DIALLING_CODE:</b> When the telephone dialling code has been supplied in an invalid format (should start with a + e.g. +44 or +1)
* <b>CONTACT_MISSING_FAX:</b> When the TLD represented by a domain contact requires a fax number to be supplied and it is blank.
* <b>CONTACT_INVALID_FAX:</b> When an invalid fax number is supplied for a domain contact (i.e. should be a local number without spaces).
* <b>CONTACT_MISSING_FAX_DIALLING_CODE:</b> When a blank fax dialling code is supplied for a domain contact when a fax number has also been supplied.
* <b>CONTACT_INVALID_FAX_DIALLING_CODE:</b> When the fax dialling code has been supplied in an invalid format (should start with a + e.g. +44 or +1.<br>
* The following Validation error codes can occur for Contact operations on UK Nominet Domains.<br />
* <b>CONTACT_MISSING_NOMINETREGISTRANTTYPE:</b> When a blank value has been supplied for the additional Nominet Registrant Type field for a UK domain contact
* <b>CONTACT_INVALID_NOMINETREGISTRANTTYPE:</b> When an invalid value has been supplied for the additional Nominet Registrant Type field for a UK domain contact (should be one of LTD,PLC,PTNR,STRA,LLP,IP,IND,SCH,RCHAR,GOV,CRC,STAT,OTHER).
*<b>CONTACT_MISSING_NOMINETCOMPANYNUMBER:</b> When a blank value has been supplied for the additional Nominet Company Number field for a UK domain contact when it is required (in the cases that the Registrant Type is LTD, PLC, LLP, IP, SCH or RCHAR).<br>
* The following Validation error codes can occur for Domain Glue Record operations.<br />
* <b>GLUE_RECORD_MISSING_SUBDOMAIN:</b> When no subdomain (prefix) is supplied for a Domain Glue Record.
* <b>GLUE_RECORD_INVALID_SUBDOMAIN:</b> When an invalid subdomain (prefix) has been supplied for a Domain Glue Record.
* <b>GLUE_RECORD_MISSING_IP_ADDRESS:</b> When no IP address (either IPv4 or IPv6) has been supplied for a Domain Glue Record.
* <b>GLUE_RECORD_INVALID_IPV4_ADDRESS:</b> When an invalid IPv4 address has been supplied for a Domain Glue Record.
* <b>GLUE_RECORD_INVALID_IPV6_ADDRESS:</b> When an invalid IPv6 address has been supplied for a Domain Glue Record.
*/
protected String code;
/**
* An accompanying message for display if required for this error.
*/
protected String message;
/**
* An associative array of additional info if relevant for this error
*/
protected Map<String,Object> additionalInfo;
/**
* Any associated errors mostly in the validation case.
*/
protected Map<String,TransactionError> relatedErrors;
/**
* Blank Constructor
*
*/
public TransactionError(){
}
/**
* Get the type
*
* @return type
*/
public String getType(){
return this.type;
}
/**
* Get the code
*
* @return code
*/
public String getCode(){
return this.code;
}
/**
* Get the message
*
* @return message
*/
public String getMessage(){
return this.message;
}
/**
* Get the additionalInfo
*
* @return additionalInfo
*/
public Map<String,Object> getAdditionalInfo(){
return this.additionalInfo;
}
/**
* Get the relatedErrors
*
* @return relatedErrors
*/
public Map<String,TransactionError> getRelatedErrors(){
return this.relatedErrors;
}
/**
* Overridden equals method for doing field based equals comparison.
*/
public boolean equals(Object otherObject) {
if (otherObject == this)
return true;
if (!(otherObject instanceof TransactionError))
return false;
TransactionError castObject = (TransactionError)otherObject;
boolean equals = true;
equals = equals && ( (this.getType() == null && castObject.getType() == null) ||
(this.getType() != null && this.getType().equals(castObject.getType())));
equals = equals && ( (this.getCode() == null && castObject.getCode() == null) ||
(this.getCode() != null && this.getCode().equals(castObject.getCode())));
equals = equals && ( (this.getMessage() == null && castObject.getMessage() == null) ||
(this.getMessage() != null && this.getMessage().equals(castObject.getMessage())));
equals = equals && ( (this.getAdditionalInfo() == null && castObject.getAdditionalInfo() == null) ||
(this.getAdditionalInfo() != null && this.getAdditionalInfo().equals(castObject.getAdditionalInfo())));
equals = equals && ( (this.getRelatedErrors() == null && castObject.getRelatedErrors() == null) ||
(this.getRelatedErrors() != null && this.getRelatedErrors().equals(castObject.getRelatedErrors())));
return equals;
}
} |
package com.library.source;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class ClassStructure {
/*
* to find library sgenature first unzip library generate class schema by run
* this commands in library folder javap * ../libraryName.txt List jar classes
* jar -tf picasso-2.5.2-sources.jar | grep '.java'
*/
public ClassStructure() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> listOfLibraryClasses = new ClassStructure().getLibraryClasses("XXX:testng:6.9.13.6");
System.out.println("*********\nlist Of Library Classes");
for (String className : listOfLibraryClasses) {
System.out.println(className);
}
// packgaes
ArrayList<String> listOfLibraryPackages = new ClassStructure().getLibraryPackages("XXX:testng:6.9.13.6");
System.out.println("*********\nlist Of Library Packages");
for (String packageName : listOfLibraryPackages) {
System.out.println(packageName);
}
// get classes and methods as objects
ArrayList<ClassObj> listOfLibraryClassesObj = new ClassStructure().getLibraryClassesObj("XXX:testng:6.9.13.6"); // org.slf4j:slf4j-api:1.6.6
System.out.println("*********\nlist Of Library Classes Info");
System.out.println("===========================");
for (ClassObj classObj : listOfLibraryClassesObj) {
classObj.print();
System.out.println("===========================");
for (MethodObj methodObj : classObj.classMethods) {
methodObj.print();
}
}
// static methods
ArrayList<String> listOfStaticMethods = new ClassStructure().getStaticMethods("XXX:easymock:3.4");
System.out.println("*********\nlist Of Static methods");
for (String packageName : listOfStaticMethods) {
System.out.println(packageName);
}
}
// get list of class name for any input library depend on library sechman that
// we already have
public ArrayList<String> getLibraryClasses(String libraryInfo) {
String[] LibraryInfos = libraryInfo.split(":");
String DgroupId = LibraryInfos[0];
String DartifactId = LibraryInfos[1];
String Dversion = LibraryInfos[2];
ArrayList<String> listOfClasses = new ArrayList<String>();
String libraryPath = "librariesClasses/" + DartifactId + "-" + Dversion + ".jar.txt";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(libraryPath)));
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.contains(" class ") || line.startsWith("class ") || line.contains(" interface ")
|| line.startsWith("interface ")) {
String searchFor = line.contains("class") == true ? "class" : "interface";
String className = "";
try {
String[] classInfo = line.split(searchFor);
String[] packgeWithClass = classInfo[1].trim().split(" ");
String[] packageInfo = packgeWithClass[0].split("\\.");
className = packageInfo[packageInfo.length - 1];
} catch (Exception e) {
// TODO: handle exception
}
if (className == "") {
continue;
}
;
if (listOfClasses.contains(className) == false) {
// System.out.println(className);
listOfClasses.add(className);
}
}
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
return listOfClasses;
}
// get list of packges name for any input library depend on library sechman that
// we already have
public ArrayList<String> getLibraryPackages(String libraryInfo) {
ArrayList<String> listOfPackages = new ArrayList<String>();
String[] LibraryInfos = libraryInfo.split(":");
String DgroupId = LibraryInfos[0];
String DartifactId = LibraryInfos[1];
String Dversion = LibraryInfos[2];
String libraryPath = "librariesClasses/" + DartifactId + "-" + Dversion + ".jar.txt";
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(libraryPath)));
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.contains(" class ") || line.startsWith("class ") || line.contains(" interface ")
|| line.startsWith("interface ")) {
String searchFor = line.contains("class") == true ? "class" : "interface";
String packageName = "";
try {
String[] classInfo = line.split(searchFor);
String[] packgeWithClass = classInfo[1].trim().split(" ");
String[] packageInfo = packgeWithClass[0].split("\\.");
for (int i = 0; i < packageInfo.length - 1; i++) {
String folder = packageInfo[i];
if (packageName == "") {
packageName = folder;
} else {
packageName += "." + folder;
}
}
} catch (Exception e) {
// TODO: handle exception
}
if (packageName == "") {
continue;
}
;
if (listOfPackages.contains(packageName) == false) {
// System.out.println(className);
listOfPackages.add(packageName);
}
}
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
return listOfPackages;
}
// This function return list of static methods for direct call
public ArrayList<String> getStaticMethods(String libraryInfo) {
ArrayList<String> listOfStaticMethods = new ArrayList<String>();
ArrayList<ClassObj> listOfClassesObj = getLibraryClassesObj(libraryInfo);
for (ClassObj classObj : listOfClassesObj) {
for (MethodObj methodObj : classObj.classMethods) {
if (methodObj.scope.trim().contains(" static")) {
listOfStaticMethods.add(methodObj.methodName);
}
}
}
return listOfStaticMethods;
}
/*
* This function return list of objects with all classes and methods that been
* // in the library
*/
public ArrayList<ClassObj> getLibraryClassesObj(String libraryInfo) {
String[] LibraryInfos = libraryInfo.split(":");
String DgroupId = LibraryInfos[0];
String DartifactId = LibraryInfos[1];
String Dversion = LibraryInfos[2];
ArrayList<ClassObj> listOfClassesObj = new ArrayList<ClassObj>();
String libraryPath = "librariesClasses/" + DartifactId + "-" + Dversion + ".jar.txt";
ClassObj classObj = null;
boolean readingMethods = false;// when this flag is active that mean the line is method
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(libraryPath)));
String line;
String searchFor = "Compiled from ";
String className;
while ((line = br.readLine()) != null) {
if (line.trim().equals("}") && readingMethods == true) {
readingMethods = false; // complete reading methods for this class
if (classObj != null) {
listOfClassesObj.add(classObj);
classObj = null;
}
}
if (readingMethods == true) {
if (classObj != null) {
classObj.addMethod(line);
}
}
// new class to process
if (line.contains("class ") || line.contains("interface ")) {
classObj = new ClassObj();
classObj.setClassName(line);
// listOfClasses.add(className);
readingMethods = true;
}
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
return listOfClassesObj;
}
}
|
package com.ifeng.recom.mixrecall.negative;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
/**
* Created by jibin on 2017/5/23.
*/
public class JsonUtils {
private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);
private static final ObjectMapper jsonObjectMapper = new ObjectMapper();
static {
jsonObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
jsonObjectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
jsonObjectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
jsonObjectMapper.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false));
jsonObjectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
/**
* 将实体写成json格式字符串
*
* @param value
* @return
*/
public static String writeToJSON(Object value) {
String result = null;
try {
result = jsonObjectMapper.writeValueAsString(value);
} catch (Exception e) {
logger.error("writeToJSON ERROR:{}", e);
}
return result;
}
public static final <T> T json2Object(String text, Class<T> clazz) throws IOException {
return jsonObjectMapper.readValue(text, clazz);
}
/**
* 将text转换为对象
*
* @param text
* @param clazz
* @param <T>
* @return
*/
public static final <T> T json2ObjectWithoutException(String text, Class<T> clazz) {
try {
return jsonObjectMapper.readValue(text, clazz);
} catch (IOException e) {
e.printStackTrace();
logger.error("jsonstr:{},Exception:{}", text, e);
return null;
}
}
/**
* 将jackson json转化为list、map等复杂对象
* 例如: List<Bean> beanList = mapper.readValue(jsonString, new TypeReference<List<Bean>>() {});
*
* @param text
* @param typeReference
* @param <T>
* @return
* @throws IOException
*/
public static final <T> T json2Object(String text, TypeReference typeReference) {
try {
return jsonObjectMapper.readValue(text, typeReference);
} catch (IOException e) {
// e.printStackTrace();
logger.error("jsonstr:{},Exception:{}", text, e);
return null;
}
}
}
|
/*
* 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 Logica;
import Dominio.*;
/**
*
* @author defGrupo()
*/
public class ListaCliente {
private int max;
private int cant;
private Cliente[] lista;
public ListaCliente(int max){
lista = new Cliente[max];
cant = 0;
this.max=max;
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public int getCant() {
return cant;
}
public void setCant(int cant) {
this.cant = cant;
}
public Cliente[] getLista() {
return lista;
}
public void setLista(Cliente[] lista) {
this.lista = lista;
}
public boolean addCliente(Cliente c){
if(cant<max){
lista[cant]=c;
cant++;
return true;
}else
return false;
}
public Cliente getClienteI(int i){
if(i>=0 && i<cant)
return lista[i];
else
return null;
}
public Cliente buscarCliente(String rut){
int j;
for(j=0;j<cant;j++){
if(lista[j].getRut().equalsIgnoreCase(rut))
break;
}
if(j==cant)
return null;
else
return lista[j];
}
} |
package io.cde.account.exception;
/**
* @author lcl
* 业务异常
*/
public class BizException extends Exception {
/**
* 序列号.
*/
private static final long serialVersionUID = -5937698721553801873L;
/**
* 异常编码.
*/
private int code;
/**
* 异常信息.
*/
private String message;
/**
* 构造方法.
*
* @param code 错误码
* @param message 错误信息
*/
public BizException(final int code, final String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(final int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(final String message) {
this.message = message;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.