text stringlengths 10 2.72M |
|---|
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.01.28 at 02:10:24 PM CST
//
package org.mesa.xml.b2mml;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for BatchListEntryType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="BatchListEntryType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ID" type="{http://www.mesa.org/xml/B2MML-V0600}IDType"/>
* <element name="Description" type="{http://www.mesa.org/xml/B2MML-V0600}DescriptionType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="BatchListEntryType" type="{http://www.mesa.org/xml/B2MML-V0600}BatchListEntryTypeType"/>
* <element name="Status" type="{http://www.mesa.org/xml/B2MML-V0600}BatchStatusType" minOccurs="0"/>
* <element name="Mode" type="{http://www.mesa.org/xml/B2MML-V0600}ModeType" minOccurs="0"/>
* <element name="ExternalID" type="{http://www.mesa.org/xml/B2MML-V0600}ExternalIDType" minOccurs="0"/>
* <element name="RecipeID" type="{http://www.mesa.org/xml/B2MML-V0600}RecipeIDType" minOccurs="0"/>
* <element name="RecipeVersion" type="{http://www.mesa.org/xml/B2MML-V0600}RecipeVersionType" minOccurs="0"/>
* <element name="BatchID" type="{http://www.mesa.org/xml/B2MML-V0600}BatchIDType" minOccurs="0"/>
* <element name="LotID" type="{http://www.mesa.org/xml/B2MML-V0600}LotIDType" minOccurs="0"/>
* <element name="CampaignID" type="{http://www.mesa.org/xml/B2MML-V0600}CampaignIDType" minOccurs="0"/>
* <element name="ProductID" type="{http://www.mesa.org/xml/B2MML-V0600}ProductIDType" minOccurs="0"/>
* <element name="OrderID" type="{http://www.mesa.org/xml/B2MML-V0600}OrderIDType" minOccurs="0"/>
* <element name="StartCondition" type="{http://www.mesa.org/xml/B2MML-V0600}StartConditionType" minOccurs="0"/>
* <element name="RequestedStartTime" type="{http://www.mesa.org/xml/B2MML-V0600}RequestedStartTimeType" minOccurs="0"/>
* <element name="ActualStartTime" type="{http://www.mesa.org/xml/B2MML-V0600}ActualStartTimeType" minOccurs="0"/>
* <element name="RequestedEndTime" type="{http://www.mesa.org/xml/B2MML-V0600}RequestedEndTimeType" minOccurs="0"/>
* <element name="ActualEndTime" type="{http://www.mesa.org/xml/B2MML-V0600}ActualEndTimeType" minOccurs="0"/>
* <element name="BatchPriority" type="{http://www.mesa.org/xml/B2MML-V0600}BatchPriorityType" minOccurs="0"/>
* <element name="RequestedBatchSize" type="{http://www.mesa.org/xml/B2MML-V0600}RequestedBatchSizeType" minOccurs="0"/>
* <element name="ActualBatchSize" type="{http://www.mesa.org/xml/B2MML-V0600}ActualBatchSizeType" minOccurs="0"/>
* <element name="UnitOfMeasure" type="{http://www.mesa.org/xml/B2MML-V0600}UnitOfMeasureType" minOccurs="0"/>
* <element name="Note" type="{http://www.mesa.org/xml/B2MML-V0600}NoteType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="Parameter" type="{http://www.mesa.org/xml/B2MML-V0600}BatchParameterType" maxOccurs="unbounded" minOccurs="0"/>
* <choice maxOccurs="unbounded" minOccurs="0">
* <element name="EquipmentID" type="{http://www.mesa.org/xml/B2MML-V0600}BatchEquipmentIDType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="EquipmentClassID" type="{http://www.mesa.org/xml/B2MML-V0600}BatchEquipmentClassIDType" maxOccurs="unbounded" minOccurs="0"/>
* </choice>
* <element name="ActualEquipmentID" type="{http://www.mesa.org/xml/B2MML-V0600}ActualEquipmentIDType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="BatchListEntry" type="{http://www.mesa.org/xml/B2MML-V0600}BatchListEntryType" maxOccurs="unbounded" minOccurs="0"/>
* <group ref="{http://www.mesa.org/xml/B2MML-V0600-AllExtensions}BatchListEntry" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "BatchListEntryType", propOrder = {
"id",
"description",
"batchListEntryType",
"status",
"mode",
"externalID",
"recipeID",
"recipeVersion",
"batchID",
"lotID",
"campaignID",
"productID",
"orderID",
"startCondition",
"requestedStartTime",
"actualStartTime",
"requestedEndTime",
"actualEndTime",
"batchPriority",
"requestedBatchSize",
"actualBatchSize",
"unitOfMeasure",
"note",
"parameter",
"equipmentIDOrEquipmentClassID",
"actualEquipmentID",
"batchListEntry"
})
public class BatchListEntryType {
@XmlElement(name = "ID", required = true)
protected IDType id;
@XmlElement(name = "Description")
protected List<DescriptionType> description;
@XmlElement(name = "BatchListEntryType", required = true)
protected BatchListEntryTypeType batchListEntryType;
@XmlElement(name = "Status")
protected BatchStatusType status;
@XmlElement(name = "Mode")
protected ModeType mode;
@XmlElement(name = "ExternalID")
protected ExternalIDType externalID;
@XmlElement(name = "RecipeID")
protected RecipeIDType recipeID;
@XmlElement(name = "RecipeVersion")
protected RecipeVersionType recipeVersion;
@XmlElement(name = "BatchID")
protected BatchIDType batchID;
@XmlElement(name = "LotID")
protected LotIDType lotID;
@XmlElement(name = "CampaignID")
protected CampaignIDType campaignID;
@XmlElement(name = "ProductID")
protected ProductIDType productID;
@XmlElement(name = "OrderID")
protected OrderIDType orderID;
@XmlElement(name = "StartCondition")
protected StartConditionType startCondition;
@XmlElement(name = "RequestedStartTime")
protected RequestedStartTimeType requestedStartTime;
@XmlElement(name = "ActualStartTime")
protected ActualStartTimeType actualStartTime;
@XmlElement(name = "RequestedEndTime")
protected RequestedEndTimeType requestedEndTime;
@XmlElement(name = "ActualEndTime")
protected ActualEndTimeType actualEndTime;
@XmlElement(name = "BatchPriority")
protected BatchPriorityType batchPriority;
@XmlElement(name = "RequestedBatchSize")
protected RequestedBatchSizeType requestedBatchSize;
@XmlElement(name = "ActualBatchSize")
protected ActualBatchSizeType actualBatchSize;
@XmlElement(name = "UnitOfMeasure")
protected UnitOfMeasureType unitOfMeasure;
@XmlElement(name = "Note")
protected List<NoteType> note;
@XmlElement(name = "Parameter")
protected List<BatchParameterType> parameter;
@XmlElements({
@XmlElement(name = "EquipmentID", type = BatchEquipmentIDType.class),
@XmlElement(name = "EquipmentClassID", type = BatchEquipmentClassIDType.class)
})
protected List<Object> equipmentIDOrEquipmentClassID;
@XmlElement(name = "ActualEquipmentID")
protected List<ActualEquipmentIDType> actualEquipmentID;
@XmlElement(name = "BatchListEntry")
protected List<BatchListEntryType> batchListEntry;
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link IDType }
*
*/
public IDType getID() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link IDType }
*
*/
public void setID(IDType value) {
this.id = value;
}
/**
* Gets the value of the description property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the description property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDescription().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DescriptionType }
*
*
*/
public List<DescriptionType> getDescription() {
if (description == null) {
description = new ArrayList<DescriptionType>();
}
return this.description;
}
/**
* Gets the value of the batchListEntryType property.
*
* @return
* possible object is
* {@link BatchListEntryTypeType }
*
*/
public BatchListEntryTypeType getBatchListEntryType() {
return batchListEntryType;
}
/**
* Sets the value of the batchListEntryType property.
*
* @param value
* allowed object is
* {@link BatchListEntryTypeType }
*
*/
public void setBatchListEntryType(BatchListEntryTypeType value) {
this.batchListEntryType = value;
}
/**
* Gets the value of the status property.
*
* @return
* possible object is
* {@link BatchStatusType }
*
*/
public BatchStatusType getStatus() {
return status;
}
/**
* Sets the value of the status property.
*
* @param value
* allowed object is
* {@link BatchStatusType }
*
*/
public void setStatus(BatchStatusType value) {
this.status = value;
}
/**
* Gets the value of the mode property.
*
* @return
* possible object is
* {@link ModeType }
*
*/
public ModeType getMode() {
return mode;
}
/**
* Sets the value of the mode property.
*
* @param value
* allowed object is
* {@link ModeType }
*
*/
public void setMode(ModeType value) {
this.mode = value;
}
/**
* Gets the value of the externalID property.
*
* @return
* possible object is
* {@link ExternalIDType }
*
*/
public ExternalIDType getExternalID() {
return externalID;
}
/**
* Sets the value of the externalID property.
*
* @param value
* allowed object is
* {@link ExternalIDType }
*
*/
public void setExternalID(ExternalIDType value) {
this.externalID = value;
}
/**
* Gets the value of the recipeID property.
*
* @return
* possible object is
* {@link RecipeIDType }
*
*/
public RecipeIDType getRecipeID() {
return recipeID;
}
/**
* Sets the value of the recipeID property.
*
* @param value
* allowed object is
* {@link RecipeIDType }
*
*/
public void setRecipeID(RecipeIDType value) {
this.recipeID = value;
}
/**
* Gets the value of the recipeVersion property.
*
* @return
* possible object is
* {@link RecipeVersionType }
*
*/
public RecipeVersionType getRecipeVersion() {
return recipeVersion;
}
/**
* Sets the value of the recipeVersion property.
*
* @param value
* allowed object is
* {@link RecipeVersionType }
*
*/
public void setRecipeVersion(RecipeVersionType value) {
this.recipeVersion = value;
}
/**
* Gets the value of the batchID property.
*
* @return
* possible object is
* {@link BatchIDType }
*
*/
public BatchIDType getBatchID() {
return batchID;
}
/**
* Sets the value of the batchID property.
*
* @param value
* allowed object is
* {@link BatchIDType }
*
*/
public void setBatchID(BatchIDType value) {
this.batchID = value;
}
/**
* Gets the value of the lotID property.
*
* @return
* possible object is
* {@link LotIDType }
*
*/
public LotIDType getLotID() {
return lotID;
}
/**
* Sets the value of the lotID property.
*
* @param value
* allowed object is
* {@link LotIDType }
*
*/
public void setLotID(LotIDType value) {
this.lotID = value;
}
/**
* Gets the value of the campaignID property.
*
* @return
* possible object is
* {@link CampaignIDType }
*
*/
public CampaignIDType getCampaignID() {
return campaignID;
}
/**
* Sets the value of the campaignID property.
*
* @param value
* allowed object is
* {@link CampaignIDType }
*
*/
public void setCampaignID(CampaignIDType value) {
this.campaignID = value;
}
/**
* Gets the value of the productID property.
*
* @return
* possible object is
* {@link ProductIDType }
*
*/
public ProductIDType getProductID() {
return productID;
}
/**
* Sets the value of the productID property.
*
* @param value
* allowed object is
* {@link ProductIDType }
*
*/
public void setProductID(ProductIDType value) {
this.productID = value;
}
/**
* Gets the value of the orderID property.
*
* @return
* possible object is
* {@link OrderIDType }
*
*/
public OrderIDType getOrderID() {
return orderID;
}
/**
* Sets the value of the orderID property.
*
* @param value
* allowed object is
* {@link OrderIDType }
*
*/
public void setOrderID(OrderIDType value) {
this.orderID = value;
}
/**
* Gets the value of the startCondition property.
*
* @return
* possible object is
* {@link StartConditionType }
*
*/
public StartConditionType getStartCondition() {
return startCondition;
}
/**
* Sets the value of the startCondition property.
*
* @param value
* allowed object is
* {@link StartConditionType }
*
*/
public void setStartCondition(StartConditionType value) {
this.startCondition = value;
}
/**
* Gets the value of the requestedStartTime property.
*
* @return
* possible object is
* {@link RequestedStartTimeType }
*
*/
public RequestedStartTimeType getRequestedStartTime() {
return requestedStartTime;
}
/**
* Sets the value of the requestedStartTime property.
*
* @param value
* allowed object is
* {@link RequestedStartTimeType }
*
*/
public void setRequestedStartTime(RequestedStartTimeType value) {
this.requestedStartTime = value;
}
/**
* Gets the value of the actualStartTime property.
*
* @return
* possible object is
* {@link ActualStartTimeType }
*
*/
public ActualStartTimeType getActualStartTime() {
return actualStartTime;
}
/**
* Sets the value of the actualStartTime property.
*
* @param value
* allowed object is
* {@link ActualStartTimeType }
*
*/
public void setActualStartTime(ActualStartTimeType value) {
this.actualStartTime = value;
}
/**
* Gets the value of the requestedEndTime property.
*
* @return
* possible object is
* {@link RequestedEndTimeType }
*
*/
public RequestedEndTimeType getRequestedEndTime() {
return requestedEndTime;
}
/**
* Sets the value of the requestedEndTime property.
*
* @param value
* allowed object is
* {@link RequestedEndTimeType }
*
*/
public void setRequestedEndTime(RequestedEndTimeType value) {
this.requestedEndTime = value;
}
/**
* Gets the value of the actualEndTime property.
*
* @return
* possible object is
* {@link ActualEndTimeType }
*
*/
public ActualEndTimeType getActualEndTime() {
return actualEndTime;
}
/**
* Sets the value of the actualEndTime property.
*
* @param value
* allowed object is
* {@link ActualEndTimeType }
*
*/
public void setActualEndTime(ActualEndTimeType value) {
this.actualEndTime = value;
}
/**
* Gets the value of the batchPriority property.
*
* @return
* possible object is
* {@link BatchPriorityType }
*
*/
public BatchPriorityType getBatchPriority() {
return batchPriority;
}
/**
* Sets the value of the batchPriority property.
*
* @param value
* allowed object is
* {@link BatchPriorityType }
*
*/
public void setBatchPriority(BatchPriorityType value) {
this.batchPriority = value;
}
/**
* Gets the value of the requestedBatchSize property.
*
* @return
* possible object is
* {@link RequestedBatchSizeType }
*
*/
public RequestedBatchSizeType getRequestedBatchSize() {
return requestedBatchSize;
}
/**
* Sets the value of the requestedBatchSize property.
*
* @param value
* allowed object is
* {@link RequestedBatchSizeType }
*
*/
public void setRequestedBatchSize(RequestedBatchSizeType value) {
this.requestedBatchSize = value;
}
/**
* Gets the value of the actualBatchSize property.
*
* @return
* possible object is
* {@link ActualBatchSizeType }
*
*/
public ActualBatchSizeType getActualBatchSize() {
return actualBatchSize;
}
/**
* Sets the value of the actualBatchSize property.
*
* @param value
* allowed object is
* {@link ActualBatchSizeType }
*
*/
public void setActualBatchSize(ActualBatchSizeType value) {
this.actualBatchSize = value;
}
/**
* Gets the value of the unitOfMeasure property.
*
* @return
* possible object is
* {@link UnitOfMeasureType }
*
*/
public UnitOfMeasureType getUnitOfMeasure() {
return unitOfMeasure;
}
/**
* Sets the value of the unitOfMeasure property.
*
* @param value
* allowed object is
* {@link UnitOfMeasureType }
*
*/
public void setUnitOfMeasure(UnitOfMeasureType value) {
this.unitOfMeasure = value;
}
/**
* Gets the value of the note property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the note property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getNote().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link NoteType }
*
*
*/
public List<NoteType> getNote() {
if (note == null) {
note = new ArrayList<NoteType>();
}
return this.note;
}
/**
* Gets the value of the parameter property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the parameter property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getParameter().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link BatchParameterType }
*
*
*/
public List<BatchParameterType> getParameter() {
if (parameter == null) {
parameter = new ArrayList<BatchParameterType>();
}
return this.parameter;
}
/**
* Gets the value of the equipmentIDOrEquipmentClassID property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the equipmentIDOrEquipmentClassID property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getEquipmentIDOrEquipmentClassID().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link BatchEquipmentIDType }
* {@link BatchEquipmentClassIDType }
*
*
*/
public List<Object> getEquipmentIDOrEquipmentClassID() {
if (equipmentIDOrEquipmentClassID == null) {
equipmentIDOrEquipmentClassID = new ArrayList<Object>();
}
return this.equipmentIDOrEquipmentClassID;
}
/**
* Gets the value of the actualEquipmentID property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the actualEquipmentID property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getActualEquipmentID().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ActualEquipmentIDType }
*
*
*/
public List<ActualEquipmentIDType> getActualEquipmentID() {
if (actualEquipmentID == null) {
actualEquipmentID = new ArrayList<ActualEquipmentIDType>();
}
return this.actualEquipmentID;
}
/**
* Gets the value of the batchListEntry property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the batchListEntry property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getBatchListEntry().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link BatchListEntryType }
*
*
*/
public List<BatchListEntryType> getBatchListEntry() {
if (batchListEntry == null) {
batchListEntry = new ArrayList<BatchListEntryType>();
}
return this.batchListEntry;
}
}
|
package com.mrhan.database;
import java.sql.ResultSet;
/**
* 实体操作结果集合方法!
* <br/>
* {@link IEntity} 和 {@link IDao}的本质区别,在于:<br/>
* {@link IDao} 在处理结果集合是!无需考虑遍历集合,{@linkplain IDao}但其有类型限制,类似于一个辅助类<br/>
* {@link IEntity} 在处理结果集合时,需要考虑遍历集合,对于结果集合的处理!完全独立
*/
public interface IEntity {
/**
* 处理结果集合方法
* @param rs
*/
void entitys(ResultSet rs);
}
|
package elora;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import timePhrase.TimePhrase;
import timePhrase.TimePhraseFactory;
/**
* Encapsulates the logic for converting a plain English representation of a time relative to now into a {@link Date} object.
*
* @author akauffman
*
*/
public final class TellMeWhen {
/**
* Gets a date relative to the current date that matches a plain English description.
* <br/>
* Ex: "Next Thursday" would return a date for the next Thursday.
*
* @param relativeTime A plain English representation of a time relative to now. Ex: Last Month
* @return the requested {@link Date}
* @throws InvalidPatternException if the given time string does not match any known time patterns.
*/
public static final Date listen(String relativeTime) throws InvalidPatternException{
return listen(relativeTime, Calendar.getInstance().getTime());
}
/**
* Gets a date relative to the given date that matches a plain English description.
* <br/>
* Ex: "Next Thursday" from 4/19/2015 would return a date of 4/23/2015.
*
* @param relativeTime A plain English representation of a relative time. Ex: Last Month
* @param fromDate The date that will be modified based on the relativeTime phrase.
* @return the requested {@link Date}
* @throws InvalidPatternException if the given time string does not match any known time patterns.
*/
public static final Date listen(String relativeTime, Date fromDate) throws InvalidPatternException{
if(null == relativeTime){
throw new NullPointerException("RelativeTime is null");
}
if(null == fromDate){
throw new NullPointerException("fromDate is null");
}
relativeTime = relativeTime.toUpperCase().trim();
final Calendar fromWhen = Calendar.getInstance();
fromWhen.setTime(fromDate);
final List<TimePhrase> timePhrases = TimePhraseFactory.getTimePhrases();
for(TimePhrase timePhrase : timePhrases){
if(timePhrase.matches(relativeTime)){
return timePhrase.getTime(fromWhen);
}
}
throw new InvalidPatternException();
}
}
|
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.servlet.frontend;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.openkm.api.OKMAuth;
import com.openkm.api.OKMNotification;
import com.openkm.core.AccessDeniedException;
import com.openkm.core.DatabaseException;
import com.openkm.core.PathNotFoundException;
import com.openkm.core.RepositoryException;
import com.openkm.frontend.client.OKMException;
import com.openkm.frontend.client.constants.service.ErrorCode;
import com.openkm.frontend.client.service.OKMNotifyService;
import com.openkm.principal.PrincipalAdapterException;
import com.openkm.util.MailUtils;
/**
* Servlet Class
*/
public class NotifyServlet extends OKMRemoteServiceServlet implements OKMNotifyService {
private static final long serialVersionUID = 1L;
private static Logger log = LoggerFactory.getLogger(FolderServlet.class);
@Override
public void subscribe(String nodePath) throws OKMException {
log.debug("subscribe({})", nodePath);
updateSessionManager();
try {
OKMNotification.getInstance().subscribe(null, nodePath);
} catch (PathNotFoundException e) {
log.warn(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMNotifyService, ErrorCode.CAUSE_PathNotFound), e.getMessage());
} catch (AccessDeniedException e) {
log.warn(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMNotifyService, ErrorCode.CAUSE_AccessDenied), e.getMessage());
} catch (RepositoryException e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMNotifyService, ErrorCode.CAUSE_Repository), e.getMessage());
} catch (DatabaseException e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMNotifyService, ErrorCode.CAUSE_Database), e.getMessage());
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMNotifyService, ErrorCode.CAUSE_General), e.getMessage());
}
log.debug("subscribe: void");
}
@Override
public void unsubscribe(String nodePath) throws OKMException {
log.debug("subscribe({})", nodePath);
updateSessionManager();
try {
OKMNotification.getInstance().unsubscribe(null, nodePath);
} catch (PathNotFoundException e) {
log.warn(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMNotifyService, ErrorCode.CAUSE_PathNotFound), e.getMessage());
} catch (AccessDeniedException e) {
log.warn(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMNotifyService, ErrorCode.CAUSE_AccessDenied), e.getMessage());
} catch (RepositoryException e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMNotifyService, ErrorCode.CAUSE_Repository), e.getMessage());
} catch (DatabaseException e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMNotifyService, ErrorCode.CAUSE_Database), e.getMessage());
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMNotifyService, ErrorCode.CAUSE_General), e.getMessage());
}
log.debug("subscribe: void");
}
@Override
public void notify(String docPath, String mails, String users, String roles, String message, boolean attachment) throws
OKMException {
log.debug("notify({}, {}, {}, {}, {})", new Object[] { docPath, mails, users, roles, message, attachment });
updateSessionManager();
try {
List<String> userNames = new ArrayList<String>(Arrays.asList(users.isEmpty() ? new String[0] : users.split(",")));
List<String> roleNames = new ArrayList<String>(Arrays.asList(roles.isEmpty() ? new String[0] : roles.split(",")));
for (String role : roleNames) {
List<String> usersInRole = OKMAuth.getInstance().getUsersByRole(null, role);
for (String user : usersInRole) {
if (!userNames.contains(user)) {
userNames.add(user);
}
}
}
List<String> mailList = MailUtils.parseMailList(mails);
OKMNotification.getInstance().notify(null, docPath, userNames, mailList, message, attachment);
} catch (PathNotFoundException e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMNotifyService, ErrorCode.CAUSE_PathNotFound), e.getMessage());
} catch (AccessDeniedException e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMNotifyService, ErrorCode.CAUSE_AccessDenied), e.getMessage());
} catch (RepositoryException e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMNotifyService, ErrorCode.CAUSE_Repository), e.getMessage());
} catch (PrincipalAdapterException e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMNotifyService, ErrorCode.CAUSE_PrincipalAdapter), e.getMessage());
} catch (DatabaseException e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMNotifyService, ErrorCode.CAUSE_Database), e.getMessage());
} catch (IOException e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMNotifyService, ErrorCode.CAUSE_IO), e.getMessage());
}
log.debug("notify: void");
}
}
|
package com.lr.config;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import java.nio.charset.Charset;
public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class<T> clazz;
public FastJsonRedisSerializer(Class<T> clazz) {
super();
this.clazz = clazz;
}
@Override
public byte[] serialize(T t) throws SerializationException {
if (t == null) {
return new byte[0];
}
try {
return JSON.toJSONBytes(t, SerializerFeature.WriteClassName);
} catch (Exception ex) {
throw new SerializationException("Could not write JSON: " + ex.getMessage(), ex);
}
}
@Override
public T deserialize(byte[] bytes) throws SerializationException {
String data =new String(bytes);
T result = (T)JSON.parse(data);
return result;
}
}
|
package DTO;
import java.util.ArrayList;
/**
* Created by Quan-DevTeam on 11/9/15.
*/
public class MenuSection
{
String title;
ArrayList<Menu> listSubtitle;
public MenuSection(String title, ArrayList<Menu> listSubtitle) {
this.title = title;
this.listSubtitle = listSubtitle;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public ArrayList<Menu> getListSubtitle() {
return listSubtitle;
}
}
|
package com.tencent.tencentmap.mapsdk.a;
public final class rx extends rw {
private int d;
private int e;
private qx f;
private int g;
public final void a(int i) {
this.d = i;
}
public final void a(qx qxVar) {
this.f = qxVar;
}
public final void a(sl slVar) {
sh c = slVar.c();
this.e = this.e == 0 ? c.getHeight() - (this.g * 2) : this.e - (this.g * 2);
this.d = this.d == 0 ? c.getWidth() - (this.g * 2) : this.d - (this.g * 2);
if (this.e != 0 && this.d != 0) {
qw c2 = this.f.c();
qw b = this.f.b();
ru a = rv.a(c2);
ru a2 = rv.a(b);
double a3 = a.a() - a2.a();
double b2 = a.b() - a2.b();
rs a4 = slVar.b().a(new rs(0, (double) ((((float) this.e) * 1.0f) / ((float) this.d) < ((float) (a3 / b2)) ? (float) ((((double) this.e) * 156543.0339d) / a3) : (float) ((((double) this.d) * 156543.0339d) / b2))));
ru ruVar = new ru((b2 / 2.0d) + a2.b(), (a3 / 2.0d) + a2.a());
if (this.a) {
c.a(ruVar, this.b, this.c);
} else {
c.b(ruVar);
}
c.b(a4.c(), this.a, this.c);
}
}
public final void b(int i) {
this.e = i;
}
public final void c(int i) {
this.g = i;
}
}
|
package DesktopApp;
import javax.swing.JButton;
/**
* Η adminMain αποτελεί το GUI της βασικής οθόνης λειτουργίας της εφαρμογής , δινοντας
* τη δυνατότητα στο χρήστη να επιλέξει μεταξύ των ορισμένων λειτουργιών. Εδώ γίνεται
* και ο έλεγχος των δικαιωμάτων του χρήστη αναφορικά με τις υπηρεσίες που μπορεί να
* εκτελεί. Η λειτουργία αυτή είναι δυναμικά ορισμένη ελέγχοντας κάθε φορά μέσω ειδικού
* webService τις λειτουργίες που εχουν οριστεί ως επιτρεπόμενες απο τη βάση δεδομένων.
* @author Ioulios Tsiko: cs131027
* @author Theofilos Axiotis: cs131011
*/
public class adminMain extends javax.swing.JFrame {
private final String info1 = "Εισαγωγής ενός νέου φοιτητή \n(Α.Μ., Επώνυμο, Όνομα, Εξάμηνο)";
private final String info2 = "Εισαγωγή/τροποποίηση του βαθμού\nενός φοιτητή σε ένα μάθημα";
private final String info3 = "Τροποποίηση των βαθμών πολλών φοιτητών \nσε ένα μάθημα (στοιχεία από αρχείο “.xlsx”)";
private final String info4 = "Προβολής των προσωπικών στοιχείων\nενός φοιτητή και των βαθμών του.";
private final String info5 = "Εισαγωγής των στοιχείων ενός\nνέου χρήστη του συστήματος.";
String[] services=null;
String[] buttons = new String[6];
JButton[] btns=new JButton[5];
//default constructor - γίνεται η κλήση της initComponents για τη δημιουργία των
//στοιχείων του gui
public adminMain() {
initComponents();
}
JButton[] bt = new JButton[5];
/**
* Η initButtons κάνει απλώς μια αρχικοποίηση 5 jButtons,ορισμένα στο GUI, σε έναν πίνακα απο
* buttons. Η χρήση της είναι στη μέθοδο checkServices, οπου και θα γίνει εκτενέστερη
* ανάλυση.
* @return Ενα reference στον πίνακα bt
*/
public JButton[] initButtons(){
bt[0]=jButton1;
bt[1]=jButton2;
bt[2]=jButton3;
bt[3]=jButton4;
bt[4]=jButton5;
return bt;
}
/**
* Elegxei poies upiresies boroun na ektelestoun apo to xristi.
* i sigkrisi ginetai me to onoma tou button.(!)
* Ta buttons exoun ginei Disabled by default, kai mesw tis methodou
* energopoiountai mono osa epitrepetai analogws me ton xristi
* @param services
*/
public void checkService(String[] services){
int j;
int i;
btns=initButtons();
System.out.println("CHECKING SERVICES");
for(i=0;i<btns.length;i++){
for(j=0;j<services.length;j++){
if(btns[i].getText().equals(services[j])){
System.out.println("service allowed is:"+services[j]);
btns[i].setEnabled(true);
}
}
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();
jButton6 = new javax.swing.JButton();
jTextField1 = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
init();
setResizable(false);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
/*
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
*/
jLabel1.setBackground(new java.awt.Color(124, 146, 253));
jButton1.setText("Add Student");
jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseExited(java.awt.event.MouseEvent evt) {
jButton1MouseExited(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
jButton1MouseEntered(evt);
}
});
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Add/Modify Grade");
jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseExited(java.awt.event.MouseEvent evt) {
jButton2MouseExited(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
jButton2MouseEntered(evt);
}
});
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setText("Modify Grades");
jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseExited(java.awt.event.MouseEvent evt) {
jButton3MouseExited(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
jButton3MouseEntered(evt);
}
});
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jLabel2.setText("Logged in as "+User.getRole());
jButton4.setText("Show Data");
jButton4.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseExited(java.awt.event.MouseEvent evt) {
jButton4MouseExited(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
jButton4MouseEntered(evt);
}
});
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jButton5.setText("Add User");
jButton5.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseExited(java.awt.event.MouseEvent evt) {
jButton5MouseExited(evt);
}
public void mouseEntered(java.awt.event.MouseEvent evt) {
jButton5MouseEntered(evt);
}
});
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);
jButton6.setText("Logout");
jButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton6ActionPerformed(evt);
}
});
jTextField1.setText(" Latest Changes");
jLabel3.setText("Username: "+User.getUsername());
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel2))
.addGroup(layout.createSequentialGroup()
.addGap(31, 31, 31)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 412, Short.MAX_VALUE))))
.addGap(28, 28, 28))
.addGroup(layout.createSequentialGroup()
.addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(18, 18, 18)
.addComponent(jButton2)
.addGap(18, 18, 18)
.addComponent(jButton3)
.addGap(18, 18, 18)
.addComponent(jButton4)
.addGap(18, 18, 18)
.addComponent(jButton5))
.addComponent(jScrollPane1))
.addGap(37, 37, 37)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton6)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(26, Short.MAX_VALUE))
);
pack();
//ola ta buttons ginontai disabled by default kai sti sunexeia kaleitai
//i checkService gia na ginoun enabled mono ekeina pou epitrepetai gia
//ton xristi.
jButton1.setEnabled(false);
jButton2.setEnabled(false);
jButton3.setEnabled(false);
jButton4.setEnabled(false);
jButton5.setEnabled(false);
checkService(User.getServices());
}// </editor-fold>//GEN-END:initComponents
private void jButton1MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseEntered
// TODO add your handling code here:
jTextArea1.setText(info1);
}//GEN-LAST:event_jButton1MouseEntered
private void jButton2MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseEntered
// TODO add your handling code here:
jTextArea1.setText(info2);
}//GEN-LAST:event_jButton2MouseEntered
private void jButton1MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseExited
// TODO add your handling code here:
jTextArea1.setText("");
}//GEN-LAST:event_jButton1MouseExited
private void jButton2MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseExited
// TODO add your handling code here:
jTextArea1.setText("");
}//GEN-LAST:event_jButton2MouseExited
private void jButton3MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseExited
// TODO add your handling code here:
jTextArea1.setText("");
}//GEN-LAST:event_jButton3MouseExited
private void jButton4MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton4MouseExited
// TODO add your handling code here:
jTextArea1.setText("");
}//GEN-LAST:event_jButton4MouseExited
private void jButton5MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton5MouseExited
// TODO add your handling code here:
jTextArea1.setText("");
}//GEN-LAST:event_jButton5MouseExited
private void jButton3MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseEntered
// TODO add your handling code here:
jTextArea1.setText(info3);
}//GEN-LAST:event_jButton3MouseEntered
private void jButton4MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton4MouseEntered
// TODO add your handling code here:
jTextArea1.setText(info4);
}//GEN-LAST:event_jButton4MouseEntered
private void jButton5MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton5MouseEntered
// TODO add your handling code here:
jTextArea1.setText(info5);
}//GEN-LAST:event_jButton5MouseEntered
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
this.setVisible(false);
addStudent newStud = new addStudent(this);
newStud.setVisible(true);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
this.setVisible(false);
modifyGrade mod = new modifyGrade(this);
mod.setVisible(true);
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
this.setVisible(false);
modifyFromFile fileMod = new modifyFromFile(this);
fileMod.setVisible(true);
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
// TODO add your handling code here:
this.setVisible(false);
showStud studDat = new showStud(this);
studDat.setVisible(true);
}//GEN-LAST:event_jButton4ActionPerformed
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
// TODO add your handling code here:
this.setVisible(false);
addUser adUsr = new addUser(this);
adUsr.setVisible(true);
}//GEN-LAST:event_jButton5ActionPerformed
//Logout Button
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
// TODO add your handling code here:
logoutClient lgOut = new logoutClient();
lgOut.logout(User.getUsername());
this.setVisible(false);
loginForm lg = new loginForm();
lg.setVisible(true);
}//GEN-LAST:event_jButton6ActionPerformed
/**
* @param args the command line arguments
*/
public void init(){
//public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(adminMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(adminMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(adminMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(adminMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JButton jButton5;
private javax.swing.JButton jButton6;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
// End of variables declaration//GEN-END:variables
}
|
package nl.computerinfor.groamchat.activities;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.TextView;
import nl.computerinfor.groamchat.R;
/**
* Created by Tom Remeeus on 27-5-2016.
*/
public class InformationActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information);
final TextView rateText = (TextView)findViewById(R.id.rateText);
RatingBar ratingBar = (RatingBar)findViewById(R.id.ratingBar);
ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener()
{
@Override
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser)
{
String ratingValue = String.valueOf(rating);
switch (ratingValue)
{
case "0.5":
rateText.setText("Worst app ever.");
break;
case "1.0":
rateText.setText("This is #^$&#!");
break;
case "1.5":
rateText.setText("Yugh!");
break;
case "2.0":
rateText.setText("Waste of time.");
break;
case "2.5":
rateText.setText("Meh...");
break;
case "3.0":
rateText.setText("It's OK...");
break;
case "3.5":
rateText.setText("Good.");
break;
case "4.0":
rateText.setText("Very good.");
break;
case "4.5":
rateText.setText("Supurb!");
break;
case "5.0":
rateText.setText("Top kek m8!");
break;
}
}
});
Button back = (Button)findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
backMain();
}
});
}
private void backMain()
{
this.finish();
}
}
|
package com.example.healthmanage.ui.activity.mytask;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.example.healthmanage.BR;
import com.example.healthmanage.R;
import com.example.healthmanage.base.BaseActivity;
import com.example.healthmanage.bean.network.response.AirResponse;
import com.example.healthmanage.bean.network.response.NursingResponse;
import com.example.healthmanage.databinding.ActivityTaskDataBinding;
import com.example.healthmanage.ui.activity.memberdetail.adapter.AirAdapter;
import com.example.healthmanage.ui.activity.memberdetail.adapter.SpiritAdapter;
import com.example.healthmanage.ui.activity.memberdetail.response.HealthDataResponse;
import com.example.healthmanage.ui.activity.memberdetail.response.SpiritHealthResponse;
import com.example.healthmanage.ui.activity.mytask.adapter.AirTaskAdapter;
import com.example.healthmanage.ui.activity.mytask.adapter.SpiritTaskAdapter;
import com.example.healthmanage.ui.activity.mytask.response.HealthTaskDetailResponse;
import com.example.healthmanage.utils.ToolUtil;
import com.example.healthmanage.widget.DropdownNewBar;
import com.example.healthmanage.widget.TitleToolBar;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 异常数据查询
*/
public class HealthTaskDetailActivity extends BaseActivity<ActivityTaskDataBinding,MyNewTaskViewModel> implements TitleToolBar.OnTitleIconClickCallBack{
private TitleToolBar titleToolBar = new TitleToolBar();
private List<HealthTaskDetailResponse.DataBean.SongARIListBean> tEnvironmentBeanList;
private List<HealthTaskDetailResponse.DataBean.SleepDataBean> spiritListData;
private HealthTaskDetailResponse.DataBean.SongEnDataBean todayHealthData;
private HealthTaskDetailResponse.DataBean.SongHuLiYiDataBean bodyHealthData;
private AirTaskAdapter airAdapter;
private SpiritTaskAdapter spiritAdapter;
private int userId;
@Override
protected void initData() {
userId = getIntent().getIntExtra("userId",0);
titleToolBar.setTitle("异常数据");
titleToolBar.setLeftIconVisible(true);
titleToolBar.setTitleColor(getResources().getColor(R.color.colorBlack));
dataBinding.includeTitle.toolbarTitle.setBackgroundColor(getResources().getColor(R.color.white));
titleToolBar.setBackIconSrc(R.drawable.back_black);
viewModel.setTitleToolBar(titleToolBar);
tEnvironmentBeanList = new ArrayList<>();
airAdapter = new AirTaskAdapter(tEnvironmentBeanList);
dataBinding.recycleviewTodayenvironment.setLayoutManager(new LinearLayoutManager(this));
dataBinding.recycleviewTodayenvironment.setAdapter(airAdapter);
spiritListData = new ArrayList<>();
spiritAdapter = new SpiritTaskAdapter(spiritListData);
dataBinding.rlSpiritHealth.setLayoutManager(new LinearLayoutManager(this));
dataBinding.rlSpiritHealth.setAdapter(spiritAdapter);
todayHealthData = new HealthTaskDetailResponse.DataBean.SongEnDataBean();
bodyHealthData = new HealthTaskDetailResponse.DataBean.SongHuLiYiDataBean();
viewModel.getExceptionData(userId);
DropdownNewBar dropdownBarTodayEnvironment = new DropdownNewBar("今日环境", false, false);
DropdownNewBar dropdownBarTodayHealth = new DropdownNewBar("今日健康", false, false);
DropdownNewBar dropdownBarBodyHealth = new DropdownNewBar("身体健康", false, false);
DropdownNewBar dropdownBarSpiritHealth = new DropdownNewBar("精神健康", false, false);
List<DropdownNewBar> dropdownNewBarList = new ArrayList<>();
dropdownNewBarList = Arrays.asList(dropdownBarTodayEnvironment,dropdownBarTodayHealth,dropdownBarBodyHealth,dropdownBarSpiritHealth);
viewModel.dropdownBarLists.setValue(dropdownNewBarList);
}
@Override
protected void registerUIChangeEventObserver() {
super.registerUIChangeEventObserver();
if (tEnvironmentBeanList!=null && tEnvironmentBeanList.size()>0){
dataBinding.includeTodayEnvironmentNull.setVisibility(View.GONE);
}
viewModel.dataItemAir.observe(this, new Observer<List<HealthTaskDetailResponse.DataBean.SongARIListBean>>() {
@Override
public void onChanged(List<HealthTaskDetailResponse.DataBean.SongARIListBean> songARIListBeans) {
if (songARIListBeans!=null && songARIListBeans.size()>0){
if (tEnvironmentBeanList!=null && tEnvironmentBeanList.size()>0){
tEnvironmentBeanList.clear();
}
tEnvironmentBeanList.addAll(songARIListBeans);
airAdapter.notifyDataSetChanged();
}
}
});
viewModel.todayAirVisible.observe(this, new Observer<Boolean>() {
@Override
public void onChanged(Boolean aBoolean) {
if (aBoolean){
dataBinding.includeTodayEnvironment.tvCollapse.setVisibility(View.VISIBLE);
}else {
dataBinding.includeTodayEnvironment.tvCollapse.setVisibility(View.GONE);
}
}
});
viewModel.dataItemSpiritHealth.observe(this, new Observer<List<HealthTaskDetailResponse.DataBean.SleepDataBean>>() {
@Override
public void onChanged(List<HealthTaskDetailResponse.DataBean.SleepDataBean> sleepDataBeans) {
if (sleepDataBeans!=null && sleepDataBeans.size()>0){
if (spiritListData != null && spiritListData.size()>0){
spiritListData.clear();
}
spiritListData.addAll(sleepDataBeans);
spiritAdapter.notifyDataSetChanged();
}else {
dataBinding.rlSpiritHealth.setVisibility(View.GONE);
}
}
});
viewModel.spiritVisiable.observe(this, new Observer<Boolean>() {
@Override
public void onChanged(Boolean aBoolean) {
if (aBoolean){
dataBinding.includeSpiritHealth.tvCollapse.setVisibility(View.VISIBLE);
}else {
dataBinding.includeSpiritHealth.tvCollapse.setVisibility(View.GONE);
}
}
});
viewModel.dataItemTodayHealth.observe(this, new Observer<HealthTaskDetailResponse.DataBean.SongEnDataBean>() {
@Override
public void onChanged(HealthTaskDetailResponse.DataBean.SongEnDataBean songEnDataBean) {
if (songEnDataBean != null){
todayHealthData = songEnDataBean;
dataBinding.layoutTodayHealth.tvHealth1.setText(Html.fromHtml("步数:<font color=\"#000000\">"+todayHealthData.getSteps()+"</font>"));
dataBinding.layoutTodayHealth.tvHealth2.setText(Html.fromHtml("消耗:<font color=\"#000000\">"+todayHealthData.getCalorie()+"</font>"));
dataBinding.layoutTodayHealth.tvHealth3.setText(Html.fromHtml("高压:<font color=\"#000000\">"+todayHealthData.getHighPressure()+"</font>"));
dataBinding.layoutTodayHealth.tvHealth4.setText(Html.fromHtml("低压:<font color=\"#000000\">"+todayHealthData.getLowPressure()+"</font>"));
dataBinding.layoutTodayHealth.tvHealth5.setText(Html.fromHtml("血氧:<font color=\"#000000\">"+todayHealthData.getSaturation()+"</font>"));
dataBinding.layoutTodayHealth.tvHealth6.setText(Html.fromHtml("血糖:<font color=\"#000000\">"+todayHealthData.getPPG()+"</font>"));
dataBinding.layoutTodayHealth.tvHealth7.setText(Html.fromHtml("体温:<font color=\"#000000\">"+todayHealthData.getTemperature()+"</font>"));
dataBinding.layoutTodayHealth.tvHealth8.setText(Html.fromHtml("心率:<font color=\"#000000\">"+todayHealthData.getHeartRate()+"</font>"));
dataBinding.layoutTodayHealth.divisionLine4.setVisibility(View.GONE);
dataBinding.layoutTodayHealth.layout5.setVisibility(View.GONE);
}
}
});
viewModel.todayHealthVisible.observe(this, new Observer<Boolean>() {
@Override
public void onChanged(Boolean aBoolean) {
if (aBoolean){
dataBinding.includeTodayHealth.tvCollapse.setVisibility(View.VISIBLE);
dataBinding.layoutTodayHealth.getRoot().setVisibility(View.VISIBLE);
}else {
dataBinding.includeTodayHealth.tvCollapse.setVisibility(View.GONE);
dataBinding.layoutTodayHealth.getRoot().setVisibility(View.GONE);
}
}
});
viewModel.dataItemBodyHealth.observe(this, new Observer<HealthTaskDetailResponse.DataBean.SongHuLiYiDataBean>() {
@Override
public void onChanged(HealthTaskDetailResponse.DataBean.SongHuLiYiDataBean dataBean) {
if (dataBean!=null){
bodyHealthData = dataBean;
dataBinding.layoutBodyHealth.tvDeviceName.setText("护理仪");
dataBinding.layoutBodyHealth.tvHealth1.setText(Html.fromHtml("ID:<font color=\"#000000\">"+ ToolUtil.isNull(bodyHealthData.getDeviceId())+"</font>"));
dataBinding.layoutBodyHealth.tvHealth2.setText(Html.fromHtml("设定风温:<font color=\"#000000\">"+stateToString(bodyHealthData.getSetWindT())+"</font>"));
dataBinding.layoutBodyHealth.tvHealth3.setText(Html.fromHtml("设定水压:<font color=\"#000000\">"+stateToString(bodyHealthData.getSetWaterP())+"</font>"));
dataBinding.layoutBodyHealth.tvHealth4.setText(Html.fromHtml("设定水温:<font color=\"#000000\">"+stateToString(bodyHealthData.getSetWaterT())+"</font>"));
dataBinding.layoutBodyHealth.tvHealth5.setText(Html.fromHtml("当前风温:<font color=\"#000000\">"+ToolUtil.isNull(bodyHealthData.getCurrentWindT())+"</font>"));
dataBinding.layoutBodyHealth.tvHealth6.setText(Html.fromHtml("清洁空气状态:<font color=\"#000000\">"+ToolUtil.isNull(bodyHealthData.getCleanAirStatus() == 0 ? "等待中" : "进行中")+"</font>"));
dataBinding.layoutBodyHealth.tvHealth7.setText(Html.fromHtml("当前空气状态:<font color=\"#000000\">"+ToolUtil.isNull(bodyHealthData.getCurrentWorkStatus())+"</font>"));
dataBinding.layoutBodyHealth.tvHealth8.setText(Html.fromHtml("当前工作状态:<font color=\"#000000\">"+ToolUtil.isNull(bodyHealthData.getCurrentWorkStatus())+"</font>"));
dataBinding.layoutBodyHealth.divisionLine4.setVisibility(View.GONE);
dataBinding.layoutBodyHealth.layout5.setVisibility(View.GONE);
}
}
});
viewModel.bodyHealthVisible.observe(this, new Observer<Boolean>() {
@Override
public void onChanged(Boolean aBoolean) {
if (aBoolean){
dataBinding.layoutBodyHealth.getRoot().setVisibility(View.VISIBLE);
dataBinding.includeBodyHealth.tvCollapse.setVisibility(View.VISIBLE);
}else {
dataBinding.includeBodyHealth.tvCollapse.setVisibility(View.GONE);
dataBinding.layoutBodyHealth.getRoot().setVisibility(View.GONE);
}
}
});
dataBinding.includeTodayEnvironment.tvCollapse.setOnClickListener(v -> {
dataBinding.includeTodayEnvironment.tvExpand.setVisibility(View.VISIBLE);
dataBinding.includeTodayEnvironment.tvCollapse.setVisibility(View.GONE);
dataBinding.recycleviewTodayenvironment.setVisibility(View.GONE);
});
dataBinding.includeTodayEnvironment.tvExpand.setOnClickListener(v -> {
dataBinding.includeTodayEnvironment.tvExpand.setVisibility(View.GONE);
dataBinding.includeTodayEnvironment.tvCollapse.setVisibility(View.VISIBLE);
dataBinding.recycleviewTodayenvironment.setVisibility(View.VISIBLE);
});
dataBinding.includeTodayHealth.tvCollapse.setOnClickListener(v -> {
dataBinding.includeTodayHealth.tvExpand.setVisibility(View.VISIBLE);
dataBinding.includeTodayHealth.tvCollapse.setVisibility(View.GONE);
dataBinding.layoutTodayHealth.getRoot().setVisibility(View.GONE);
});
dataBinding.includeTodayHealth.tvExpand.setOnClickListener(v -> {
dataBinding.includeTodayHealth.tvExpand.setVisibility(View.GONE);
dataBinding.includeTodayHealth.tvCollapse.setVisibility(View.VISIBLE);
dataBinding.layoutTodayHealth.getRoot().setVisibility(View.VISIBLE);
});
dataBinding.includeBodyHealth.tvCollapse.setOnClickListener(v -> {
dataBinding.includeBodyHealth.tvExpand.setVisibility(View.VISIBLE);
dataBinding.includeBodyHealth.tvCollapse.setVisibility(View.GONE);
dataBinding.layoutBodyHealth.getRoot().setVisibility(View.GONE);
});
dataBinding.includeBodyHealth.tvExpand.setOnClickListener(v -> {
dataBinding.includeBodyHealth.tvExpand.setVisibility(View.GONE);
dataBinding.includeBodyHealth.tvCollapse.setVisibility(View.VISIBLE);
dataBinding.layoutBodyHealth.getRoot().setVisibility(View.VISIBLE);
});
dataBinding.includeSpiritHealth.tvCollapse.setOnClickListener(v -> {
dataBinding.includeSpiritHealth.tvExpand.setVisibility(View.VISIBLE);
dataBinding.includeSpiritHealth.tvCollapse.setVisibility(View.GONE);
dataBinding.rlSpiritHealth.setVisibility(View.GONE);
});
dataBinding.includeSpiritHealth.tvExpand.setOnClickListener(v -> {
dataBinding.includeSpiritHealth.tvExpand.setVisibility(View.GONE);
dataBinding.includeSpiritHealth.tvCollapse.setVisibility(View.VISIBLE);
dataBinding.rlSpiritHealth.setVisibility(View.VISIBLE);
});
}
@Override
public void initViewListener() {
super.initViewListener();
titleToolBar.setOnClickCallBack(this);
}
@Override
protected int initVariableId() {
return BR.ViewModel;
}
@Override
protected int setContentViewSrc(Bundle savedInstanceState) {
return R.layout.activity_task_data;
}
@Override
public void onRightIconClick() {
}
@Override
public void onBackIconClick() {
finish();
}
private String stateToString(int state) {
String string = "";
switch (state) {
case 0:
string = "低挡";
break;
case 1:
string = "中档";
break;
case 2:
string = "高挡";
break;
}
return string;
}
}
|
/*
* Copyright 2002-2013 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.integration.kafka.support;
import java.util.Map;
import kafka.serializer.Decoder;
import kafka.serializer.DefaultDecoder;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.integration.kafka.core.KafkaConsumerDefaults;
/**
* @author Soby Chacko
* @author Rajasekar Elango
* @since 0.5
*/
public class ConsumerMetadata<K,V> implements InitializingBean {
//High level consumer defaults
private String groupId = KafkaConsumerDefaults.GROUP_ID;
private String socketTimeout = KafkaConsumerDefaults.SOCKET_TIMEOUT;
private String socketBufferSize = KafkaConsumerDefaults.SOCKET_BUFFER_SIZE;
private String fetchSize = KafkaConsumerDefaults.FETCH_SIZE;
private String backoffIncrement = KafkaConsumerDefaults.BACKOFF_INCREMENT;
private String queuedChunksMax = KafkaConsumerDefaults.QUEUED_CHUNKS_MAX;
private String autoCommitEnable = KafkaConsumerDefaults.AUTO_COMMIT_ENABLE;
private String autoCommitInterval = KafkaConsumerDefaults.AUTO_COMMIT_INTERVAL;
private String autoOffsetReset = KafkaConsumerDefaults.AUTO_OFFSET_RESET;
private String rebalanceRetriesMax = KafkaConsumerDefaults.REBALANCE_RETRIES_MAX;
private String consumerTimeout = KafkaConsumerDefaults.CONSUMER_TIMEOUT;
private String topic;
private int streams;
private Decoder<V> valueDecoder;
private Decoder<K> keyDecoder;
private Map<String, Integer> topicStreamMap;
private TopicFilterConfiguration topicFilterConfiguration;
public String getGroupId() {
return groupId;
}
public void setGroupId(final String groupId) {
this.groupId = groupId;
}
public String getSocketTimeout() {
return socketTimeout;
}
public void setSocketTimeout(final String socketTimeout) {
this.socketTimeout = socketTimeout;
}
public String getSocketBufferSize() {
return socketBufferSize;
}
public void setSocketBufferSize(final String socketBufferSize) {
this.socketBufferSize = socketBufferSize;
}
public String getFetchSize() {
return fetchSize;
}
public void setFetchSize(final String fetchSize) {
this.fetchSize = fetchSize;
}
public String getBackoffIncrement() {
return backoffIncrement;
}
public void setBackoffIncrement(final String backoffIncrement) {
this.backoffIncrement = backoffIncrement;
}
public String getQueuedChunksMax() {
return queuedChunksMax;
}
public void setQueuedChunksMax(final String queuedChunksMax) {
this.queuedChunksMax = queuedChunksMax;
}
public String getAutoCommitEnable() {
return autoCommitEnable;
}
public void setAutoCommitEnable(final String autoCommitEnable) {
this.autoCommitEnable = autoCommitEnable;
}
public String getAutoCommitInterval() {
return autoCommitInterval;
}
public void setAutoCommitInterval(final String autoCommitInterval) {
this.autoCommitInterval = autoCommitInterval;
}
public String getAutoOffsetReset() {
return autoOffsetReset;
}
public void setAutoOffsetReset(final String autoOffsetReset) {
this.autoOffsetReset = autoOffsetReset;
}
public String getRebalanceRetriesMax() {
return rebalanceRetriesMax;
}
public void setRebalanceRetriesMax(final String rebalanceRetriesMax) {
this.rebalanceRetriesMax = rebalanceRetriesMax;
}
public String getConsumerTimeout() {
return consumerTimeout;
}
public void setConsumerTimeout(final String consumerTimeout) {
this.consumerTimeout = consumerTimeout;
}
public String getTopic() {
return topic;
}
public void setTopic(final String topic) {
this.topic = topic;
}
public int getStreams() {
return streams;
}
public void setStreams(final int streams) {
this.streams = streams;
}
public Decoder<V> getValueDecoder() {
return valueDecoder;
}
public void setValueDecoder(final Decoder<V> valueDecoder) {
this.valueDecoder = valueDecoder;
}
public Decoder<K> getKeyDecoder() {
return keyDecoder;
}
public void setKeyDecoder(final Decoder<K> keyDecoder) {
this.keyDecoder = keyDecoder;
}
public Map<String, Integer> getTopicStreamMap() {
return topicStreamMap;
}
public void setTopicStreamMap(final Map<String, Integer> topicStreamMap) {
this.topicStreamMap = topicStreamMap;
}
@Override
@SuppressWarnings("unchecked")
public void afterPropertiesSet() throws Exception {
if (valueDecoder == null) {
setValueDecoder((Decoder<V>) new DefaultDecoder(null));
}
if (keyDecoder == null) {
setKeyDecoder((Decoder<K>) getValueDecoder());
}
}
public TopicFilterConfiguration getTopicFilterConfiguration() {
return topicFilterConfiguration;
}
public void setTopicFilterConfiguration(
TopicFilterConfiguration topicFilterConfiguration) {
this.topicFilterConfiguration = topicFilterConfiguration;
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* IvSeqlastioId generated by hbm2java
*/
public class IvSeqlastioId implements java.io.Serializable {
private String relationid;
private String createtime;
private Long iotype;
public IvSeqlastioId() {
}
public IvSeqlastioId(String relationid, String createtime, Long iotype) {
this.relationid = relationid;
this.createtime = createtime;
this.iotype = iotype;
}
public String getRelationid() {
return this.relationid;
}
public void setRelationid(String relationid) {
this.relationid = relationid;
}
public String getCreatetime() {
return this.createtime;
}
public void setCreatetime(String createtime) {
this.createtime = createtime;
}
public Long getIotype() {
return this.iotype;
}
public void setIotype(Long iotype) {
this.iotype = iotype;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof IvSeqlastioId))
return false;
IvSeqlastioId castOther = (IvSeqlastioId) other;
return ((this.getRelationid() == castOther.getRelationid()) || (this.getRelationid() != null
&& castOther.getRelationid() != null && this.getRelationid().equals(castOther.getRelationid())))
&& ((this.getCreatetime() == castOther.getCreatetime()) || (this.getCreatetime() != null
&& castOther.getCreatetime() != null && this.getCreatetime().equals(castOther.getCreatetime())))
&& ((this.getIotype() == castOther.getIotype()) || (this.getIotype() != null
&& castOther.getIotype() != null && this.getIotype().equals(castOther.getIotype())));
}
public int hashCode() {
int result = 17;
result = 37 * result + (getRelationid() == null ? 0 : this.getRelationid().hashCode());
result = 37 * result + (getCreatetime() == null ? 0 : this.getCreatetime().hashCode());
result = 37 * result + (getIotype() == null ? 0 : this.getIotype().hashCode());
return result;
}
}
|
package com.example.behavioral.chainofresponsibility;
/**
* Copyright (C), 2020
* FileName: MainDemo
*
* @author: xieyufeng
* @date: 2020/10/13 17:54
* @description:
*/
public class MainDemo {
public static void main(String[] args) {
Manager commonManager = new CommonManager();
commonManager.setName("JingLi");
Manager majorManager = new MajorManager();
majorManager.setName("ZongJian");
Manager gereralManager = new GeneralManager();
gereralManager.setName("ZongJingLi");
commonManager.setNextLeader(majorManager);
majorManager.setNextLeader(gereralManager);
RequestMeta requestMeta1 = new RequestMeta("张三", 2, RequestTypeEnum.HOLIDAY.getRequestType());
RequestMeta requestMeta2 = new RequestMeta("李四", 4, RequestTypeEnum.HOLIDAY.getRequestType());
RequestMeta requestMeta3 = new RequestMeta("王五", 8, RequestTypeEnum.HOLIDAY.getRequestType());
RequestMeta requestMeta4 = new RequestMeta("小六", 15, RequestTypeEnum.HOLIDAY.getRequestType());
commonManager.handleRequest(requestMeta1);
commonManager.handleRequest(requestMeta2);
commonManager.handleRequest(requestMeta3);
commonManager.handleRequest(requestMeta4);
RequestMeta requestMeta5 = new RequestMeta("张三", 500, RequestTypeEnum.RAISE.getRequestType());
RequestMeta requestMeta6 = new RequestMeta("李四", 1500, RequestTypeEnum.RAISE.getRequestType());
RequestMeta requestMeta7 = new RequestMeta("王五", 3000, RequestTypeEnum.RAISE.getRequestType());
RequestMeta requestMeta8 = new RequestMeta("小六", 10000, RequestTypeEnum.RAISE.getRequestType());
commonManager.handleRequest(requestMeta5);
commonManager.handleRequest(requestMeta6);
commonManager.handleRequest(requestMeta7);
commonManager.handleRequest(requestMeta8);
}
}
|
package actors;
import display.Camera;
import entity.Entity;
import entity.WinHeart;
import handler.Handler;
import input.KeyInput;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import sun.audio.AudioPlayer;
import tile.Tile;
import util.Util;
import world.World;
public class Player extends Actor {
private KeyInput key;
private boolean jumping;
private double time = 0;
public static int health = 3;
public static int points = 0;
public Player(int x, int y, int speed, Handler handler, World world) {
super(x, y, speed, "resources/textures/playerAnimation.png", 5, 4, 9, world, true);
this.key = handler.getKeyInput();
}
@Override
public void update() {
updateAnimationFrame();
updateCollisionBox(7, 0, 17, 31);
updateCollisionWithEnemy();
updateCollisionWithEntity();
physics.update(jumping);
jump();
move();
}
@Override
public void render(Graphics g) {
renderPlayer(g);
renderHealth(g);
RenderPoints(g);
}
private void move() {
if (key.isRight()) {
if (!collision.collisionWithSolidTile(speed, "right") || key.isEditor()) {
x += speed;
animationDirection = 3;
return;
}
}
if (key.isLeft()) {
if (!collision.collisionWithSolidTile(speed, "left") || key.isEditor()) {
x -= speed;
animationDirection = 1;
return;
}
}
animationDirection = 0;
}
private void jump() {
double jumpSpeed = 2.0;
if (jumping) {
y -= jumpSpeed * time;
time -= 0.2;
}
if (!physics.getGravity().isFalling() && !jumping) {
if (key.isUp()) {
jumping = true;
}
}
if (time <= 0.0 || collision.collisionWithSolidTile((int) jumpSpeed, "up")) {
time = 5;
jumping = false;
}
}
private void updateCollisionWithEnemy() {
if (!Tile.editor) {
Actor enemy = collision.collisionWithEnemy();
if (enemy != null) {
health--;
world.getEnemyList().remove(enemy);
}
}
}
private void updateCollisionWithEntity() {
if (!Tile.editor) {
Entity entity = collision.collisionWithEntity();
if (entity != null) {
if (!(entity instanceof WinHeart)) {
points += entity.getPoints();
world.getEntityList().remove(entity);
// AudioPlayer.player.start(Util.getSound("resources/sounds/coin.wav"));
}
}
}
}
private void renderPlayer(Graphics g) {
g.drawImage(animation[animationDirection][animationFrame % 5], x - Camera.xOffset, y, null);
// g.fillRect(collisionBox.x, collisionBox.y, collisionBox.width, collisionBox.height); // draws collision box
}
private void renderHealth(Graphics g) {
int imageY = 7;
BufferedImage image = Util.getImage("resources/textures/heart.png");
for (int i = 0; i < health; i++) {
g.drawImage(image, i * 32, imageY, null);
}
}
private void RenderPoints(Graphics g) {
g.setColor(Color.red);
// g.setFont(new Font("", 1, 20));
g.drawString(String.valueOf(points), 10, 60);
}
public boolean isJumping() {
return jumping;
}
public int getHealth() {
return health;
}
public int getPoints() {
return points;
}
public void addToHealth(int amount){
health += amount;
}
}
|
import java.util.Scanner;
/**
*
* @author ryanbarbera
*/
public class ActionMenu {
Scanner user_input = new Scanner(System.in);
/**
* Select what enemy to fight.
* @param current_room list of enemies in that room.
* @return who the player will be fighting.
*/
public int fight_menu(Room current_room) {
System.out.println(current_room);
System.out.println("--------------");
System.out.println("who will you fight?");
System.out.println("--------------");
int position = user_input.nextInt();
user_input.nextLine();
if(position > current_room.enemylist.size() - 1) {
System.out.println("ERROR enter a valid position");
return fight_menu(current_room);
}
System.out.println("--------------");
return position;
}
/**
* Selects ability to shoot
* @param current_room Used for enemy list.
* @param position What specific enemy they're fighting.
* @return Shoots enemy.
*/
public int shoot(Room current_room, int position){
Enemy enemy_we_fight = current_room.enemylist.get(position);
System.out.println("Targetted enemy " + enemy_we_fight);
System.out.println(enemy_we_fight);
System.out.println("--------------");
System.out.println("Would you like to shoot? (1)");
int shoot = user_input.nextInt();
user_input.nextLine();
return shoot;
}
/**
* Moves to the next room instance.
* @param current_room Looks at the room list.
* @param roomgen Generates the next room.
* @param player_test Uses the player themselves to move.
* @return The move command of "1"
*/
public int next_room(Room current_room, RoomGen roomgen, Player player_test){
System.out.println("--------------");
System.out.println("All enemies have been defeated");
System.out.println("--------------");
System.out.println("Would you like to move forward? (Hit 1 to move forward)");
int input = user_input.nextInt();
user_input.nextLine();
return input;
}
}
|
package exerc7;
import java.io.File;
import java.util.Comparator;
// classe usada para organizar o ArrayList com os arquivos pelo tamanho
public class MySort implements Comparator<File> {
@Override
public int compare(File f1, File f2){
return (int) (f2.length() - f1.length());
}
}
|
package com.tencent.mm.plugin.voip.model;
class p$3 implements Runnable {
final /* synthetic */ p oMX;
p$3(p pVar) {
this.oMX = pVar;
}
public final void run() {
this.oMX.oMW.SO();
}
}
|
package com.sharpower.quartzs;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import com.sharpower.beckhoff.FunDataReadWriteBeckhoffService;
import com.sharpower.entity.Fun;
import com.sharpower.entity.PlcType;
import com.sharpower.service.PlcDataReader;
import com.sharpower.service.PlcTypeService;
import com.sharpower.service.RecodeService;
import de.beckhoff.jni.tcads.AdsCallDllFunction;
public class DataQuartz {
private PlcTypeService plcTypeService;
private FunDataReadWriteBeckhoffService funDataReadWriteBeckhoffService;
private RecodeService recodeService;
private List<PlcType> plcTypes = new ArrayList<>();
private Map<Integer, Boolean> readDataTheadStaMap = new ConcurrentHashMap<>();
private Map<Integer,Map<String, Object>> dataMap = new ConcurrentHashMap<>();
private Map<String, Object> params = new HashMap<>();
private List<Fun> funs = new ArrayList<>();
public void setPlcTypeService(PlcTypeService plcTypeService) {
this.plcTypeService = plcTypeService;
}
public void setFunDataReadWriteBeckhoffService(FunDataReadWriteBeckhoffService funDataReadWriteBeckhoffService) {
this.funDataReadWriteBeckhoffService = funDataReadWriteBeckhoffService;
}
public void setRecodeService(RecodeService recodeService) {
this.recodeService = recodeService;
}
public void setParams(Map<String, Object> params) {
this.params = params;
}
public Map<Integer, Map<String, Object>> getDataMap() {
return dataMap;
}
private void init(){
if (funs.isEmpty()){
plcTypes = plcTypeService.findEntityByHQL("FROM PlcType p LEFT JOIN FETCH p.funs");
for ( PlcType plcType : plcTypes ) {
for (Fun fun : plcType.getFuns()) {
if (!fun.isDisabled()) {
funs.add(fun);
}
}
}
for (Fun fun : funs) {
readDataTheadStaMap.put(fun.getId(), false);
if (fun.getPlcType().getPlcCommType().getName().equals("beckhoff")) {
AdsCallDllFunction.adsPortOpen();
}
}
}
}
public void readData(){
synchronized (this) {
init();
for (Fun fun : funs) {
PlcDataReader plcDataReader;
if (fun.getPlcType().getPlcCommType().getName().equals("beckhoff")) {
plcDataReader = funDataReadWriteBeckhoffService;
}else {
plcDataReader = funDataReadWriteBeckhoffService;
}
//检查上轮线程状态,如已完成则创建新线程,未完成则不创建
Boolean threadSta = readDataTheadStaMap.get(fun.getId());
if (threadSta!=true){
readDataTheadStaMap.put(fun.getId(), true);
FunDataThread funDataThread = new FunDataThread();
funDataThread.setPlcData(plcDataReader);
funDataThread.setFun(fun);
funDataThread.setParams(params);
funDataThread.setDataMap(dataMap);
funDataThread.setReadDataTheadStaMap(readDataTheadStaMap);
Thread thread = new Thread(funDataThread);
thread.start();
}
}
}
}
public void saveData(){
Date now = new Date();
for (Entry<Integer,Map<String, Object>> entry : dataMap.entrySet()) {
Map<String, Object> dataTemp = new HashMap<>();
dataTemp.putAll(entry.getValue());
dataTemp.put( "id", null );
dataTemp.put( "dateTime", now );
recodeService.save( dataTemp );
}
}
@Override
protected void finalize() throws Throwable {
super.finalize();
for (Fun fun : funs) {
AdsCallDllFunction.adsPortClose();
}
}
}
|
package com.codersergg.demo_mongoDB.repository;
import com.codersergg.demo_mongoDB.model.Photo;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface PhotoRepository extends MongoRepository<Photo, String> { }
|
package com.accenture.exception;
public class StudentIdMismatch extends RuntimeException{
}
|
package April.ElgunAZE;
import java.util.*;
public class Elgun {
public static void main(String[] args) {
// String str [][] = {{"Mike Artrur","Mike123"},
// {"Jason Mike","Coole1233"},
// {"Johnny avard","Avard123"},
// {"Ford","Fiesta"}};
//
//
// for(int i =0,j =3; i <=4;i++,j--){
// //System.out.println(i);
// System.out.println(j);
// }
int num[] ={14, 16, 3, 7, 17, 19, 9}; //16, 7, 17, 19
for(int i =0; i < num.length; i++){
if(num[i] < num[i+1]){
System.out.println(num[i+1]);
}
}
}
}
|
package src;
import java.io.IOException;
import java.util.Scanner;
public class H009 {
public static void main(String... args) throws IOException {
while (true) {
System.out.println("How much Fibonacci numbers you want to see?");
long quantity;
try {
Scanner scanner = new Scanner(System.in);
quantity = scanner.nextInt();
} catch (RuntimeException e) {
continue;
}
if (quantity == 0) {
System.out.println("Bravo! That's your 0 Fibonacci numbers!");
System.out.println("Well done!");
break;
} else if (quantity == 1) {
System.out.println("Your dear Fibonacci numbers: 0.");
System.out.println("That's all!");
break;
} else if (quantity == 2) {
System.out.println("Your dear Fibonacci numbers: 0, 1.");
System.out.println("That's all!");
break;
} else if (quantity == 3) {
System.out.println("Your dear Fibonacci numbers: 0, 1, 1.");
System.out.println("That's all!");
break;
} else if (quantity < 3)
continue;
System.out.print("Your dear Fibonacci numbers: ");
long oldNewYear, newNewYear = 0, value = 1;
for (long i = 0; i < quantity - 2; i++) {
oldNewYear = newNewYear;
newNewYear = value;
value = oldNewYear + newNewYear;
if (i == 0)
System.out.print("0, 1, ");
System.out.print(value);
if (i < quantity - 3)
System.out.print(", ");
else {
System.out.println(".");
System.out.println("That's all!");
}
}
break;
}
}
}
|
package com.kumar.penguingame;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class AfricanActivity extends Activity {
RadioGroup radiogroup1;
RadioButton rb4, rb5, rb6;
Button b2;
TextView sc1;
int counter = 1;
int temp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.african);
int val1 = getIntent().getExtras().getInt("val", -1);
sc1 = (TextView)findViewById(R.id.txt4);
sc1.setText("Score : " + val1 );
radiogroup1 = (RadioGroup) findViewById(R.id.rg2);
rb4 = (RadioButton) findViewById(R.id.yelloweyedbutton);
rb5 = (RadioButton) findViewById(R.id.africanbutton1);
rb6 = (RadioButton) findViewById(R.id.macoronibutton);
b2 = (Button)findViewById(R.id.button2);
rb4.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (counter == 1){
counter ++;
Toast.makeText(AfricanActivity.this,rb4.getText(), Toast.LENGTH_SHORT).show();
} else if (counter >1){
Toast.makeText(AfricanActivity.this," Please Try again ", Toast.LENGTH_SHORT).show();
} }
});
rb5.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (counter == 1){
temp = getIntent().getExtras().getInt("val", -1) + 5;
counter ++;
sc1.setText("Score : " + temp);
Toast.makeText(AfricanActivity.this,rb5.getText(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(AfricanActivity.this, BlueActivity.class);
intent.putExtra("val2", temp);
startActivity(intent);
}else if (counter >1){
Toast.makeText(AfricanActivity.this," Please Try again ", Toast.LENGTH_SHORT).show();
} }
});
rb6.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (counter == 1){
counter ++;
Toast.makeText(AfricanActivity.this,rb6.getText(), Toast.LENGTH_SHORT).show();
} else if (counter >1){
Toast.makeText(AfricanActivity.this," Please Try again ", Toast.LENGTH_SHORT).show();
} }
});
b2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(AfricanActivity.this," Known as Jackass Penguin ", Toast.LENGTH_SHORT).show();
}
});
}
} |
package com.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import com.pojo.Register_User;
public class Dao_Registration {
public int register(Register_User reg) {
int success=0;
Dao_Connect connect= new Dao_Connect();
Connection con=connect.database();
try {
String query= "INSERT INTO crud_app.mvc_crud()VALUES (?,?,?)";
PreparedStatement ps= con.prepareStatement(query);
ps.setString(1, reg.getUsername());
ps.setString(2, reg.getPassword());
ps.setString(3, reg.getConfirmpassword());
success=ps.executeUpdate();
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("Something Went Wrong!!!");
}
return success;
}
}
|
package com.utils.tools.research.service.Impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.utils.tools.research.mapper.MsgMapper;
import com.utils.tools.research.pojo.Msg;
import com.utils.tools.research.service.MsgService;
import com.utils.util.wrapper.BaseQueryDto;
import com.utils.util.wrapper.PageUtil;
import com.utils.util.wrapper.PageWrapMapper;
import com.utils.util.wrapper.PageWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class MsgServiceImpl extends ServiceImpl<MsgMapper, Msg> implements MsgService {
@Autowired
private MsgMapper msgMapper;
@Override
public PageWrapper<List<Msg>> getListByPage(BaseQueryDto baseQueryDto) {
Page page = PageHelper.startPage(baseQueryDto.getPageNum(), baseQueryDto.getPageSize());
List<Msg> list = msgMapper.getList();
Long total = page.getTotal();
return PageWrapMapper.wrap(list, new PageUtil(total.intValue(), baseQueryDto.getPageNum(), baseQueryDto.getPageSize()));
}
}
//docker run -p 56379:56379 --name redis -v /usr/local/redis/conf/redis.conf:/etc/redis/redis.conf -v /usr/local/redis/data:/data -d redis:5.0.5 redis-server /etc/redis/redis.conf --appendonly yes
|
package me.solidev.quickdevlib.entity.news_type;
import me.solidev.quickdevlib.entity.NewsItem;
/**
* Created by _SOLID
* Date:2016/9/29
* Time:13:16
* Desc:
*/
public class DefaultNewsItem extends NewsItem {
}
|
package com.wincentzzz.project.template.springhack.mapper;
import com.wincentzzz.project.template.springhack.dto.request.ExaminationRequest;
import com.wincentzzz.project.template.springhack.dto.response.ExaminationListResponse;
import com.wincentzzz.project.template.springhack.dto.response.ExaminationResponse;
import com.wincentzzz.project.template.springhack.models.Appointment;
import com.wincentzzz.project.template.springhack.models.Examination;
import java.util.List;
import java.util.stream.Collectors;
public class ExaminationMapper {
public static List<ExaminationListResponse> toListOfExaminationResponse(List<Examination> examinations){
return examinations.stream().map(examination -> ExaminationListResponse.builder()
.id(examination.getId())
.name(examination.getName())
.file(examination.getFile())
.build()
).collect(Collectors.toList());
}
public static ExaminationResponse toExaminationResponse(Examination examination){
return ExaminationResponse.builder()
.id(examination.getId())
.name(examination.getName())
.file(examination.getFile())
.build();
}
public static Examination toExamination(ExaminationRequest examinationRequest){
return Examination.builder()
.name(examinationRequest.getName())
.file(examinationRequest.getFile())
.appointment(Appointment.builder().id(examinationRequest.getAppointmentId()).build())
.build();
}
public static Examination toExamination(ExaminationRequest examinationRequest, Long id){
return Examination.builder()
.name(examinationRequest.getName())
.file(examinationRequest.getFile())
.appointment(Appointment.builder().id(examinationRequest.getAppointmentId()).build())
.id(id)
.build();
}
}
|
package com.it.userportrait.reduce;
import com.it.userportrait.analy.EntanglementProductEntity;
import org.apache.commons.lang.StringUtils;
import org.apache.flink.api.common.functions.ReduceFunction;
public class EntanglementProductAnlayReduce implements ReduceFunction<EntanglementProductEntity> {
public EntanglementProductEntity reduce(EntanglementProductEntity entanglementProductEntity, EntanglementProductEntity t1) throws Exception {
long numbers1 = 0l;
String groupField = "";
if(entanglementProductEntity != null){
numbers1 =entanglementProductEntity.getNumbers();
groupField = entanglementProductEntity.getGroupField();
}
long numbers2 = 0l;
if(t1 != null){
numbers2 = t1.getNumbers();
groupField = t1.getGroupField();
}
if(StringUtils.isNotBlank(groupField)){
EntanglementProductEntity entanglementProductEntity1 = new EntanglementProductEntity();
entanglementProductEntity1.setGroupField(groupField);
entanglementProductEntity1.setNumbers(numbers1+numbers2);
return entanglementProductEntity1;
}
return null;
}
}
|
package com.learn.learn.bassis.broadcast.binder;
/**
* Created by Administrator on 2018/8/25 0025.
*/
/**
* 类 名: OnProgressListener<br>
* 说 明:<br>
* 创建日期:2018/8/25 0025<br>
* 作 者:蒋委员长<br>
* 功 能:<br>
* 注 意:<br>
* 待做事情:
*/
public interface OnProgressListener {
void onProgress(int progress);
}
|
package microservice.currencyconversionservice.service;
import microservice.currencyconversionservice.entity.CurrencyConversion;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
//@FeignClient(name= "currency-exchange-service",url = "localhost:8000")
// when we want to talk to multiple instance of currency-exchange-service we do not need the URI
//@RibbonClient(name = "currency-exchange-service")
//@FeignClient(name= "netflix-zulu-gateway-server",url = "localhost:8765")
@FeignClient(name= "currency-exchange-service")
public interface CurrencyExchangeServiceProxy {
// @GetMapping("/currency-exchange/from/{from}/to/{to}")
// public CurrencyConversion retrieveExchangeValue(@PathVariable("from") String from, @PathVariable("to") String to);
@GetMapping("/currency-exchange-service/currency-exchange/from/{from}/to/{to}")
public CurrencyConversion retrieveExchangeValue(@PathVariable("from") String from, @PathVariable("to") String to);
}
|
/*
* Copyright 2009 Kjetil Valstadsve
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package vanadis.extrt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vanadis.core.collections.Generic;
import vanadis.core.lang.Not;
import vanadis.core.lang.Strings;
import vanadis.core.properties.PropertySet;
import vanadis.core.properties.PropertySets;
import vanadis.core.reflection.Retyper;
import vanadis.ext.CoreProperty;
import vanadis.ext.Property;
import vanadis.objectmanagers.ObjectManagerInjectPointMBean;
import vanadis.osgi.*;
import vanadis.services.networking.RemoteInjectPoint;
import java.util.Map;
import java.util.Set;
abstract class Injector<T> extends ManagedFeature<T, ObjectManagerInjectPointMBean> {
private final boolean remotable;
private final Filter annotatedFilter;
private final int minimum;
private final boolean injectUpdates;
private final InjectionListener listener;
private final boolean multi;
private final boolean retained;
private final Map<Reference<T>, T> references = Generic.map();
private int injectCount;
private Registration<RemoteInjectPoint> remoteInjectPointRegistration;
private final boolean passReference;
private Filter filter;
private boolean discontinued;
Injector(FeatureAnchor<T> featureAnchor, Property[] annotatedProperties,
boolean remotable,
int minimum,
boolean multi,
boolean retained,
boolean injectUpdates,
boolean passReference,
InjectionListener listener) {
super(featureAnchor, ObjectManagerInjectPointMBean.class);
this.annotatedFilter = filter(annotatedProperties, featureAnchor.getPropertySet());
this.remotable = remotable;
this.minimum = minimum;
this.multi = multi;
this.retained = retained;
this.injectUpdates = injectUpdates;
this.listener = listener;
this.passReference = passReference;
}
@Override
protected ObjectManagerInjectPointMBean mbean() {
return new ObjectManagerInjectPointMBeanImpl(this);
}
final Filter getFilter() {
return filter;
}
@Override
final boolean isComplete() {
return injectCount >= getMinimum();
}
final Set<Reference<T>> getReferences() {
return references.keySet();
}
@Override
final void activate() {
if (isRemotable()) {
registerRemoteInjectPoint(getContext());
}
doActivate();
}
@Override
protected final void performDeactivate() {
if (remoteInjectPointRegistration != null) {
remoteInjectPointRegistration.unregister();
}
for (Map.Entry<Reference<T>, T> entry : Generic.list(references.entrySet())) {
uninject(entry.getKey(), entry.getValue());
}
doDeactivate();
}
final Map.Entry<Reference<T>, T> getReplacement() {
return references.entrySet().iterator().next();
}
final boolean containsReferences() {
return !references.isEmpty();
}
final boolean isRemotable() {
return remotable;
}
final Filter getAnnotatedFilter() {
return annotatedFilter;
}
final int getMinimum() {
return minimum;
}
@Override
final boolean isMulti() {
return multi;
}
final Object getManaged() {
return getObjectManager().getManagedObject();
}
final boolean isPassReference() {
return passReference;
}
final Filter filter() {
if (filter == null) {
filter = isRemotable() ? getAnnotatedFilter().and(REMOTABLE_FILTER) : getAnnotatedFilter();
}
return filter;
}
final void inject(Reference<T> reference, T providedService, boolean update) {
Not.nil(reference, "reference");
if (discontinued) {
log.debug(this + " discontinued, skipping inject of " + providedService);
return;
}
if (update && !injectUpdates) {
return;
}
T service = providedService != null ? providedService : reference.getService();
if (service == null) {
log.warn(this + " was asked to inject null-valued service for reference " + reference);
return;
}
try {
performInject(reference, service);
log.info(this + " injected " + service);
} finally {
if (retained) {
references.put(reference, service);
}
injectCount++;
fireInjected();
}
}
final void uninject(Reference<T> reference, T providedService) {
Not.nil(reference, "reference");
if (discontinued) {
log.debug(this + " discontinued, skipping uninject of " + providedService);
return;
}
T service = resolveService(reference, providedService);
if (retained) {
references.remove(reference);
}
if (service == null) {
log.warn(this + " could not uninject reference " + reference + ", no service could be resolved");
return;
}
try {
performUninject(reference, service);
} catch (RuntimeException e) {
processInvocationError(e);
} finally {
reference.unget();
injectCount--;
fireRetracted();
}
}
private void processInvocationError(RuntimeException e) {
if (shutdownRaceIssues(e)) {
if (log.isDebugEnabled()) {
log.debug(this + " failed to uninject, assuming shutdown races", e);
}
} else {
throw e;
}
}
private T resolveService(Reference<T> reference, T providedService) {
T retainedService = references.get(reference);
if (retained && retainedService == null) {
log.warn(this + " did not have retained reference " + reference +
", provided service was: " + providedService);
}
if (retainedService != null && providedService == null) {
return retainedService;
} else if (providedService != null && retainedService == null) {
return providedService;
}
if (retainedService != providedService) {
throw new IllegalArgumentException
(this + " contained " + retainedService + ", was asked to unregister " + providedService);
}
return providedService;
}
protected abstract void doDeactivate();
protected abstract void doActivate();
protected abstract void performInject(Reference<T> reference, T service);
protected abstract void performUninject(Reference<T> reference, T service);
private void fireInjected() {
try {
listener.wasInjected(this);
} catch (Throwable e) {
log.warn(this + " could not notify listener " + listener + " about injection", e);
}
}
private void fireRetracted() {
try {
listener.wasRetracted(this);
} catch (Throwable e) {
log.warn(this + " could not notify listener " + listener + " about retraction", e);
}
}
private boolean shutdownRaceIssues(RuntimeException e) {
// Can't use CausesIterable here - it may not be accessible anymore!
for (Throwable cause = e; cause != null; cause = cause.getCause()) {
if (cause instanceof ClassNotFoundException || cause instanceof NoClassDefFoundError) {
discontinued = true;
return true;
}
}
return false;
}
private void registerRemoteInjectPoint(Context context) {
ServiceProperties<RemoteInjectPoint> serviceProperties =
ServiceProperties.create(RemoteInjectPoint.class);
RemoteInjectPoint service =
new RemoteInjectPoint(getServiceInterface(),
getObjectManagerName(),
filter());
remoteInjectPointRegistration = context.register(service, serviceProperties);
}
private static final Logger log = LoggerFactory.getLogger(Injector.class);
private static final String[] NO_STRINGS = new String[]{};
private static final Filter REMOTABLE_FILTER = CoreProperty.REMOTABLE.filter(true);
private static Filter filter(Property[] properties, PropertySet configuredProperties) {
Filter filter = Filters.NULL;
for (Property property : properties) {
String[] value = values(property.value(), property.values());
String name = property.name();
Class<?> propertyType = property.propertyType();
Filter append = value.length == 0 ? Filters.present(name)
: Filters.eq(name, Retyper.coerceArray(propertyType, value));
filter = filter.and(property.negate() ? append.not() : append);
}
for (String property : configuredProperties) {
String value = configuredProperties.getString(property, PropertySets.systemProperties());
Filter append = Strings.isEmpty(value) ? Filters.present(value)
: Filters.eq(property, value);
filter = filter.and(append);
}
return filter;
}
private static String[] values(String singleValue, String[] multiValues) {
if (multiValues.length == 0) {
String value = singleValue.trim();
return value.length() == 0 ? NO_STRINGS
: new String[]{value};
}
return multiValues;
}
@Override
public long[] getServiceIds() {
Map<Reference<T>, T> map = Generic.map(references);
long[] ids = new long[references.size()];
int i = 0;
for (Reference<?> reference : map.keySet()) {
ids[i++] = reference.getServiceId();
}
return ids;
}
}
|
package cn.com.ykse.santa.service.vo;
/**
* Created by youyi on 2016/2/22.
*/
public class CommentVO {
private int refId;
private String category;
private String content;
private String author;
private String gmtCreate;
public int getRefId() {
return refId;
}
public void setRefId(int refId) {
this.refId = refId;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getGmtCreate() {
return gmtCreate;
}
public void setGmtCreate(String gmtCreate) {
this.gmtCreate = gmtCreate;
}
}
|
package com.elepy.models.props;
import com.elepy.annotations.FileReference;
import com.elepy.models.FieldType;
import com.elepy.models.Property;
import com.elepy.uploads.FileUploadEvaluator;
import java.lang.reflect.AccessibleObject;
public class FileReferencePropertyConfig implements PropertyConfig {
private final String allowedExtensions;
private final long maximumFileSize;
public FileReferencePropertyConfig(String allowedMimeType, long maximumFileSize) {
this.allowedExtensions = allowedMimeType;
this.maximumFileSize = maximumFileSize;
}
public static FileReferencePropertyConfig of(AccessibleObject accessibleObject) {
final var annotation = accessibleObject.getAnnotation(FileReference.class);
return new FileReferencePropertyConfig(annotation == null ? "*/*" : annotation.allowedMimeType(), annotation == null ? FileUploadEvaluator.DEFAULT_MAX_FILE_SIZE : annotation.maximumFileSize());
}
public static FileReferencePropertyConfig of(Property property) {
return new FileReferencePropertyConfig(property.getExtra("allowedMimeType"), property.getExtra("maximumFileSize"));
}
@Override
public void config(Property property) {
property.setType(FieldType.FILE_REFERENCE);
property.setExtra("allowedMimeType", allowedExtensions);
property.setExtra("maximumFileSize", maximumFileSize);
}
public String getAllowedMimeType() {
return allowedExtensions;
}
public long getMaxSizeInBytes() {
return maximumFileSize;
}
}
|
package com.layla;
import android.app.Application;
import com.parse.Parse;
import com.parse.ParseACL;
import com.parse.ParseInstallation;
import com.parse.ParsePush;
public class StarterParse extends Application
{
@Override
public void onCreate()
{
super.onCreate();
// Enable Local Datastore.
Parse.enableLocalDatastore(this);
// Add your initialization code here
Parse.initialize(new Parse.Configuration.Builder(getApplicationContext())
.applicationId("ed27f8b32bcae4823258606d1f059228db9839dd")
.clientKey("07bed1deda6b12c4ea3b51e9a722eeeaf8d4d414")
.server("http://35.159.11.157:80/parse/")
.build()
);
ParseInstallation.getCurrentInstallation().saveInBackground();
ParsePush.subscribeInBackground("");
//ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
defaultACL.setPublicReadAccess(true);
defaultACL.setPublicWriteAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
}
}
|
package com.android.superlorenzo;
import android.gameengine.icadroids.objects.GameObject;
public class Kaas extends GameObject{
private int size;
private LorenzoGame game;
public Kaas(LorenzoGame game, int size)
{
this.size = size;
this.game = game;
if (size==2){
setSprite("kaas1");
}
else if (size==3){
setSprite("kaas2");
}
else if (size==4){
setSprite("kaas3");
}
else if (size==5){
setSprite("kaas4");
}
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
|
package com.handsomedong.dynamic.datasource.helper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
* Created by HandsomeDong on 2021/9/30 23:48
* 路由到对应的数据源
*/
@Slf4j
public class DynamicRoutingDataSource extends AbstractRoutingDataSource {
private Map<Object, Object> targetDataSources = new HashMap<>();
public DynamicRoutingDataSource() {
setTargetDataSources(targetDataSources);
}
@Override
protected Object determineCurrentLookupKey() {
log.info("Route datasource: {}", DynamicDataSourceContextHolder.getDSKey());
return DynamicDataSourceContextHolder.getDSKey();
}
public void addDataSource(String dataSourceKey, DataSource dataSource) {
targetDataSources.put(dataSourceKey, dataSource);
log.info("Added datasource {} successfully ", dataSource);
}
}
|
package au.com.flexisoft.redisutil.dto;
import java.io.Serializable;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Setter
@Getter
@ToString
public class Account implements Serializable {
private Integer id;
private String type;
private Double amount;
private List<AccountSummary> accountSummaries;
}
|
package io.github.qyvlik.iostnode.response.info;
import com.alibaba.fastjson.annotation.JSONField;
import java.math.BigDecimal;
public class RAMInfo {
@JSONField(name = "available")
private BigDecimal available; // 可用 RAM 数量,以 byte 为单位
@JSONField(name = "total")
private BigDecimal total; // 系统总计 RAM 数量,以 byte 为单位
@JSONField(name = "used")
private BigDecimal used; // 已经出售的 RAM 数量,以 byte 为单位
public BigDecimal getAvailable() {
return available;
}
public void setAvailable(BigDecimal available) {
this.available = available;
}
public BigDecimal getTotal() {
return total;
}
public void setTotal(BigDecimal total) {
this.total = total;
}
public BigDecimal getUsed() {
return used;
}
public void setUsed(BigDecimal used) {
this.used = used;
}
@Override
public String toString() {
return "RAMInfo{" +
"available=" + available +
", total=" + total +
", used=" + used +
'}';
}
}
|
// $Id: random.java,v 1.11 2001/07/31 16:38:37 doug Exp $
// http://www.bagley.org/~doug/shootout/
package com.harris.mobihoc;
import java.text.*;
public class random implements Runnable{
public static final long IM = 139968;
public static final long IA = 3877;
public static final long IC = 29573;
private boolean contin = false;
private int N = 10;
public random(boolean contin, int N){
this.contin = contin;
this.N = N;
}
@Override
public void run(){
//int N = Integer.parseInt(args[0]) - 1;
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(9);
nf.setMinimumFractionDigits(9);
nf.setGroupingUsed(false);
while (N-- > 0) {
gen_random(100);
}
System.out.println(nf.format(gen_random(100)));
if(contin){
try{
Thread trial = new Thread(new sieve(contin, N));
trial.start();
}catch(Exception e){
e.printStackTrace();
}
}
}
public static long last = 42;
public static double gen_random(double max) {
return( max * (last = (last * IA + IC) % IM) / IM );
}
}
|
package com.tencent.mm.plugin.fav.ui.widget;
import android.view.View;
import android.view.View.OnClickListener;
class b$1 implements OnClickListener {
final /* synthetic */ b jfn;
public b$1(b bVar) {
this.jfn = bVar;
}
public final void onClick(View view) {
if (this.jfn.jfm != null) {
this.jfn.jfm.aMy();
}
}
}
|
package com.wanglu.movcat.util;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* Created by wangl on 2017/10/26 0026.
*/
public class RedisTemplateUtil {
public static RedisTemplate setRedisTemplate(RedisTemplate redisTemplate) {
RedisSerializer stringSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringSerializer);
redisTemplate.setValueSerializer(stringSerializer);
redisTemplate.setHashKeySerializer(stringSerializer);
redisTemplate.setHashValueSerializer(stringSerializer);
return redisTemplate;
}
}
|
package q0084_hard;
public class LargestRectangleInHistogram {
}
|
package com.android.lvxin.videos;
/**
* Created by Administrator on 2015/11/15.
*/
import android.content.ContentUris;
import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.lvxin.R;
import com.android.lvxin.data.VideoInfo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
public class StaggeredAdapter extends RecyclerView.Adapter<StaggeredAdapter.VerticalItemHolder> {
private final static String TAG = "VideoPlayer/StaggeredAdapter";
private ArrayList<VideoInfo> mItems;
private AdapterView.OnItemClickListener mOnItemClickListener;
private AdapterView.OnItemLongClickListener mOnItemLongClickListener;
private OnStaggeredAdapterListener mOnStaggeredAdapterInformation;
private Context mContext;
private int mThumbnailParentWidth;
private Bitmap mDefaultThumbnailBitmap;
public StaggeredAdapter(Context context, int thumbnailParentWidth,
OnStaggeredAdapterListener onStaggeredAdapterInformation) {
mContext = context;
mThumbnailParentWidth = thumbnailParentWidth;
mOnStaggeredAdapterInformation = onStaggeredAdapterInformation;
mItems = new ArrayList<VideoInfo>();
mDefaultThumbnailBitmap = scaleBitmap(
BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.thumbnail_default),
mThumbnailParentWidth,
mThumbnailParentWidth);
generateItems();
}
private static boolean cancelPotionalWork(int videoId, ImageView imageView) {
final ThumbnailBitmapWorkTask thumbnailBitmapWorkTask = getThumbnailBitmapWorkTask(imageView);
if (thumbnailBitmapWorkTask != null) {
final int thumnailVideoId = thumbnailBitmapWorkTask.videoId;
if (videoId != thumnailVideoId) {
thumbnailBitmapWorkTask.cancel(true);
} else {
return false;
}
}
return true;
}
private static ThumbnailBitmapWorkTask getThumbnailBitmapWorkTask(ImageView imageView) {
if (imageView != null) {
final Drawable drawable = imageView.getDrawable();
if (drawable instanceof AsyncDrawable) {
final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
return asyncDrawable.getThumbnailBitmapWorkTask();
}
}
return null;
}
public void removeItem(int position) {
if (position >= mItems.size())
return;
mItems.remove(position);
notifyItemRemoved(position);
}
public VideoInfo getVideoItemAtPosition(int position) {
return mItems.get(position);
}
@Override
public VerticalItemHolder onCreateViewHolder(ViewGroup container, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(container.getContext());
View root = layoutInflater.inflate(R.layout.item_staggredview, container, false);
return new VerticalItemHolder(root, this);
}
@Override
public int getItemCount() {
return mItems.size();
}
@Override
public void onBindViewHolder(VerticalItemHolder itemHolder, int position) {
final View thumbnailView = itemHolder.videoThumbnail;
if (position % 4 == 0) {
thumbnailView.setMinimumHeight(300);
} else {
thumbnailView.setMinimumHeight(100);
}
VideoInfo item = mItems.get(position);
itemHolder.setVideoTitle(item.getFileName());
itemHolder.setVideoSize(item.getVideoSize() + "");
itemHolder.setVideoDuration(item.getDuration());
itemHolder.setVideoProgress(item.getVideoProgress());
loadThumbnailBitmap(item.getVideoId(),
item.getDuration(),
item.getVideoProgress(),
item.getVideoPath(),
itemHolder.getVideoThumbnail());
}
private void onItemHolderClick(VerticalItemHolder itemHolder) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(null, itemHolder.itemView,
itemHolder.getAdapterPosition(),
mItems.get(itemHolder.getAdapterPosition()).getVideoId());
}
}
public void setOnItemClickListener(AdapterView.OnItemClickListener listener) {
mOnItemClickListener = listener;
}
private void onItemHolderLongClick(VerticalItemHolder itemHolder) {
if (mOnItemLongClickListener != null) {
mOnItemLongClickListener.onItemLongClick(null, itemHolder.itemView,
itemHolder.getAdapterPosition(),
mItems.get(itemHolder.getAdapterPosition()).getVideoId());
}
}
public void setOnItemLongClickListener(AdapterView.OnItemLongClickListener listener) {
mOnItemLongClickListener = listener;
}
private void generateItems() {
String[] videoColumns = {
MediaStore.Video.Media._ID,
MediaStore.Video.Media.DATA,
MediaStore.Video.Media.TITLE,
MediaStore.Video.Media.SIZE,
MediaStore.Video.Media.DURATION,
};
Cursor cursor = mContext.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoColumns,
null, null, null);
int totalCount = cursor.getCount();
// no video, then show the no video hint
if (totalCount <= 0) {
mOnStaggeredAdapterInformation.onStaggeredAdapterInformation();
}
cursor.moveToFirst();
for (int i = 0; i < totalCount; i++) {
int videoId = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
String videoPath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
long videoDuration = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));
String videoTitle = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
int videoSize = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
VideoInfo item = new VideoInfo(videoId, videoPath, videoTitle, videoSize, videoDuration);
mItems.add(item);
cursor.moveToNext();
}
cursor.close();
}
private Bitmap scaleBitmap(Bitmap originalBitmap, int toWidth, int toHeight) {
float scaleWidth = ((float) toWidth) / originalBitmap.getWidth();
float scaleHeight = ((float) toHeight) / originalBitmap.getHeight();
// float scale = 0;
// if (scaleWidth < scaleHeight) {
// scale = scaleWidth;
// } else {
// scale = scaleHeight;
// }
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
return Bitmap.createBitmap(originalBitmap, 0, 0, originalBitmap.getWidth(),
originalBitmap.getHeight(), matrix, true);
}
private void loadThumbnailBitmap(int videoId, long videoDuration, long videoProgress, String videoPath,
ImageView thumbnailView) {
if (cancelPotionalWork(videoId, thumbnailView)) {
final ThumbnailBitmapWorkTask task = new ThumbnailBitmapWorkTask(videoId, videoDuration, videoProgress,
videoPath, thumbnailView);
final AsyncDrawable asyncDrawable = new AsyncDrawable(mContext.getResources(),
mDefaultThumbnailBitmap, task);
thumbnailView.setImageDrawable(asyncDrawable);
task.execute(videoId);
}
}
public interface OnStaggeredAdapterListener {
void onStaggeredAdapterInformation();
}
public static class VerticalItemHolder extends RecyclerView.ViewHolder
implements View.OnClickListener, View.OnLongClickListener {
private LinearLayout videoTitleLayout;
private LinearLayout videoSizeLayout;
private LinearLayout videoDurationLayout;
private LinearLayout videoProgressLayout;
private ImageView videoThumbnail;
private StaggeredAdapter mAdapter;
public VerticalItemHolder(View v,
StaggeredAdapter adapter) {
super(v);
v.setOnClickListener(this);
v.setOnLongClickListener(this);
mAdapter = adapter;
videoThumbnail = (ImageView) v.findViewById(R.id.item_staggredview_thumbnail);
videoTitleLayout = (LinearLayout) v.findViewById(R.id.item_video_title);
videoSizeLayout = (LinearLayout) v.findViewById(R.id.item_video_size);
videoDurationLayout = (LinearLayout) v.findViewById(R.id.item_video_duration);
videoProgressLayout = (LinearLayout) v.findViewById(R.id.item_video_progess);
}
@Override
public void onClick(View v) {
mAdapter.onItemHolderClick(this);
}
@Override
public boolean onLongClick(View v) {
mAdapter.onItemHolderLongClick(this);
return true;
}
public void setVideoThumbnail(Drawable videoThumbnail) {
this.videoThumbnail.setImageDrawable(videoThumbnail);
}
public ImageView getVideoThumbnail() {
return this.videoThumbnail;
}
public void setVideoThumbnail(Bitmap thumbnailBitmap) {
this.videoThumbnail.setImageBitmap(thumbnailBitmap);
}
public void setVideoTitle(String videoTitle) {
TextView videoItemName = (TextView) this.videoTitleLayout.findViewById(R.id.video_item_name);
TextView videoItemDeatail = (TextView) this.videoTitleLayout.findViewById(R.id.video_item_detail);
videoItemName.setText(R.string.video_title_name);
videoItemDeatail.setText(videoTitle);
}
public void setVideoSize(String videoSize) {
TextView videoItemName = (TextView) this.videoSizeLayout.findViewById(R.id.video_item_name);
TextView videoItemDeatail = (TextView) this.videoSizeLayout.findViewById(R.id.video_item_detail);
videoItemName.setText(R.string.video_size_name);
videoItemDeatail.setText(videoSize);
}
public void setVideoDuration(long videoDuration) {
TextView videoItemName = (TextView) this.videoDurationLayout.findViewById(R.id.video_item_name);
TextView videoItemDeatail = (TextView) this.videoDurationLayout.findViewById(R.id.video_item_detail);
videoItemName.setText(R.string.video_duration_name);
videoItemDeatail.setText(Long.toString(videoDuration));
}
public void setVideoProgress(long videoProgress) {
TextView videoItemName = (TextView) this.videoProgressLayout.findViewById(R.id.video_item_name);
TextView videoItemDeatail = (TextView) this.videoProgressLayout.findViewById(R.id.video_item_detail);
videoItemName.setText(R.string.video_progress_name);
videoItemDeatail.setText(Long.toString(videoProgress));
}
}
static class AsyncDrawable extends BitmapDrawable {
private final WeakReference<ThumbnailBitmapWorkTask> thumbnailBitmapWorkTaskWeakReference;
public AsyncDrawable(Resources res, Bitmap bitmap,
ThumbnailBitmapWorkTask thumbnailBitmapWorkTask) {
super(res, bitmap);
thumbnailBitmapWorkTaskWeakReference = new WeakReference<ThumbnailBitmapWorkTask>(thumbnailBitmapWorkTask);
}
public ThumbnailBitmapWorkTask getThumbnailBitmapWorkTask() {
return thumbnailBitmapWorkTaskWeakReference.get();
}
}
class ThumbnailBitmapWorkTask extends AsyncTask<Integer, Void, Bitmap> {
private final WeakReference<ImageView> imageViewWeakReference;
private int videoId;
private long videoDuration;
private long videoProgress;
private String videoPath;
public ThumbnailBitmapWorkTask(int videoId, long videoDuration, long videoProgress, String videoPath,
ImageView imageView) {
imageViewWeakReference = new WeakReference<ImageView>(imageView);
this.videoId = videoId;
this.videoDuration = videoDuration;
this.videoProgress = videoDuration / 2;
this.videoPath = videoPath;
}
@Override
protected Bitmap doInBackground(Integer... params) {
Bitmap bitmap = null;
File thumbnailParent = new File(mContext.getExternalCacheDir(), "/list_thumbnail");
if (!thumbnailParent.exists()) {
thumbnailParent.mkdir();
}
String videoThumbnailPathName = mContext.getExternalCacheDir() + "/list_thumbnail/" + videoId + "_" +
videoProgress;
File file = new File(videoThumbnailPathName);
if (file.exists()) {
bitmap = BitmapFactory.decodeFile(videoThumbnailPathName);
} else {
bitmap = createVideoThumbnail(videoId, videoProgress);
saveVideoThumbnail(bitmap, videoThumbnailPathName);
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewWeakReference != null && bitmap != null) {
final ImageView imageView = imageViewWeakReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
/**
* @param videoId
* @param videoProgress
* @return
*/
private Bitmap createVideoThumbnail(int videoId, long videoProgress) {
MediaMetadataRetriever mediaMetadataRetriever = null;
Bitmap srcBitmap = null;
try {
mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(mContext,
ContentUris.withAppendedId(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, videoId));
srcBitmap = mediaMetadataRetriever.getFrameAtTime(videoProgress * 1000,
MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
} catch (Exception e) {
} finally {
if (mediaMetadataRetriever != null) {
mediaMetadataRetriever.release();
}
}
if (srcBitmap == null) {
srcBitmap = MediaStore.Video.Thumbnails.getThumbnail(mContext.getContentResolver(), videoId,
MediaStore.Video.Thumbnails.MINI_KIND, null);
if (srcBitmap == null) {
srcBitmap = MediaStore.Video.Thumbnails.getThumbnail(mContext.getContentResolver(), videoId,
MediaStore.Video.Thumbnails.MICRO_KIND, null);
}
}
return scaleBitmap(srcBitmap, mThumbnailParentWidth, mThumbnailParentWidth);
}
private void saveVideoThumbnail(Bitmap bitmap, String thumbnailPath) {
try {
File thumbnailFile = new File(thumbnailPath);
FileOutputStream fileOutputStream = new FileOutputStream(thumbnailFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
}
}
}
}
|
package com.developpez.lmauzaize.java.concurrence.ch02_synchronisation.phaser;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.Phaser;
import com.developpez.lmauzaize.java.concurrence.Logger;
public class PhaserDemo {
public static void main(String[] args) throws InterruptedException,BrokenBarrierException {
//////////////////////////////////////////
Phaser phaser = new Phaser() {
{
println("<init>");
}
private void println(String action) {
Logger.println("{%-10s} phase=%02d registred=%02d arrived=%02d unarrived=%02d", action, getPhase(), getRegisteredParties(), getArrivedParties(), getUnarrivedParties());
}
@Override
public int register() {
int register = super.register();
println("register");
return register;
}
@Override
public int arrive() {
int arrive = super.arrive();
println("arrive");
return arrive;
}
protected boolean onAdvance(int phase, int registeredParties) {
Logger.println("{%-10s} phase=%02d registred=%02d", "onAdvance", phase, registeredParties);
return super.onAdvance(phase, registeredParties);
}
};
phaser.register();
phaser.register();
phaser.arrive();
phaser.arrive();
//////////////////////////////////////////
}
}
|
package example.payroll;
import example.money.Money;
import java.time.LocalDate;
public class Employment {
public boolean isActiveOn(LocalDate date) {
return false;
}
public boolean isEmployedBy(Employer employer) {
return false;
}
public Money getAnnualSalary() {
return null;
}
}
|
/*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.buildServer.staticUIExtensions.config;
import com.intellij.openapi.diagnostic.Logger;
import jetbrains.buildServer.serverSide.impl.persisting.SettingsPersister;
import jetbrains.buildServer.staticUIExtensions.PagePlacesCollector;
import jetbrains.buildServer.util.FileUtil;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
/**
* @author Eugene Petrenko (eugene.petrenko@gmail.com)
* Date: 17.11.11 14:11
*/
public class DefaultFilesInitializer {
private static final Logger LOG = Logger.getInstance(DefaultFilesInitializer.class.getName());
private final PagePlacesCollector myCollector;
private final ConfigurationImpl myConfig;
private final SettingsPersister mySettingsPersister;
public DefaultFilesInitializer(@NotNull final ConfigurationImpl config,
@NotNull final PagePlacesCollector collector,
@NotNull final SettingsPersister settingsPersister) {
myConfig = config;
myCollector = collector;
mySettingsPersister = settingsPersister;
}
public void writeInitialFiles() {
writeDistConfig();
}
private void writeDistConfig() {
final File config = myConfig.getConfigurationXml();
final File distConfig = new File(myConfig.getConfigurationXml() + ".dist");
final boolean defaultConfig = isDefaultConfig(config);
writeDistConfig(distConfig);
if (defaultConfig) {
// if main config is the same as default, then it was not changed and we can update
// all the configs from the resources
writeDistConfig(config);
for (String name : Collections.singletonList("beforeContent.html")) {
final File file = new File(myConfig.getIncludeFilesBase(), name);
if (!file.isFile()) {
saveResourceToFile("/" + name, file);
}
}
}
}
private void writeDistConfig(@NotNull File targetFile) {
try {
String configText = FileUtil.readResourceAsString(getClass(), "/static-ui-extensions.xml", StandardCharsets.UTF_8);
if (configText == null) return;
configText = configText.replaceAll("@@@PAGE_PLACES_LIST@@@", generatePagePlaces());
mySettingsPersister.scheduleSaveFile("Updating static-ui-extensions.xml.dist", targetFile, configText.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
LOG.warnAndDebugDetails("Failed to write " + targetFile, e);
}
}
private void saveResourceToFile(@NotNull String resourcePath, @NotNull File targetFile) {
try {
String configText = FileUtil.readResourceAsString(getClass(), resourcePath, StandardCharsets.UTF_8);
if (configText == null) return;
mySettingsPersister.scheduleSaveFile("Writing the " + targetFile.getName(), targetFile, configText.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
LOG.warnAndDebugDetails("Failed to write " + targetFile, e);
}
}
private boolean isDefaultConfig(@NotNull File config) {
if (!config.exists()) return true;
try {
return FileUtil.readText(config).equals(FileUtil.readText(new File(config.getPath() + ".dist")));
} catch(IOException e) {
return false;
}
}
@NotNull
private String generatePagePlaces() {
StringBuilder sb = new StringBuilder();
final String newLine = System.getProperty("line.separator", "\r\n");
final String gap = " - ";
sb.append(newLine);
sb.append(" Supported values for place-id are: ").append(newLine);
for (String placeId : myCollector.getPlaceIds().keySet()) {
sb.append(gap);
sb.append(placeId);
sb.append(newLine);
}
return sb.toString();
}
}
|
package String;
public class LongestCommonPrefix_14 {
/*14. 最长公共前缀*/
/*
水平扫描字符串数组中每一个字符串的前缀;
其他思路:二分查找法去寻找最长前缀;
分治法将数组中字符串分别求最长前缀;
*/
public String longestCommonPrefix(String[] strs) {
if(strs.length == 0 || strs[0].length() == 0){
return "";
}
int index = -1;
boolean flag = true;
while(flag){
index++;
if(index >= strs[0].length()){
break;
}
char c = strs[0].charAt(index);
for(int i = 1; i < strs.length; i++){
if(index >= strs[i].length() || c != strs[i].charAt(index)){
flag = false;
break;
}
}
}
return strs[0].substring(0,index);
}
}
|
package walking_web.repositories;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import walking_web.models.Customer;
public interface CustomerRepository extends JpaRepository<Customer, Long>{
List<Customer> findByUsername(String username);
}
|
package gov.virginia.dmas.dto;
import java.io.Serializable;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import gov.virginia.dmas.serializer.DateDeserializer;
import gov.virginia.dmas.serializer.DateSerializer;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter @Setter @ToString
@JsonIgnoreProperties(ignoreUnknown=true)
public class ReportProblemResponseDto implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String category;
private String categoryOther;
private String relationship;
private String relationshipOther;
private String memFirstname;
private String memLastname;
private String memPhone;
private String memEmail;
private Date memDOB;
private String memMedID;
private String memSSN;
private String memAddr1;
private String memAddr2;
private String memCity;
private String memState;
private String memZipcode;
private String description;
@JsonSerialize(using = DateSerializer.class)
public Date getMemDOB() {
return memDOB;
}
@JsonDeserialize(using = DateDeserializer.class)
public void setMemDOB(Date memDOB) {
this.memDOB = memDOB;
}
}
|
package steps;
import lombok.extern.log4j.Log4j2;
import pages.FeedPage;
import pages.LoginPage;
import pages.MoodModal;
import pages.MyFeedPage;
//import static com.codeborne.selenide.Selenide.sleep;
@Log4j2
public class MoodSteps {
LoginPage loginPage;
FeedPage feedPage;
MoodModal moodModal;
MyFeedPage myFeedPage;
public MoodSteps(){
loginPage = new LoginPage();
feedPage = new FeedPage();
myFeedPage = new MyFeedPage();
moodModal = new MoodModal();
}
public MoodSteps login(String user, String password){
loginPage.openPage();
loginPage.login(user, password);
log.info(String.format("Trying to login with email %s and password %s.", user, password));
feedPage.isPageOpen();
return this;
}
public MoodSteps updateMood(int moodRating, String description, String date){
feedPage.clickUpdate();
moodModal.isPageOpen();
moodModal.updateDetails(moodRating, description, date);
moodModal.clickUpdateMood();
moodModal.toDiary();
log.info("Diary page was opened.");
return this;
}
public MoodSteps removeMyMood(int index){
myFeedPage
.openPage()
.isPageOpen()
.removeMyMood(index);
return this;
}
public MoodSteps addReplyForMyFeed(int index, String text){
myFeedPage
.openPage()
.isPageOpen()
.addReply(index, text);
return this;
}
public MoodSteps addReplyForWorldFeed(int index, String text){
feedPage.addReply(index, text);
return this;
}
}
|
package com.question.model;
public class Selections {
private int selectionId;
private int questionId;
private String selectionsContent;
private int count;
public int getSelectionId() {
return selectionId;
}
public void setSelectionId(int selectionId) {
this.selectionId = selectionId;
}
public int getQuestionId() {
return questionId;
}
public void setQuestionId(int questionId) {
this.questionId = questionId;
}
public String getSelectionsContent() {
return selectionsContent;
}
public void setSelectionsContent(String selectionsContent) {
this.selectionsContent = selectionsContent;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
@Override
public String toString() {
return "Selections{" +
"selectionId=" + selectionId +
", questionId=" + questionId +
", selectionsContent='" + selectionsContent + '\'' +
", count=" + count +
'}';
}
}
|
package com.one.sugarcane.io.ride.sensitive;
import java.io.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* 敏感词汇过滤工具
*/
public class SensitiveWordFilter {
private static HashMap sensitiveWordMap = null;
private InputStream in = null;
public static int MinMatchType = 1; // 最小匹配
public static int MaxMatchType = 2; // 最大匹配
/**
* 读入默认的敏感词汇库
*/
public SensitiveWordFilter() {
this.in = SensitiveWordFilter.class.getClassLoader().getResourceAsStream("resource/key.txt");
System.out.println();
init();
}
/**
* 读入制定的敏感词汇库
*
* @param keyWordFile 路径为相对路径
*/
public SensitiveWordFilter(String keyWordFile) {
try {
this.in = new FileInputStream(keyWordFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
init();
}
/**
* 初始化
*/
private void init() {
Set<String> keyWords = readSensitiveWords();
sensitiveWordMap = new HashMap<>(keyWords.size());
for (String keyword : keyWords) {
createKeyWord(keyword);
}
}
/**
* 去读敏感词汇文件
*
* @return 敏感词汇的set
*/
private Set<String> readSensitiveWords() {
Set<String> keyWords = new HashSet<>();
BufferedReader reader = null;
try {
// FileInputStream fin = new FileInputStream("resource/key.txt");
reader = new BufferedReader(new InputStreamReader(this.in));
String line;
while ((line = reader.readLine()) != null) {
keyWords.add(line.trim());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return keyWords;
}
/**
* 根据敏感词汇创建敏感词汇树
*
* @param keyWord 敏感词汇树
*/
private void createKeyWord(String keyWord) {
if (sensitiveWordMap == null) {
System.out.println("sensitiveWordMap 未创建");
return;
}
Map nowMap = sensitiveWordMap;
for (Character c : keyWord.toCharArray()) {
Object obj = nowMap.get(c);
// 不存在的
if (obj == null) {
Map<String, Object> childMap = new HashMap<>();
childMap.put("isEnd", "false");
nowMap.put(c, childMap);
nowMap = childMap;
} else {
nowMap = (Map) obj;
}
}
nowMap.put("isEnd", "true");
}
/**
* 检查是否有敏感词汇
*
* @param txt 等待检查的字符串
* @param beginIndex 开始的位置
* @param matchType 匹配模式
* @return 如果找到就返回敏感词的长度, 没有找到返回0
*/
public int checkSensitiveWord(String txt, int beginIndex, int matchType) {
boolean flag = false; // 用于敏感词只有一个字的情况
int matchFlag = 0;
char word;
Map nowMap = sensitiveWordMap;
for (int i = beginIndex; i < txt.length(); i++) {
word = txt.charAt(i);
nowMap = (Map) nowMap.get(word);
// 存在
if (nowMap != null) {
matchFlag++; // 长度加1
if ("true".equals(nowMap.get("isEnd"))) {
flag = true; //结束标志设置为true
// 最小匹配模式, 直接退出
if (MinMatchType == matchType) {
break;
}
}
} else {
// 不存在 直接返回
break;
}
}
if (matchFlag < 2 || !flag) {
matchFlag = 0;
}
return matchFlag;
}
/**
* 判断字符串是否含有敏感词汇
*
* @param txt 字符串
* @param matchType 匹配模式
* @return 包含敏感词汇返回true, 不包含返回false
*/
public boolean isContainSensitiveWord(String txt, int matchType) {
for (int i = 0; i < txt.length(); i++) {
if (checkSensitiveWord(txt, i, matchType) > 0) {
return true;
}
}
return false;
}
/**
* 找出所有敏感词汇
*
* @param txt 文本
* @param matchType 匹配模式
* @return 包含敏感词汇的HashSet
*/
public Set<String> getSensitiveWord(String txt, int matchType) {
Set<String> sensitiveWords = new HashSet<>();
for (int i = 0; i < txt.length(); i++) {
int len = checkSensitiveWord(txt, i, matchType);
if (len > 0) {
sensitiveWords.add(txt.substring(i, i + len));
i = i + len - 1; // for循环自增, 所以减1
}
}
return sensitiveWords;
}
/**
* 返回替代的字符, 使用默认替换字符"*"
*
* @param len 需要替换的字符串的长度
* @return 长度为n的替换字符串
*/
private String getReplaceChars(int len) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < len; i++) {
sb.append("*");
}
return sb.toString();
}
/**
* 使用指定的字符来代替敏感词汇
*
* @param replaceChar 代替的字符
* @param len 需要代替的长度
* @return 长度为n的替换字符串
*/
private String getReplaceChars(char replaceChar, int len) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < len; i++) {
sb.append(replaceChar);
}
return sb.toString();
}
/**
* 将文本中的敏感词汇替换成"*"
*
* @param txt 要替换的文本
* @param matchType 匹配模式
* @return 替换后的结果
*/
public String replaceSensitiveWords(String txt, int matchType) {
String replace = txt;
Set<String> sensitiveWords = getSensitiveWord(txt, matchType);
for (String word : sensitiveWords) {
String replaceString = getReplaceChars(word.length());
replace = replace.replaceAll(word, replaceString);
}
return replace;
}
/**
* 将文本中的敏感词汇替换成指定的字符
*
* @param txt 要替换的文本
* @param replaceChars 替换的字符
* @param matchType 匹配模式
* @return 替换后的结果
*/
public String replaceSensitiveWords(String txt, char replaceChars, int matchType) {
String replace = txt;
Set<String> sensitiveWords = getSensitiveWord(txt, matchType);
for (String word : sensitiveWords) {
String replaceString = getReplaceChars(replaceChars, word.length());
replace = replace.replaceAll(word, replaceString);
}
return replace;
}
/**
* 递归打印敏感词树, 测试用
*
* @param map 敏感词树
* @param len 控制缩进
*/
private void print(Map map, int len) {
for (Object key : map.keySet()) {
boolean flag = false;
for (int i = 0; i < len; i++) {
System.out.print("\t");
}
if (key == "isEnd") {
System.out.println(key + " = " + map.get(key));
flag = true;
} else {
System.out.println(key + " = {");
}
if (map.get(key) instanceof Map) {
print((Map) map.get(key), len + 1);
}
if (!flag) {
for (int i = 0; i < len; i++) {
System.out.print("\t");
}
System.out.println("}");
}
}
}
public static void main(String[] args) {
SensitiveWordFilter filter = new SensitiveWordFilter();
String res = filter.replaceSensitiveWords("草你妈呢草你妈,撒的报复", MaxMatchType);
System.out.println(res);
}
}
|
package controllers;
import dto.MovieDTO;
import dto.SeanceDTO;
import model.Movie;
import service.impl.MovieServiceImpl;
import service.impl.SeanceServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@WebServlet(name = "MovieManagerServlet", urlPatterns={"/admin/moviemanager"})
public class MovieManagerServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<SeanceDTO> seanceDTOList= SeanceServiceImpl.getInstance().getAll();
List<MovieDTO> movieDTOList= MovieServiceImpl.getInstance().getAll();
List<SeanceDTO> selectedSeances=new ArrayList<>();
List<MovieDTO> selectedMovies=new ArrayList<>();
List<MovieDTO> restMovies=new ArrayList<>();
Set<Date> dateSet=new TreeSet<>();
Set<Integer> movieIdSet=new TreeSet<>();
Calendar c= Calendar.getInstance();
Calendar c1=Calendar.getInstance();
Pattern pattern;
Matcher matcher;
String str;
int year_s=0, month_s=0, day_s=0;
for (SeanceDTO sd : seanceDTOList)
{ str=sd.getSeanceDate().toString();
pattern = Pattern.compile("(\\d+)(-)(\\d+)(-)(\\d+)");
matcher = pattern.matcher(str);
if (matcher.find()) {
matcher = pattern.matcher(str);
while (matcher.find()) {
year_s = Integer.parseInt(matcher.group(1));
}
matcher = pattern.matcher(str);
while (matcher.find()) {
month_s = Integer.parseInt(matcher.group(3));
}
matcher = pattern.matcher(str);
while (matcher.find()) {
day_s = Integer.parseInt(matcher.group(5));
}}
c1.set(year_s, (month_s-1), day_s);
if(c.before(c1)) {
dateSet.add(sd.getSeanceDate());
selectedSeances.add(sd);
movieIdSet.add(sd.getMovie().getId());
}
if(c.equals(c1)) {
dateSet.add(sd.getSeanceDate());
selectedSeances.add(sd);
movieIdSet.add(sd.getMovie().getId());
}
}
List<Integer> movieIdList=new ArrayList<>(movieIdSet);
boolean f=false;
for(MovieDTO m: movieDTOList)
{ f=false;
{for (Integer id : movieIdList)
{if(m.getId().equals(id)) {
selectedMovies.add(m);
f=true;
break;
}
}if(f==false){
restMovies.add(m);
}}
}
List<Date> selectedDates=new ArrayList<>(dateSet);
request.setAttribute("selectedDates", selectedDates);
request.setAttribute("selectedSeances", selectedSeances);
request.setAttribute("selectedMovies", selectedMovies);
request.setAttribute("restMovies", restMovies);
request.getRequestDispatcher("/admin/manager.jsp").forward(request,response);
// response.sendRedirect(request.getContextPath() + "/admin/manager.jsp");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
|
package com.isystk.sample.domain.entity;
import org.seasar.doma.Column;
import org.seasar.doma.Entity;
import org.seasar.doma.Id;
import org.seasar.doma.Table;
import com.isystk.sample.domain.dto.common.DomaDtoImpl;
import lombok.Getter;
import lombok.Setter;
/**
* 自動生成のため原則修正禁止!!
*/
@Entity
@Table(name = "t_post_image")
@Getter
@Setter
public class TPostImage extends DomaDtoImpl {
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1L;
/**
* 投稿ID
*/
@Id
@Column(name = "POST_ID")
Integer postId;
/**
* 画像ID
*/
@Id
@Column(name = "IMAGE_ID")
Integer imageId;
} |
package com.takshine.wxcrm.domain;
import com.takshine.wxcrm.model.AttachmentModel;
/**
* 附件
* @author liulin
*
*/
public class Attachment extends AttachmentModel{
private String parentid;//相关ID
private String parenttype;//相关类别
public String getParentid() {
return parentid;
}
public void setParentid(String parentid) {
this.parentid = parentid;
}
public String getParenttype() {
return parenttype;
}
public void setParenttype(String parenttype) {
this.parenttype = parenttype;
}
}
|
package com.tencent.mm.plugin.sns.storage.AdLandingPagesStorage.AdLandingPageComponent.component.widget;
class b$a {
final /* synthetic */ b nGR;
public boolean nzR;
private b$a(b bVar) {
this.nGR = bVar;
}
/* synthetic */ b$a(b bVar, byte b) {
this(bVar);
}
final void bzO() {
if (this.nzR) {
this.nzR = false;
}
}
}
|
package com.projet3.library_webapp.library_webapp_batch.email;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
import org.springframework.mail.MailSender;
@Service("emailSender")
public class EmailAPI {
@Autowired
private MailSender mailSender;
public void readyToSendEmail(String toAddress, String fromAddress, String subject, String msgBody) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(fromAddress);
message.setTo(toAddress);
message.setSubject(subject);
message.setText(msgBody);
mailSender.send(message);
}
}
|
package com.tmtmmobile.tmtm;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
import com.tmtmmobile.tmtm.DataBaseHelper.DbHelper;
import com.tmtmmobile.tmtm.dto.JSONMessage;
import com.tmtmmobile.tmtm.dto.UserSignUp;
import com.tmtmmobile.tmtm.ipaddress.MyIP;
import com.tmtmmobile.tmtm.remote.TmTmWebServiceInterface;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
public class MoreSignUpDetails extends AppCompatActivity {
private final String SIGNUP = MyIP.ip + "TmTm.webservices/tmtm/TmTmSignUp/";
Button save;
CheckBox read;
CheckBox draw;
CheckBox shop;
CheckBox movie;
ArrayList<String> interests;
UserSignUp user;
SharedPreferences sharedpreferences;
DbHelper dbHelper;
ProgressDialog progressDialog;
Activity activity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_more_sign_up_details);
user = (UserSignUp) getIntent().getSerializableExtra("userObj");
save = (Button) findViewById(R.id.save);
read = (CheckBox) findViewById(R.id.chkReading);
draw = (CheckBox) findViewById(R.id.chkDrawing);
movie = (CheckBox) findViewById(R.id.chkMovies);
shop = (CheckBox) findViewById(R.id.chkShopping);
activity = this;
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
progressDialog = ProgressDialog.show(activity, "Loading", "Please wait...", true);
interests = new ArrayList<>();
if (read.isChecked()) {
interests.add("Reading");
}
if (draw.isChecked()) {
interests.add("Drawing");
}
if (movie.isChecked()) {
interests.add("Cinema");
}
if (shop.isChecked()) {
interests.add("Shopping");
}
user.setInterests(interests);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SIGNUP)
.addConverterFactory(JacksonConverterFactory.create())
.build();
TmTmWebServiceInterface getAPI = retrofit.create(TmTmWebServiceInterface.class);
Call<JSONMessage> call = getAPI.addTmTmUser(user);
call.enqueue(new Callback<JSONMessage>() {
@Override
public void onResponse(Call<JSONMessage> call, Response<JSONMessage> response) {
if (response.body().getError() == false) {
int id = Integer.parseInt(response.body().getData());
user.setUserId(id);
dbHelper = DbHelper.getInstance(getApplicationContext());
dbHelper.addUser(user);
sharedpreferences = getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean("isLoggedIn", true);
editor.putInt("id", id);
editor.commit();
progressDialog.dismiss();
Intent goToMain = new Intent(MoreSignUpDetails.this, NavigationDrawerActivity.class);
startActivity(goToMain);
} else {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Sorry email already exists", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<JSONMessage> call, Throwable t) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Check your internet connection", Toast.LENGTH_SHORT).show();
t.printStackTrace();
}
});
}
});
}
}
|
package com.accp.pub.mapper;
import java.util.List;
import com.accp.pub.pojo.Awardandpunishmenttype;
public interface AwardandpunishmenttypeMapper {
int deleteByPrimaryKey(Integer aaypeid);
int insert(Awardandpunishmenttype record);
int insertSelective(Awardandpunishmenttype record);
Awardandpunishmenttype selectByPrimaryKey(Integer aaypeid);
int updateByPrimaryKeySelective(Awardandpunishmenttype record);
int updateByPrimaryKey(Awardandpunishmenttype record);
List<Awardandpunishmenttype> selectAwardandpunishmenttypeAll();
} |
package com.socklabs.lazyexamples;
/**
* Created with IntelliJ IDEA.
* User: ngerakines
* Date: 9/9/12
* Time: 12:58 PM
* To change this template use File | Settings | File Templates.
*/
public abstract class LazyData<O, R> {
private volatile boolean executed = false;
private R response = null;
public abstract R responseData(O object);
public R get(O object) {
// NKG: Could probably do a check of executed == false outside of this sync block to quickly return to optimize
// for cases where the method is called more than once or is long-lived.
synchronized (this) {
if (executed == false) {
response = responseData(object);
executed = true;
}
}
return response;
}
}
|
package com.example.cj.perfectj.mapper;
import com.example.cj.perfectj.domain.UserDomain;
import com.example.cj.perfectj.domain.UserDomainExample;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper
public interface UserDomainMapper {
long countByExample(UserDomainExample example);
int deleteByExample(UserDomainExample example);
int deleteByPrimaryKey(Long id);
int insert(UserDomain record);
int insertSelective(UserDomain record);
List<UserDomain> selectByExample(UserDomainExample example);
UserDomain selectByPrimaryKey(Long id);
int updateByExampleSelective(@Param("record") UserDomain record, @Param("example") UserDomainExample example);
int updateByExample(@Param("record") UserDomain record, @Param("example") UserDomainExample example);
int updateByPrimaryKeySelective(UserDomain record);
int updateByPrimaryKey(UserDomain record);
} |
package com.example.sdcardfinder;
import android.app.ListActivity;
import android.os.Bundle;
public class SetLanguageListActivity extends ListActivity{
private int langString;
public int getLangString() {
return langString;
}
private void setLangString() {
String lng=this.getApplicationContext().getResources().getConfiguration().locale.getLanguage();
if(lng.equals("en")){this.langString=1;return;}
if(lng.equals("ru")){this.langString=2;return;}
if(lng.equals("de")){this.langString=3;return;}
if(lng.equals("es")){this.langString=4;return;}
if(lng.equals("uk")){this.langString=5;return;}
}
/**
* returns string "back" on System language.
*/
public String getBackString(){
switch (langString){
case 2:
return "Назад";
case 3:
return "Zurück";
case 4:
return "Espalda";
case 5:
return "Назад";
default:
return "Back";
}
}
/**
* returns string "New folder" on System language.
*/
public String getNewFolderString(){
switch (langString){
case 2:
return "Новая папка";
case 3:
return "neuen ordner";
case 4:
return "nueva carpeta";
case 5:
return "Нова папка";
default:
return "New Folder";
}
}
/**
* returns string "Enter name of new folder" on System language.
*/
public String getNewFolderNameString(){
switch (langString){
case 2:
return "Введите имя новой папки";
case 3:
return "Geben Sie den neuen Ordner";
case 4:
return "Introduzca la nueva carpeta";
case 5:
return "Введіть назву нової папки";
default:
return "Enter name of new folder";
}
}
/**
* returns string "select" on System language.
*/
public String getSelectString(){
switch (langString){
case 2:
return "Выбрать";
case 3:
return "Wählen";
case 4:
return "Seleccionar";
case 5:
return "Вибрати";
default:
return "Select";
}
}
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setLangString();
}
}
|
package com.tencent.mm.plugin.game.ui;
import android.content.Intent;
import android.os.Bundle;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.game.a.b;
import com.tencent.mm.plugin.game.d.aj;
import com.tencent.mm.plugin.game.e.c;
import com.tencent.mm.plugin.game.f;
import com.tencent.mm.plugin.game.model.an;
import com.tencent.mm.plugin.game.model.h;
import com.tencent.mm.plugin.game.model.o;
import com.tencent.mm.plugin.game.model.s;
import com.tencent.mm.plugin.game.model.v;
import com.tencent.mm.plugin.game.ui.tab.GameRouteUI;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.e;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.MMBaseActivity;
import com.tencent.mm.ui.MMFragmentActivity;
import com.tencent.mm.ui.base.a;
@a(19)
public class GameCenterUI extends MMBaseActivity {
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
x.d("MicroMsg.GameCenterUI", "onCreate");
if (getIntent().getBooleanExtra("game_check_float", false)) {
int intExtra = getIntent().getIntExtra("game_sourceScene", 0);
((b) g.l(b.class)).aSi();
s aTZ = v.aTZ();
if (aTZ != null) {
aTZ.aTW();
if (!bi.oW(aTZ.jMI.url)) {
c.a(getBaseContext(), aTZ, "game_center_h5_floatlayer");
}
}
o.a(aTZ, intExtra, 1);
finish();
return;
}
boolean booleanExtra = getIntent().getBooleanExtra("switch_country_no_anim", false);
h aTL = h.aTL();
aj ajVar = null;
if (aTL.jLN != null) {
ajVar = aTL.jLN.jRn;
if (ajVar != null) {
x.i("MicroMsg.GameConfigManager", "getGameIndexSettingControl jumpType:%d, jumpUrl:%s", new Object[]{Integer.valueOf(ajVar.jQq), ajVar.jOU});
}
} else {
aTL.Zy();
}
if (ajVar != null) {
Intent intent;
Bundle extras;
switch (ajVar.jQq) {
case 0:
fz(booleanExtra);
break;
case 1:
if (!bi.oW(ajVar.jOU)) {
DM(ajVar.jOU);
break;
} else {
fz(booleanExtra);
break;
}
case 2:
intent = new Intent(this, GameOverSeaCenterUI.class);
extras = getIntent().getExtras();
if (extras != null) {
intent.putExtras(extras);
}
startActivity(intent);
if (booleanExtra) {
overridePendingTransition(f.a.in_no_slide, f.a.in_no_slide);
} else {
overridePendingTransition(MMFragmentActivity.a.tnC, MMFragmentActivity.a.tnD);
}
qU(6);
com.tencent.mm.plugin.report.service.h.mEJ.a(848, 5, 1, false);
break;
case 3:
intent = new Intent(this, GameDownloadGuidanceUI.class);
extras = getIntent().getExtras();
if (extras != null) {
intent.putExtras(extras);
}
startActivity(intent);
if (booleanExtra) {
overridePendingTransition(f.a.in_no_slide, f.a.in_no_slide);
} else {
overridePendingTransition(MMFragmentActivity.a.tnC, MMFragmentActivity.a.tnD);
}
qU(6);
com.tencent.mm.plugin.report.service.h.mEJ.a(848, 6, 1, false);
break;
}
}
fz(booleanExtra);
finish();
}
private void fz(boolean z) {
if (e.chv()) {
x.i("MicroMsg.GameCenterUI", "GP version");
} else {
com.tencent.mm.plugin.game.model.b.a qQ = com.tencent.mm.plugin.game.model.b.qQ(getIntent().getIntExtra("game_report_from_scene", 0));
if (qQ.bWA == 2 && !bi.oW(qQ.url)) {
DM(qQ.url);
return;
}
}
Intent intent = new Intent(this, GameRouteUI.class);
Bundle extras = getIntent().getExtras();
if (extras != null) {
intent.putExtras(extras);
}
startActivity(intent);
if (z) {
overridePendingTransition(f.a.in_no_slide, f.a.in_no_slide);
} else {
overridePendingTransition(MMFragmentActivity.a.tnC, MMFragmentActivity.a.tnD);
}
qU(6);
com.tencent.mm.plugin.report.service.h.mEJ.a(848, 4, 1, false);
}
private void DM(String str) {
qU(7);
Intent intent = getIntent();
if (!(this == null || bi.oW(str) || intent == null)) {
boolean booleanExtra = intent.getBooleanExtra("from_find_more_friend", false);
int intExtra = intent.getIntExtra("game_report_from_scene", 0);
((b) g.l(b.class)).aSi();
s aTZ = v.aTZ();
String a = o.a(str, aTZ);
if (booleanExtra) {
o.a(this, a, "game_center_entrance", true, aTZ, intExtra);
((b) g.l(b.class)).aSi();
v.aTY();
} else {
o.a(this, a, "game_center_entrance", false, aTZ, intExtra);
}
finish();
}
com.tencent.mm.plugin.report.service.h.mEJ.a(848, 3, 1, false);
}
private void qU(int i) {
if (getIntent().getBooleanExtra("from_find_more_friend", false)) {
((b) g.l(b.class)).aSi();
s aTX = v.aTX();
if (aTX == null) {
an.a(this, 9, 901, 1, i, 0, an.da("resource", "0"));
return;
}
aTX.aTW();
int i2 = aTX.field_msgType;
if (aTX.field_msgType == 100) {
i2 = aTX.jNa;
}
an.a(this, 9, 901, 1, i, 0, aTX.field_appId, 0, i2, aTX.field_gameMsgId, aTX.jNb, an.da("resource", String.valueOf(aTX.jMt.jNi)));
((b) g.l(b.class)).aSi();
v.aTY();
com.tencent.mm.plugin.report.service.h.mEJ.a(858, 3, 1, false);
}
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
import java.util.Date;
/**
* J4BillsId generated by hbm2java
*/
public class J4BillsId implements java.io.Serializable {
private String uniqueid;
private String billsort;
private String billurl;
private String billversion;
private String iseffect;
private String creator;
private Date createtime;
public J4BillsId() {
}
public J4BillsId(String uniqueid) {
this.uniqueid = uniqueid;
}
public J4BillsId(String uniqueid, String billsort, String billurl, String billversion, String iseffect,
String creator, Date createtime) {
this.uniqueid = uniqueid;
this.billsort = billsort;
this.billurl = billurl;
this.billversion = billversion;
this.iseffect = iseffect;
this.creator = creator;
this.createtime = createtime;
}
public String getUniqueid() {
return this.uniqueid;
}
public void setUniqueid(String uniqueid) {
this.uniqueid = uniqueid;
}
public String getBillsort() {
return this.billsort;
}
public void setBillsort(String billsort) {
this.billsort = billsort;
}
public String getBillurl() {
return this.billurl;
}
public void setBillurl(String billurl) {
this.billurl = billurl;
}
public String getBillversion() {
return this.billversion;
}
public void setBillversion(String billversion) {
this.billversion = billversion;
}
public String getIseffect() {
return this.iseffect;
}
public void setIseffect(String iseffect) {
this.iseffect = iseffect;
}
public String getCreator() {
return this.creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public Date getCreatetime() {
return this.createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof J4BillsId))
return false;
J4BillsId castOther = (J4BillsId) other;
return ((this.getUniqueid() == castOther.getUniqueid()) || (this.getUniqueid() != null
&& castOther.getUniqueid() != null && this.getUniqueid().equals(castOther.getUniqueid())))
&& ((this.getBillsort() == castOther.getBillsort()) || (this.getBillsort() != null
&& castOther.getBillsort() != null && this.getBillsort().equals(castOther.getBillsort())))
&& ((this.getBillurl() == castOther.getBillurl()) || (this.getBillurl() != null
&& castOther.getBillurl() != null && this.getBillurl().equals(castOther.getBillurl())))
&& ((this.getBillversion() == castOther.getBillversion())
|| (this.getBillversion() != null && castOther.getBillversion() != null
&& this.getBillversion().equals(castOther.getBillversion())))
&& ((this.getIseffect() == castOther.getIseffect()) || (this.getIseffect() != null
&& castOther.getIseffect() != null && this.getIseffect().equals(castOther.getIseffect())))
&& ((this.getCreator() == castOther.getCreator()) || (this.getCreator() != null
&& castOther.getCreator() != null && this.getCreator().equals(castOther.getCreator())))
&& ((this.getCreatetime() == castOther.getCreatetime())
|| (this.getCreatetime() != null && castOther.getCreatetime() != null
&& this.getCreatetime().equals(castOther.getCreatetime())));
}
public int hashCode() {
int result = 17;
result = 37 * result + (getUniqueid() == null ? 0 : this.getUniqueid().hashCode());
result = 37 * result + (getBillsort() == null ? 0 : this.getBillsort().hashCode());
result = 37 * result + (getBillurl() == null ? 0 : this.getBillurl().hashCode());
result = 37 * result + (getBillversion() == null ? 0 : this.getBillversion().hashCode());
result = 37 * result + (getIseffect() == null ? 0 : this.getIseffect().hashCode());
result = 37 * result + (getCreator() == null ? 0 : this.getCreator().hashCode());
result = 37 * result + (getCreatetime() == null ? 0 : this.getCreatetime().hashCode());
return result;
}
}
|
package com.ryit.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ryit.entity.Building;
import com.ryit.entity.vo.BuildingQueryVo;
import com.ryit.entity.vo.PlotQueryIdPname;
import com.ryit.service.BuildingService;
@Controller
@RequestMapping("pages/admin")
public class BuildingContrller{
@Autowired
private BuildingService buil;
/**
* 增加房屋栋数信息
* @param Building b
* @return
* @throws IOException
*/
@RequestMapping("/saveBuil")
public @ResponseBody Object saveBuil(HttpServletResponse response, HttpServletRequest request, Building b){
Map<String,String> map = new HashMap<String,String>();
String msg="";
if(b!= null){
msg = buil.insertDate(b);
}
if("0".equals(msg)){
map.put("error","添加失败!栋数的信息在添加时不完整,添加无法完成,请重新补充完数据!");
}else if("1".equals(msg)){
map.put("success","添加成功");
}else if("2".equals(msg)){
map.put("error","添加失败,在此小区中此栋数已存在!");
}else{
map.put("error","用户登录有效期已过,无法操作增加功能,请返回到登录页面,重新登陆!");
}
return map;
}
/**
*通过指定栋数的编号来删除指定的栋数
*@param int id
*@return
*/
@RequestMapping("/delBuil")
public @ResponseBody Object delete(HttpServletRequest request,HttpServletResponse response,Integer id){
String msg="";
if(id != 0){
msg = buil.delete(id);
}
return msg;
}
@RequestMapping("/selectBuil")
public @ResponseBody Object select(HttpServletRequest request, HttpServletResponse response, Building bu){
if(bu.getBuildingNo() == null){
List<BuildingQueryVo> list = buil.selectAll();
return list;
}else{
return buil.findBuilNo(bu);
}
}
@RequestMapping("/findBIdBname")
public @ResponseBody Object findBIdBname(HttpServletRequest request, HttpServletResponse response,Integer pid){
return buil.findBIdAndBname(pid);
}
/**
* 查询小区名称和小区编号,查询使用
* @return
*/
@RequestMapping("/selectPname")
public @ResponseBody Object selectPname(){
List<PlotQueryIdPname> list = buil.findPlotName();
return list;
}
/**
* 获得所有小区名称
* @return
*/
@RequestMapping("/findPname")
public @ResponseBody Object findPname(){
return buil.findPlotName();
}
/**
* 修改,指定修改
* @param request
* @param response
* @param bu
* @return
*/
@RequestMapping("/updateBuil")
public @ResponseBody Object update(HttpServletRequest request,HttpServletResponse response,Building bu){
Map<String,String> map = new HashMap<String,String>();
String msg="";
if(bu != null){
msg = buil.update(bu);
}
if("0".equals(msg)){
map.put("error","修改失败!栋数的信息在修改时不完整,修改无法完成,请重新补充完数据!");
}else if("1".equals(msg)){
map.put("success","修改成功!");
}else if("2".equals(msg)){
map.put("error","修改失败!,在此小区中此栋数已存在!");
}else{
map.put("error","用户登录有效期已过,无法操作增加功能,请返回到登录页面,重新登陆!");
}
return map;
}
}
|
package com.sparknetworks.loveos.domain;
public class Range<T extends Comparable<T>> {
private T from;
private T to;
private Range() {}
public static <T extends Comparable<T>> Range<T> of(T from, T to) {
Range<T> range = new Range<>();
range.from = from;
range.to = to;
return range;
}
public boolean isWithinRange(T value) {
return value.compareTo(from) >= 0 && value.compareTo(to) <= 0;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GProduction.auxiliary;
import GProduction.miniCarSim_Alpha2;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
/**
*
* @author Blondu
*/
public class resumeScreen extends Canvas {
miniCarSim_Alpha2 parent;
public resumeScreen(miniCarSim_Alpha2 parent) {
this.parent = parent;
}
protected void paint(Graphics g) {
g.setColor(0);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(0xFFFFFF);
g.drawString("Press any key to resume game.", getWidth() / 2, getHeight() / 2, Graphics.BASELINE | Graphics.VCENTER);
}
protected void keyPressed(int keyCode) {
parent.resume();
}
}
|
package com.briup.apps.zhaopin.service;
import com.briup.apps.zhaopin.bean.CustomerService;
import com.briup.apps.zhaopin.bean.extend.CustomerServiceExtend;
import java.util.List;
public interface CustomerServiceService {
List<CustomerService> findAll();
String saveOrUpdate(CustomerService customerService);
CustomerService findById(Long id);
void deleteById(Long id);
List<CustomerServiceExtend> findByGender(String gender);
List<CustomerServiceExtend> findByStatus(String status);
List<CustomerServiceExtend> findByUsername(String username);
}
|
package com.example.doubnut.di.module;
import android.arch.lifecycle.ViewModel;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import dagger.MapKey;
@Documented
@MapKey
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ViewModelKey {
Class<? extends ViewModel> value();
}
|
package pl.tiwaszko.spitter.data;
import pl.tiwaszko.spitter.Spittle;
import java.util.List;
/**
* Created by root on 29.09.15.
*/
public interface SpittleRepository {
List<Spittle> findSpittles(long max, int count);
}
|
package com.codegym.checkinhotel.service.room;
import com.codegym.checkinhotel.model.Hotel;
import com.codegym.checkinhotel.model.Room;
import com.codegym.checkinhotel.model.RoomDetails;
import com.codegym.checkinhotel.repository.IRoomRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class RoomService implements IRoomService {
@Autowired
private IRoomRepository roomRepository;
@Override
public Iterable<Room> findAll() {
return roomRepository.findAll();
}
@Override
public Optional<Room> findById(Long id) {
return roomRepository.findById(id);
}
@Override
public Room save(Room room) {
return roomRepository.save(room);
}
@Override
public void remove(Long id) {
roomRepository.deleteById(id);
}
@Override
public List<Room> getAllByHotel(Hotel hotel) {
return roomRepository.findAllByHotel(hotel);
}
@Override
public List<Room> getAllByRoomDetails(RoomDetails roomDetails) {
return roomRepository.findAllByRoomDetails(roomDetails);
}
}
|
package com.trendylibaaz.tictactoe;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.ImageButton;
import org.w3c.dom.Attr;
/**
* Created by pranaykx on 5/23/2016.
*/
public class TicTacToeImageButton extends ImageButton {
private int _row, _col;
public enum STATE{
STATE_NONE,
STATE_ZERO,
STATE_CROSS,
};
private STATE cur_state;
public void set_Row(int row) {
this._row = row;
}
public void set_Col(int col) {
this._col = col;
}
public int get_Row () {
return _row;
}
public int get_Col() {
return _col;
}
public void setCurrentState(STATE state)
{
this.cur_state = state;
}
public STATE getCurrentState()
{
return cur_state;
}
public TicTacToeImageButton(Context c) {
super(c);
}
private void getRowAndCols(Context c, AttributeSet attrs)
{
TypedArray attrSet =c.getTheme().obtainStyledAttributes(
attrs,
R.styleable.TicTacToeImageButton,
0, 0);
try {
this._col = attrSet.getInteger(R.styleable.TicTacToeImageButton_col, 0);
this._row = attrSet.getInteger(R.styleable.TicTacToeImageButton_row,0);
}finally {
attrSet.recycle();
}
}
public TicTacToeImageButton(Context c, AttributeSet attrs) {
super(c,attrs);
getRowAndCols(c,attrs);
}
public TicTacToeImageButton(Context c, AttributeSet attrs, int defStyle) {
super(c,attrs,defStyle);
getRowAndCols(c,attrs);
}
public TicTacToeImageButton(Context c, AttributeSet attrs, int defStyle, int defStyleRes) {
super(c,attrs,defStyle,defStyleRes);
getRowAndCols(c,attrs);
}
}
|
package it.dstech.film.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
@SuppressWarnings("serial")
@Entity
@Table(name = "Roles")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id", scope = Role.class)
public class Role implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "role_id")
private int id;
@Enumerated(EnumType.STRING)
private UserProfileType role;
@ManyToMany(mappedBy = "roles", fetch = FetchType.EAGER)
@JsonBackReference
private List<User> users = new ArrayList<User>();
public UserProfileType getRole() {
return role;
}
public void setRole(UserProfileType role) {
this.role = role;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
} |
package com.onlythinking.commons.exception;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
/**
* <p> API 响应 CODE 对照表 </p>
*
* @author Li Xingping
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class GlobalErrorCode {
//-----------------------------------------常用错误状态(0x7530-0x9c3F)---------------------------------------------------
//-----------------------------------------业务错误状态(0x9C40-0xC349)---------------------------------------------------
//-----------------------------------------Http错误状态(0x0100-0x01FF)-----------------------------------------------------
public static final int SC_BAD_REQUEST = 400,
SC_UNAUTHORIZED = 401,
SC_PAYMENT_REQUIRED = 402,
SC_FORBIDDEN = 403,
SC_NOT_FOUND = 404,
SC_METHOD_NOT_ALLOWED = 405,
SC_NOT_ACCEPTABLE = 406,
SC_PROXY_AUTHENTICATION_REQUIRED = 407,
SC_REQUEST_TIMEOUT = 408,
SC_CONFLICT = 409,
SC_GONE = 410,
SC_LENGTH_REQUIRED = 411,
SC_PRECONDITION_FAILED = 412,
SC_PAYLOAD_TOO_LARGE = 413,
SC_URI_TOO_LONG = 413,
SC_UNSUPPORTED_MEDIA_TYPE = 415,
SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416,
SC_EXPECTATION_FAILED = 417,
SC_I_AM_A_TEAPOT = 418,
SC_UNPROCESSABLE_ENTITY = 422,
SC_LOCKED = 423,
SC_FAILED_DEPENDENCY = 424,
SC_UPGRADE_REQUIRED = 426,
SC_PRECONDITION_REQUIRED = 428,
SC_TOO_MANY_REQUESTS = 429,
SC_REQUEST_HEADER_FIELDS_TOO_LARGE = 431,
SC_UNAVAILABLE_FOR_LEGAL_REASONS = 451,
SC_INTERNAL_SERVER_ERROR = 500,
SC_NOT_IMPLEMENTED = 501,
SC_BAD_GATEWAY = 502,
SC_SERVICE_UNAVAILABLE = 503,
SC_GATEWAY_TIMEOUT = 504,
SC_HTTP_VERSION_NOT_SUPPORTED = 505,
SC_VARIANT_ALSO_NEGOTIATES = 506,
SC_INSUFFICIENT_STORAGE = 507,
SC_LOOP_DETECTED = 508,
SC_BANDWIDTH_LIMIT_EXCEEDED = 509,
SC_NOT_EXTENDED = 510,
SC_NETWORK_AUTHENTICATION_REQUIRED = 511;
//-----------------------------------------全局错误状态---------------------------------------------------
public static final int SUCCESSFUL = 0x0000, // 请求成功
API_ARGUMENT_INVALID = 0x7531, // API请求参数校验不通过(如: NotBlank NotEmpty)
API_VIOLATION_ERROR = 0x7532, // 实体或方法参数约束校验不通过
API_REQUEST_TIMEOUT = 0x7533, // API请求超时
SYSTEM_BUSY = -1, // 系统繁忙,请稍候再试
UNDEFINED = 0xFFFF;
}
|
package br.com.Falcao.PontoInteligente.api.services.impl;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.Falcao.PontoInteligente.api.entitys.Empresa;
import br.com.Falcao.PontoInteligente.api.repositorys.EmpresaRepository;
import br.com.Falcao.PontoInteligente.api.services.EmpresaService;
@Service
public class EmpresaServiceImpl implements EmpresaService{
private static final Logger log = LoggerFactory.getLogger(EmpresaServiceImpl.class);
@Autowired
private EmpresaRepository er;
@Override
public List<Empresa> listar() {
// TODO Auto-generated method stub
log.info("Listando todas as empresas presentes no banco de dados.");
return this.er.findAll();
}
@Override
public Optional<Empresa> buscarPorCnpj(String cnpj) {
// TODO Auto-generated method stub
log.info("Buscando uma empresa pelo CNPJ {}", cnpj);
return Optional.ofNullable(this.er.findByCnpj(cnpj));
}
@Override
public Empresa persistir(Empresa empresa) {
// TODO Auto-generated method stub
log.info("Adicionando a empresa no banco de dados: {}", empresa);
return this.er.save(empresa);
}
@Override
public void remover(Long id) {
// TODO Auto-generated method stub
log.info("Removendo empresa no banco de dados pelo id: {}", id);
this.er.delete(id);
}
@Override
public Optional<Empresa> buscarPorId(Long id) {
// TODO Auto-generated method stub
return Optional.ofNullable(this.er.findOne(id));
}
}
|
package root.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import root.entity.Action;
@Repository
public interface ActionRepo extends JpaRepository<Action, Long> {
}
|
package com.youtalkwesign.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.youtalkwesign.model.Video;
import com.youtalkwesign.service.HeartedService;
@Controller
public class HeartedController {
@Autowired
HeartedService service;
@RequestMapping(value = "/hearted", method = RequestMethod.GET)
public String getHeartedVideos(ModelMap model) {
// get username
String username = SecurityContextHolder.getContext().getAuthentication().getName();
List<Video> heartedVideos = new ArrayList<Video>();
if (username.equals("anonymousUser")) {
model.addAttribute("heartedVideos", heartedVideos);
} else {
heartedVideos = service.getHeartedVideos(username);
model.addAttribute("heartedVideos", heartedVideos);
}
return "hearted-fragment :: result";
}
@RequestMapping(value = "/unheart", method = RequestMethod.POST, produces="text/plain")
@ResponseBody
public String unHeart(@RequestParam String username, @RequestParam String videoId) {
service.unheart(username, videoId);
return "success";
}
}
|
package com.jlxy.bllld.mapper;
import com.jlxy.bllld.BaseJunitTest;
import com.jlxy.bllld.entity.BlogInfo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
import static org.junit.Assert.*;
/**
* Created by ORCHID on 2017/3/25.
*/
public class BlogInfoMapperTest extends BaseJunitTest {
@Autowired
BlogInfoMapper blogInfoMapper;
@Autowired
UserMapper userMapper;
@Test
public void selectByName() throws Exception {
List<BlogInfo> blogInfos=blogInfoMapper.selectByName("xiaoxiao");
for(BlogInfo blogInfo:blogInfos){
System.out.println("UId:"+blogInfo.getUser().getUId()+",Name:"+blogInfo.getName()+",Title:"+blogInfo.getBlogTitle()+",idiograph:"+blogInfo.getIdIograph());
}
}
@Test
public void update() throws Exception {
BlogInfo blogInfo=new BlogInfo();
blogInfo.setUser(userMapper.selectByName("haha"));
blogInfo.setName("haha");
blogInfo.setBlogTitle("heheheheh");
blogInfo.setIdIograph("a;sdlk");
blogInfoMapper.update(blogInfo);
}
@Test
public void add() throws Exception {
BlogInfo blogInfo=new BlogInfo();
blogInfo.setUser(userMapper.selectByName("haha"));
blogInfo.setName("heihei");
blogInfo.setBlogTitle("heheheheh");
blogInfo.setIdIograph("a;sdaslk");
System.out.println(blogInfoMapper.add(blogInfo));
}
} |
package com.tencent.mm.plugin.subapp.ui.voicetranstext;
import android.os.Message;
import com.tencent.mm.sdk.platformtools.ag;
class VoiceTransTextUI$6 extends ag {
final /* synthetic */ VoiceTransTextUI ouz;
VoiceTransTextUI$6(VoiceTransTextUI voiceTransTextUI) {
this.ouz = voiceTransTextUI;
}
public final void handleMessage(Message message) {
int i = message.what;
if (i == 1) {
VoiceTransTextUI.b(this.ouz, true);
} else if (i == 2) {
VoiceTransTextUI.b(this.ouz, false);
}
}
}
|
package com.cater;
import java.util.concurrent.ThreadLocalRandom;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Frontdesk implements Runnable {
private Order load;
private String name;
private final static Logger logger = LoggerFactory.getLogger(Frontdesk.class);
Frontdesk(Order order, String name){
load = order;
this.name = name;
}
public void run() {
while(true) {
int receivedMessage = load.receive();
//System.out.println(name + " receive order " + receivedMessage + ",catering....");
logger.info(name + " receive order " + receivedMessage + ",catering....");
//cater
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logger.error("Thread interrupted", e);
}
//System.out.println("Order " + receivedMessage + " finished!");
logger.info("Order " + receivedMessage + " finished!");
try {
Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logger.error("Thread interrupted", e);
}
}
}
}
|
package com.eigen.impl.dao;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;
import com.eigen.iface.dao.HistDataDao;
import com.eigen.model.MHistData;
@Repository
public class HistDataDaoImpl implements HistDataDao {
@Autowired
private SessionFactory sessionFactory;
@Autowired
private HibernateTemplate hibernateTemplate;
@Override
@Transactional
public void doSave(MHistData o) {
hibernateTemplate.save(o);
}
@Override
@Transactional
public void doDelete_byProfileId(long nProfile_id) {
List<MHistData> ls = getHistData_all_byProfileId(nProfile_id);
hibernateTemplate.deleteAll(ls);
}
@Override
@Transactional
public List<MHistData> getHistData_all_byProfileId(long nProfile_id) {
String hql = "from MHistData d"
+ " where"
+ " (d.profile_id = :profile_id)";
String[] names = {"profile_id"};
Object[] values = {nProfile_id};
@SuppressWarnings("unchecked")
List<MHistData> ls = (List<MHistData>) hibernateTemplate.findByNamedParam(hql, names, values);
return ls;
}
@Override
@Transactional
public List<MHistData> getHistData_byProfileId_byType_byDate(long nProfile_id, String sType, Date dtFrom, Date dtTo) {
//
Calendar cFrom = Calendar.getInstance();
cFrom.setTime(dtFrom);
Calendar cTo = Calendar.getInstance();
cTo.setTime(dtTo);
//
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(MHistData.class)
.add(Restrictions.eq("profile_id", nProfile_id))
.add(Restrictions.ge("ts", cFrom))
.add(Restrictions.le("ts", cTo))
.addOrder(Order.asc("ts"));
//
@SuppressWarnings("unchecked")
List<MHistData> ls = (List<MHistData>) criteria.list();
return ls;
}
}
|
/*
* 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 br.com.utfpr.forms;
import br.com.utfpr.beans.Product;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
*
* @author Usuario
*/
public class ProductForm extends javax.swing.JFrame {
/**
* Creates new form ProductForm
*/
public ProductForm() {
initComponents();
initializeTable();
}
String[] tableModel = new String[] {"Produto","Preço"};
private DefaultTableModel model = new DefaultTableModel(null,tableModel);
private void initializeTable(){
model.setRowCount(0);
jTable1.setModel(model);
new Product().getList().forEach(product ->{
model.addRow(new String[]{
product.getName(),
Double.toString(product.getPrice())
});
});
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
add = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
Home = new javax.swing.JLabel();
name = new javax.swing.JTextField();
price = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
add.setText("Adiciionar");
add.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addActionPerformed(evt);
}
});
jButton2.setText("Remover");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
Home.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/utfpr/images/home_icon.png"))); // NOI18N
Home.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
HomeMouseClicked(evt);
}
});
jLabel1.setText("Produto:");
jLabel2.setText("Preço:");
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jTable1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(add, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addComponent(Home, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(price, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addComponent(add)
.addGap(28, 28, 28)
.addComponent(jButton2)
.addGap(18, 18, 18)
.addComponent(Home, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(jLabel1)
.addGap(6, 6, 6)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(8, 8, 8)
.addComponent(jLabel2)
.addGap(8, 8, 8)
.addComponent(price, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void HomeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_HomeMouseClicked
// TODO add your handling code here:
new br.com.utfpr.forms.MainForm().show();
dispose();
}//GEN-LAST:event_HomeMouseClicked
private void addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addActionPerformed
try {
new Product().add(newProduct());
JOptionPane.showMessageDialog(rootPane,"Produto inserido com sucesso");
initializeTable();
name.setText("");
price.setText("");
} catch (RuntimeException e) {
JOptionPane.showMessageDialog(rootPane,"Erro ao Inserir no Banco!\n" + e);
}
}//GEN-LAST:event_addActionPerformed
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
int line = jTable1.getSelectedRow();
name.setText(jTable1.getValueAt(line,0).toString());
price.setText(jTable1.getValueAt(line,1).toString());
}//GEN-LAST:event_jTable1MouseClicked
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
//remove - faltou renomear
try {
new Product().remove(name.getText());
JOptionPane.showMessageDialog(rootPane,"Produto removido com sucesso");
initializeTable();
name.setText("");
price.setText("");
} catch (RuntimeException e) {
JOptionPane.showMessageDialog(rootPane,"Produto não existe" + e);
}
}//GEN-LAST:event_jButton2ActionPerformed
private Product newProduct() {
Product prod = new Product();
prod.setName(name.getText());
prod.setPrice(Double.parseDouble(price.getText()));
return prod;
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ProductForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ProductForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ProductForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ProductForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ProductForm().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel Home;
private javax.swing.JButton add;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTextField name;
private javax.swing.JTextField price;
// End of variables declaration//GEN-END:variables
}
|
public class Decoding {
int message = 11211;
int messageSize = message.length();
char[] alphabet = getAlphabet();
public static void main(String[] args) {
Decoding obj = new Decoding();
}
public Decoding() {
System.out.println(alphabet[26]);
}
public char[] getAlphabet() {
char[] alphabet = new char[27];
int counter = 1;
for(char a = 'a', z = 'z'; a <= z; a++) {
alphabet[counter] = a;
counter++;
}
return alphabet;
}
}
|
public abstract class Item {
public abstract String getInfo();
public abstract int getPrice();
public abstract String getType();
public abstract void show();
protected String type;
protected int price;
protected int sNo;
}
|
package com.emp.friskyplayer.activities;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.Html;
import com.actionbarsherlock.app.SherlockPreferenceActivity;
import com.actionbarsherlock.view.MenuItem;
import com.emp.friskyplayer.R;
import com.emp.friskyplayer.application.FriskyPlayerApplication;
import com.emp.friskyplayer.utils.PreferencesConstants;
import com.emp.friskyplayer.utils.ServiceActionConstants;
public class FriskyPlayerPreferencesActivity extends SherlockPreferenceActivity
implements SharedPreferences.OnSharedPreferenceChangeListener {
private boolean sleepMode;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
String text = "<font color='#d84395'>frisky</font><font color='#cfcdce'>Player</font>";
getSupportActionBar().setTitle(Html.fromHtml(text));
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
SharedPreferences sharedPrefs = getPreferenceManager()
.getSharedPreferences();
sharedPrefs.registerOnSharedPreferenceChangeListener(this);
sleepMode = sharedPrefs.getBoolean(PreferencesConstants.SLEEP_MODE, false);
}
@Override
protected void onStop() {
super.onStop();
if(sleepMode){
// Enable sleep mode
((FriskyPlayerApplication) getApplication()).getInstance().enableSleepMode();
}
}
public void onSharedPreferenceChanged(SharedPreferences sharedPrefs,
String key) {
if (key.equals(PreferencesConstants.SLEEP_MODE)) {
sleepMode = sharedPrefs.getBoolean(PreferencesConstants.SLEEP_MODE, false);
if(!sleepMode){
// Stops sleep mode
((FriskyPlayerApplication) getApplication()).getInstance().disableSleepMode();
}
}else if(key.equals(PreferencesConstants.SLEEP_MODE_TIMEOUT)){
sleepMode = sharedPrefs.getBoolean(PreferencesConstants.SLEEP_MODE, false);
if(sleepMode){
// Restarts countdown using new value
((FriskyPlayerApplication) getApplication()).getInstance().disableSleepMode();
((FriskyPlayerApplication) getApplication()).getInstance().enableSleepMode();
}
}
else if (key.equals(PreferencesConstants.QUALITY)) {
((FriskyPlayerApplication) getApplication()).getInstance().onQualityPrefChange();
String quality = sharedPrefs.getString(PreferencesConstants.QUALITY, PreferencesConstants.QUALITY_HQ);
Editor editor = sharedPrefs.edit();
if(quality.equals(PreferencesConstants.QUALITY_HQ)){
editor.putString(PreferencesConstants.STREAMING_URL,PreferencesConstants.STREAMING_URL_HQ);
}if(quality.equals(PreferencesConstants.QUALITY_LQ)){
editor.putString(PreferencesConstants.STREAMING_URL,PreferencesConstants.STREAMING_URL_LQ);
}
editor.commit();
//Notifies service
getApplicationContext().startService(new Intent(ServiceActionConstants.ACTION_CHANGE_QUALITY));
}
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case android.R.id.home:
finish();
break;
}
return true;
}
}
|
package com.argentinatecno.checkmanager.main.fragment_reports.events;
import com.argentinatecno.checkmanager.entities.Check;
import com.argentinatecno.checkmanager.entities.Maturities;
public class FragmentReportEvent {
private String error;
private Maturities maturities;
public final static String ERROR= "Error al obtener los vencimientos de la semana.";
public Maturities getMaturities() {
return maturities;
}
public void setMaturities(Maturities maturities) {
this.maturities = maturities;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
}
|
package com.lingnet.vocs.service.finance;
import java.util.HashMap;
import com.lingnet.common.service.BaseService;
import com.lingnet.util.Pager;
import com.lingnet.vocs.entity.ContractCharge;
public interface ContractChargeService extends BaseService<ContractCharge, String> {
void saveOrUpdate(ContractCharge contractCharge) throws Exception;
@SuppressWarnings("rawtypes")
HashMap getListData(Pager pager,String id,String htsf);
String changeVerifyStatus(String amId, String verifyStatus) throws Exception;
}
|
package com.flutterwave.raveandroid.rave_presentation.banktransfer;
import com.flutterwave.raveandroid.rave_java_commons.Meta;
import com.flutterwave.raveandroid.rave_java_commons.Payload;
import com.flutterwave.raveandroid.rave_java_commons.SubAccount;
import com.flutterwave.raveandroid.rave_presentation.DaggerTestRaveComponent;
import com.flutterwave.raveandroid.rave_presentation.TestNetworkModule;
import com.flutterwave.raveandroid.rave_presentation.TestRaveComponent;
import com.flutterwave.raveandroid.rave_presentation.TestUtilsModule;
import com.flutterwave.raveandroid.rave_presentation.data.PayloadEncryptor;
import com.flutterwave.raveandroid.rave_presentation.data.PayloadToJson;
import com.flutterwave.raveandroid.rave_remote.Callbacks;
import com.flutterwave.raveandroid.rave_remote.FeeCheckRequestBody;
import com.flutterwave.raveandroid.rave_remote.RemoteRepository;
import com.flutterwave.raveandroid.rave_remote.ResultCallback;
import com.flutterwave.raveandroid.rave_remote.requests.ChargeRequestBody;
import com.flutterwave.raveandroid.rave_remote.requests.RequeryRequestBody;
import com.flutterwave.raveandroid.rave_remote.responses.ChargeResponse;
import com.flutterwave.raveandroid.rave_remote.responses.FeeCheckResponse;
import com.flutterwave.raveandroid.rave_remote.responses.RequeryResponse;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.inject.Inject;
import static junit.framework.TestCase.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class BankTransferHandlerTest {
@Mock
BankTransferContract.BankTransferInteractor interactor;
@Inject
PayloadToJson payloadToJson;
@Inject
PayloadEncryptor payloadEncryptor;
@Inject
RemoteRepository networkRequest;
@Mock
RequeryRequestBody requeryRequestBody;
private BankTransferHandler paymentHandler;
@Mock
private BankTransferHandler paymentHandlerMock;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
paymentHandler = new BankTransferHandler(interactor);
TestRaveComponent component = DaggerTestRaveComponent.builder()
.testNetworkModule(new TestNetworkModule())
.testUtilsModule(new TestUtilsModule())
.build();
component.inject(this);
component.inject(paymentHandler);
}
@Test
public void fetchFee_onError_onFetchFeeErrorCalled() {
paymentHandler.fetchFee(generatePayload());
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).getFee(any(FeeCheckRequestBody.class), captor.capture());
captor.getAllValues().get(0).onError(generateRandomString());
verify(interactor).showProgressIndicator(false);
verify(interactor).onFetchFeeError(anyString());
}
@Test
public void fetchFee_onSuccess_onTransactionFeeFetchedCalled() {
paymentHandler.fetchFee(generatePayload());
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).getFee(any(FeeCheckRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(generateFeeCheckResponse());
verify(interactor).onTransactionFeeFetched(anyString(), any(Payload.class), anyString());
}
@Test
public void fetchFee_onSuccess_Exception_showFetchFeeFailedCalled() throws NullPointerException {
doThrow(NullPointerException.class).when(interactor).onTransactionFeeFetched(any(String.class), any(Payload.class), anyString());
paymentHandler.fetchFee(generatePayload());
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).getFee(any(FeeCheckRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(new FeeCheckResponse());
verify(interactor).onFetchFeeError(anyString());
}
@Test
public void payWithBankTransfer_chargeCard_onSuccess_onTransferDetailsReceivedCalled() {
Payload payload = generatePayload();
when(payloadToJson.convertChargeRequestPayloadToJson(payload)).thenReturn(generateRandomString());
when(payloadEncryptor.getEncryptedData(any(String.class), any(String.class))).thenReturn(generateRandomString());
paymentHandler.payWithBankTransfer(payload, generateRandomString());
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
ChargeResponse chargeResponse = generateValidChargeResponse();
verify(networkRequest).charge(any(ChargeRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(chargeResponse);
verify(interactor).showProgressIndicator(false);
verify(interactor).onTransferDetailsReceived(chargeResponse.getData().getAmount(), chargeResponse.getData().getAccountnumber(), chargeResponse.getData().getBankname(), chargeResponse.getData().getNote().substring(
chargeResponse.getData().getNote().indexOf("to ") + 3));
}
@Test
public void payWithBankTransfer_chargeCard_onSuccess_nullResponse_onTransferDetailsReceivedCalled() {
Payload payload = generatePayload();
when(payloadToJson.convertChargeRequestPayloadToJson(payload)).thenReturn(generateRandomString());
when(payloadEncryptor.getEncryptedData(any(String.class), any(String.class))).thenReturn(generateRandomString());
paymentHandler.payWithBankTransfer(payload, generateRandomString());
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
ChargeResponse chargeResponse = new ChargeResponse();
verify(networkRequest).charge(any(ChargeRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(chargeResponse);
verify(interactor).onPaymentError("No response data was returned");
}
@Test
public void payWithBankTransfer_chargeCard_onError_onPaymentErrorCalled() {
Payload payload = generatePayload();
when(payloadToJson.convertChargeRequestPayloadToJson(payload)).thenReturn(generateRandomString());
when(payloadEncryptor.getEncryptedData(any(String.class), any(String.class))).thenReturn(generateRandomString());
paymentHandler.payWithBankTransfer(payload, generateRandomString());
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
String message = generateRandomString();
verify(networkRequest).charge(any(ChargeRequestBody.class), captor.capture());
captor.getAllValues().get(0).onError(message);
verify(interactor).showProgressIndicator(false);
verify(interactor).onPaymentError(message);
}
@Test
public void startPaymentVerification_requeryTxCalled() {
paymentHandler.startPaymentVerification(300);
long time = System.currentTimeMillis();
String randomflwRef = generateRandomString();
String randomTxRef = generateRandomString();
String randomPubKey = generateRandomString();
verify(interactor).showPollingIndicator(true);
paymentHandlerMock.requeryTx(randomflwRef, randomTxRef, randomPubKey, true, time, time);
verify(paymentHandlerMock).requeryTx(randomflwRef, randomTxRef, randomPubKey, true, time, time);
}
@Test
public void cancelPolling_pollingCancelledTrue() {
paymentHandler.cancelPolling();
assertTrue(paymentHandler.pollingCancelled);
}
@Test
public void requeryTx_onSuccess_onRequerySuccessful_onPaymentSuccessful_00_Called() {
String randomflwRef = generateRandomString();
String randomTxRef = generateRandomString();
String randomPubKey = generateRandomString();
long time = System.currentTimeMillis();
paymentHandler.requeryTx(randomflwRef, randomTxRef, randomPubKey, true, time, time);
requeryRequestBody.setFlw_ref(generateRandomString());
requeryRequestBody.setPBFPubKey(generateRandomString());
String responseJson = generateRandomString();
ArgumentCaptor<Callbacks.OnRequeryRequestComplete> captor = ArgumentCaptor.forClass(Callbacks.OnRequeryRequestComplete.class);
verify(networkRequest).requeryPayWithBankTx(any(RequeryRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(generateRequerySuccessful("00"), responseJson);
verify(interactor).showPollingIndicator(false);
verify(interactor).onPaymentSuccessful(randomflwRef, randomTxRef, responseJson);
}
@Test
public void requeryTx_onSuccess_onRequerySuccessful_onPaymentSuccessful_01_onPollingTimeoutCalled() {
String randomflwRef = generateRandomString();
String randomTxRef = generateRandomString();
String randomPubKey = generateRandomString();
long time = 400000;
paymentHandler.requeryTx(randomflwRef, randomTxRef, randomPubKey, false, time, time);
String responseJson = generateRandomString();
ArgumentCaptor<Callbacks.OnRequeryRequestComplete> captor = ArgumentCaptor.forClass(Callbacks.OnRequeryRequestComplete.class);
verify(networkRequest).requeryPayWithBankTx(any(RequeryRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(generateRequerySuccessful("01"), responseJson);
verify(interactor).showPollingIndicator(false);
verify(interactor).onPollingTimeout(randomflwRef, randomTxRef, responseJson);
}
@Test
public void requeryTx_onSuccess_onRequerySuccessful_onPaymentSuccessful_01_requeryTxCalled() {
String randomflwRef = generateRandomString();
String randomTxRef = generateRandomString();
String randomPubKey = generateRandomString();
long time = System.currentTimeMillis() - 10000;
doCallRealMethod().when(paymentHandlerMock).requeryTx(
any(String.class),
any(String.class),
any(String.class),
anyBoolean(),
anyLong(), eq(time));
paymentHandlerMock.networkRequest = networkRequest;
paymentHandlerMock.pollingCancelled = false;
paymentHandlerMock.mInteractor = interactor;
paymentHandlerMock.requeryTx(randomflwRef, randomTxRef, randomPubKey, false, time, time);
String responseJson = generateRandomString();
ArgumentCaptor<Callbacks.OnRequeryRequestComplete> captor = ArgumentCaptor.forClass(Callbacks.OnRequeryRequestComplete.class);
verify(networkRequest).requeryPayWithBankTx(any(RequeryRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(generateRequerySuccessful("01"), responseJson);
verify(paymentHandlerMock, times(2))
.requeryTx(anyString(), anyString(), anyString(), anyBoolean(), anyLong(), eq(time));
}
@Test
public void requeryTx_onSuccess_onRequerySuccessful_onPaymentSuccessful_01_PollingCancelled() {
String randomflwRef = generateRandomString();
String randomTxRef = generateRandomString();
String randomPubKey = generateRandomString();
long time = System.currentTimeMillis();
paymentHandler.requeryTx(randomflwRef, randomTxRef, randomPubKey, true, time, time);
String responseJson = generateRandomString();
ArgumentCaptor<Callbacks.OnRequeryRequestComplete> captor = ArgumentCaptor.forClass(Callbacks.OnRequeryRequestComplete.class);
verify(networkRequest).requeryPayWithBankTx(any(RequeryRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(generateRequerySuccessful("01"), responseJson);
verify(interactor).showPollingIndicator(false);
verify(interactor).onPollingCanceled(randomflwRef, randomTxRef, responseJson);
}
@Test
public void requeryTx_onSuccess_nullResponse_onPaymentFailedCalled() {
long time = System.currentTimeMillis();
RequeryResponse requeryResponse = new RequeryResponse();
String jsonResponse = generateRandomString();
paymentHandler.requeryTx(generateRandomString(), generateRandomString(), generateRandomString(), true, time, time);
ArgumentCaptor<Callbacks.OnRequeryRequestComplete> captor = ArgumentCaptor.forClass(Callbacks.OnRequeryRequestComplete.class);
verify(networkRequest).requeryPayWithBankTx(any(RequeryRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(requeryResponse, jsonResponse);
verify(interactor).onPaymentFailed(requeryResponse.getStatus(), jsonResponse);
}
@Test
public void requeryTx_onSuccess_chargeResponseCodeNeither00Nor01_onPaymentFailedCalled() {
long time = System.currentTimeMillis();
RequeryResponse requeryResponse = new RequeryResponse();
String jsonResponse = generateRandomString();
paymentHandler.requeryTx(generateRandomString(), generateRandomString(), generateRandomString(), true, time, time);
ArgumentCaptor<Callbacks.OnRequeryRequestComplete> captor = ArgumentCaptor.forClass(Callbacks.OnRequeryRequestComplete.class);
verify(networkRequest).requeryPayWithBankTx(any(RequeryRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(generateRequerySuccessful("099"), jsonResponse);
verify(interactor).showProgressIndicator(false);
verify(interactor).onPaymentFailed(requeryResponse.getStatus(), jsonResponse);
}
@Test
public void requeryTx_onError_onPaymentFailedCalled() {
long time = System.currentTimeMillis();
paymentHandler.requeryTx(generateRandomString(), generateRandomString(), generateRandomString(), true, time, time);
ArgumentCaptor<Callbacks.OnRequeryRequestComplete> captor = ArgumentCaptor.forClass(Callbacks.OnRequeryRequestComplete.class);
verify(networkRequest).requeryPayWithBankTx(any(RequeryRequestBody.class), captor.capture());
captor.getAllValues().get(0).onError(generateRandomString(), generateRandomString());
verify(interactor).onPaymentFailed(anyString(), anyString());
}
private String generateRandomString() {
return UUID.randomUUID().toString();
}
private Payload generatePayload() {
List<Meta> metas = new ArrayList<>();
List<SubAccount> subAccounts = new ArrayList<>();
return new Payload(generateRandomString(), metas, subAccounts, generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString());
}
private RequeryResponse generateRequerySuccessful(String responseCode) {
RequeryResponse requeryResponse = new RequeryResponse();
RequeryResponse.Data data = new RequeryResponse.Data();
data.setChargeResponseCode(responseCode);
requeryResponse.setData(data);
return requeryResponse;
}
private ChargeResponse generateValidChargeResponse() {
ChargeResponse chargeResponse = new ChargeResponse();
chargeResponse.setData(new ChargeResponse.Data());
chargeResponse.getData().setChargeResponseCode("00");
chargeResponse.getData().setNote("Please transfer to Abakaliki General");
chargeResponse.getData().setChargedAmount(generateRandomString());
chargeResponse.getData().setBankName(generateRandomString());
chargeResponse.getData().setAccountnumber(generateRandomString());
return chargeResponse;
}
private FeeCheckResponse generateFeeCheckResponse() {
FeeCheckResponse feeCheckResponse = new FeeCheckResponse();
FeeCheckResponse.Data feeCheckResponseData = new FeeCheckResponse.Data();
feeCheckResponseData.setCharge_amount(generateRandomString());
feeCheckResponse.setData(feeCheckResponseData);
feeCheckResponse.getData().setFee(generateRandomString());
return feeCheckResponse;
}
} |
package com.z3pipe.z3location.content;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import com.z3pipe.z3location.broadcast.GpsLocationListener;
import java.util.List;
public class GpsPosHelper {
private static GpsPosHelper m_instance = null;
private LocationManager locationManager;
/**
* 是否正在使用网络定位
*/
private boolean networkUsing = false;
/**
* 是否正在使用GPS
*/
private boolean gpsUsing = false;
private boolean init = false;
private boolean getPosSuccess = false;
private GpsLocationListener gpsLocationListener;
/**
* private访问,不允许外部new出实例
*/
private GpsPosHelper() {
// TODO Auto-generated constructor stub
}
/**
* 获取定位实例
*
* @return
*/
public static GpsPosHelper getInstance() {
if (m_instance == null) {
m_instance = new GpsPosHelper();
}
return m_instance;
}
//public void setGetPosListener(GpsPosListener listener){
// this.listener = listener;
// }
/**
* 初始化
*
* @param context
*/
public void init(Context context) {
if (init) {
return;
}
this.getPosSuccess = false;
initPositionSensor(context);
init = true;
}
/**
* 判断是否已经经过了初始化
*
* @return
*/
public boolean isInited() {
return init;
}
// public void pause(long timeminus) {
// pausedTime = timeminus;
// long currentTime = System.currentTimeMillis();
// lastSendTime = currentTime;
// }
/**
* 退出地图,注销定位监听器。
*/
public void stopLocation() {
gpsLocationListener = null;
stopGpsLocation();
stopNetworkLocation();
// if (timer != null) {
// try {
// timer.cancel();
// } catch (Exception e) {
// e.printStackTrace();
// }
// timer = null;
// }
init = false;
}
/**
* 开始监听位置。
* 该时间之后依然未收到坐标,则认为失败。
*/
public void startLocation(GpsLocationListener listener) {
gpsLocationListener = listener;
this.getPosSuccess = false;
startGpsLocation();
startNetworkLocation();
// if (timeDelay > 0) {
// if (timer != null) {
// return;
// }
//
//
// timer = new Timer();
// TimerTask timerTask = new TimerTask() {
// @Override
// public void run() {
//
// if (!getPosSuccess) {
// PositionManager.getInstance().positionError("获取坐标失败");
// }
//
// }
// };
// timer.schedule(timerTask, timeDelay);
// }
}
/**
* 初始化定位
*
* @param context
*/
private void initPositionSensor(Context context) {
if (locationManager != null) {
locationManager = null;
}
if (context != null) {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
}
/**
* 启动网络定位
*
* @return
*/
private boolean startNetworkLocation() {
if (getNetworkUseful()) {
if (!networkUsing) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, networkListener);
}
networkUsing = true;
return true;
}
return false;
}
/**
* 启动GPS定位
*
* @return
*/
private boolean startGpsLocation() {
if (getGpsUseful()) {
if (!gpsUsing) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, gpsListener);
}
gpsUsing = true;
return true;
}
return false;
}
private void stopNetworkLocation() {
if (networkUsing) {
locationManager.removeUpdates(networkListener);
networkUsing = false;
}
}
private void stopGpsLocation() {
if (gpsUsing) {
locationManager.removeUpdates(gpsListener);
gpsUsing = false;
}
}
private LocationListener gpsListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
//ToastUtil.showShort("getLocationWithGPS:"+location.getLongitude()+","+location.getLatitude());
processNewLocation(location);
}
}
};
private LocationListener networkListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onLocationChanged(Location location) {
if (location != null) {
//ToastUtil.showShort("getLocationWithNetWork:" + location.getLongitude() + "," + location.getLatitude());
processNewLocation(location);
}
}
};
public List<String> getUsefulLocationList() {
if (locationManager == null) {
return null;
}
//List<String> accessibleProviders = locationManager.getProviders(true);
return locationManager.getProviders(true);
}
public boolean getGpsUseful() {
List<String> accessibleProviders = getUsefulLocationList();
if (accessibleProviders == null) {
//没有
return false;
}
if (accessibleProviders.contains(LocationManager.GPS_PROVIDER)) {
return true;
}
return false;
}
public boolean getNetworkUseful() {
List<String> accessibleProviders = getUsefulLocationList();
if (accessibleProviders == null) {
//没有
return false;
}
if (accessibleProviders.contains(LocationManager.NETWORK_PROVIDER)) {
return true;
}
return false;
}
/**
* 处理定位的坐标
*
* @param location
* @return
*/
private void processNewLocation(Location location) {
if (location == null) {
return;
}
//pro
getPosSuccess = true;
if (gpsLocationListener != null){
gpsLocationListener.onLocationChanged(location);
}
//
// long currentTime = System.currentTimeMillis();
//
// if (lastSendTime == 0) {
// lastSendTime = currentTime;
// } else if (currentTime - lastSendTime > pausedTime) {
//
// lastSendTime = currentTime;
// pausedTime = 0;
//
//
// if (location != null){
//
// double accuracy = location.getAccuracy();
//
// if (accuracy < 0) {
// accuracy = -accuracy;
// }
// double sqrtAccur = Math.sqrt(accuracy);
//
// PositionManager.getInstance().notifyGpsPositionReady();
//
// PositionManager.getInstance().newPositionArrive(new ECityPosition(location, ECityPosProducer.GPS),new PositionAccur(sqrtAccur, sqrtAccur, accuracy));
// }
// if (listener != null) {
// listener.LocationReceived(new ECityPosition(location, ECityPosProducer.GPS));
// double accuracy = location.getAccuracy();
//
// if (accuracy < 0) {
// accuracy = -accuracy;
// }
//
// double sqrtAccur = Math.sqrt(accuracy);
//
// listener.PositionAccurChanged(new PositionAccur(sqrtAccur, sqrtAccur, accuracy));
// }
// }
}
// private PositionChangeListener listener = new PositionChangeListener() {
//
// @Override
// public void LocationReceived(ECityPosition position) {
//
// SimPosHelper.getInstance().stopPosReceive();
// if (SessionManager.lastLocation == null) {
// SessionManager.lastLocation = position;
// }
// BlueToothEvent event = new BlueToothEvent();
// event.type = BlueToothEvent.BtEventType.POSITION;
// event.data = position;
// EventBusUtil.post(event);
// }
//
// @Override
// public void PositionAccurChanged(PositionAccur accur) {
// BlueToothEvent event = new BlueToothEvent();
// event.type = BlueToothEvent.BtEventType.PRECISION;
// event.data = accur;
// EventBusUtil.post(event);
// }
//
// @Override
// public void PositionErrord(String errorMsg) {
//
// BlueToothEvent event = new BlueToothEvent();
// event.type = BlueToothEvent.BtEventType.POS_ERROR;
// event.data = errorMsg;
// EventBusUtil.post(event);
//
// }
// };
}
|
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.Topology;
import org.apache.kafka.streams.kstream.KStream;
import org.apache.kafka.streams.kstream.KTable;
import org.apache.kafka.streams.kstream.Materialized;
import org.apache.kafka.streams.kstream.Produced;
import java.util.Arrays;
import java.util.Properties;
public class WordCountApplication {
public static void main(String[] args) {
WordCountApplication wordCountApplication = new WordCountApplication();
KafkaStreams streams = new KafkaStreams(wordCountApplication.createTopology(),
wordCountApplication.getKafkaProperties());
streams.start();
Runtime.getRuntime().addShutdownHook(new Thread(streams::close));
// print the topology
while(true){
streams.localThreadsMetadata().forEach(System.out::println);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
break;
}
}
}
public Topology createTopology(){
StreamsBuilder builder = new StreamsBuilder();
KStream<String, String> textLines = builder.stream("word-count-input");
KTable<String, Long> wordCounts = textLines
.mapValues(textLine -> textLine.toLowerCase())
.flatMapValues(textLine -> Arrays.asList(textLine.split("\\W+")))
.selectKey((key, word) -> word)
.groupByKey()
.count(Materialized.as("Counts"));
wordCounts.toStream().to("word-count-output", Produced.with(Serdes.String(), Serdes.Long()));
return builder.build();
}
public Properties getKafkaProperties(){
Properties properties = new Properties();
properties.put(StreamsConfig.APPLICATION_ID_CONFIG, "wordcount-application");
properties.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092");
properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
properties.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
properties.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
return properties;
}
}
|
public class CustomObjectOrder implements format {
private String text;
@Override
public void createHeader() {
this.text = "<Object header>";
}
@Override
public void createFooter() {
this.text += "<Object footer>";
}
@Override
public void addData(String data) {
this.text += data;
}
@Override
public void display() {
System.out.println(this.text);
}
}
|
package LinkedLists;
public class AddTwoNumbers {
public static void main(String[] args) {
ListNode l1 = new ListNode(0);
ListNode l2 = new ListNode(7);
l2.next = new ListNode(3);
System.out.println(addTwoNumbers(l1, l2).next.val);
}
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode save = l1;
int add = 0;
ListNode prev = l1;
while (l1 != null && l2 != null) {
System.out.println(l1.val + " " + l2.val);
int out = l1.val + l2.val + add;
l1.val = out % 10;
add = out / 10;
prev = l1;
l1 = l1.next;
l2 = l2.next;
}
if (l2 != null) {
prev.next = l2;
}
return save;
}
public static class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi;
import android.view.WindowManager.LayoutParams;
import com.tencent.mm.plugin.appbrand.e;
import com.tencent.mm.plugin.appbrand.l;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.MMActivity;
import org.json.JSONObject;
class bj$1 implements Runnable {
final /* synthetic */ int doP;
final /* synthetic */ l fCl;
final /* synthetic */ JSONObject fHi;
final /* synthetic */ bj fHj;
bj$1(bj bjVar, JSONObject jSONObject, l lVar, int i) {
this.fHj = bjVar;
this.fHi = jSONObject;
this.fCl = lVar;
this.doP = i;
}
public final void run() {
float f = 0.01f;
this.fHj.fHh = (float) this.fHi.optDouble("value");
if (Float.isNaN(this.fHj.fHh) || this.fHj.fHh < 0.0f || this.fHj.fHh > 1.0f) {
this.fCl.E(this.doP, this.fHj.f("fail:value invalid", null));
x.e("MicroMsg.JsApiSetScreenBrightness", "value invalid");
return;
}
MMActivity c = bj.c(this.fCl);
if (c == null) {
this.fCl.E(this.doP, this.fHj.f("fail", null));
x.e("MicroMsg.JsApiSetScreenBrightness", "context is null, invoke fail!");
return;
}
LayoutParams attributes = c.getWindow().getAttributes();
if (Float.isNaN(this.fHj.fHg)) {
this.fHj.fHg = attributes.screenBrightness;
e.a(this.fCl.mAppId, new 1(this, attributes, c));
}
if (this.fHj.fHh >= 0.01f) {
f = this.fHj.fHh;
}
attributes.screenBrightness = f;
c.getWindow().setAttributes(attributes);
this.fCl.E(this.doP, this.fHj.f("ok", null));
}
}
|
import java.util.*;
public class Solution {
static void shuffle(int[] arr, int n)
{
Random rand = new Random();
for (int i = n-1; i >= 0; i--) {
int index = rand.nextInt(n);
int temp = arr[index];
arr[index] = arr[i];
arr[i] = temp;
}
}
public static void quickSort(int[] input) {
int[] arr = new int[input.length+1];
shuffle(input,input.length);
for(int i = 0 ; i < input.length ; i++)
{
arr[i] = input[i];
}
arr[arr.length-1] = Integer.MAX_VALUE;
quickSort(arr,0,arr.length-1);
for (int i = 0; i < input.length; i++) {
input[i] = arr[i];
}
}
static int partition(int[] arr, int start, int end)
{
int i = start , j= end, pivot = arr[start];
while(i<=j)
{
do{
j--;
}while(arr[j]>pivot);
do{
i++;
}
while(arr[i]<=pivot);
if(i<j)
{
int temp = arr[i] ;
arr[i] = arr[j];
arr[j] = temp;
}
}
arr[start] = arr[j] ;
arr[j] = pivot;
return j;
}
public static void quickSort(int[] arr,int start, int end)
{
if(start>=end)
{
return;
}
int pivot = partition(arr, start, end);
quickSort(arr,start, pivot);
quickSort(arr,pivot+1,end);
}
} |
package com.example.kliker;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
public class SecondLvlActivity extends AppCompatActivity {
private int faza = 0;
private int switchVariable = 1;
private ImageView shtora;
private ImageView shtora1;
private Button open;
private Button close;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_main);
ImageView window = findViewById(R.id.window);
shtora = findViewById(R.id.shtora);
shtora1 = findViewById(R.id.shtora1);
window.setImageResource(R.drawable.window);
shtora.setImageResource(R.drawable.shtora);
shtora1.setImageResource(R.drawable.shtora1);
Button mainScreen = findViewById(R.id.button);
Button fourthmain = findViewById(R.id.bottleLVL);
open = findViewById(R.id.left);
close = findViewById(R.id.right);
mainScreen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
open.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
faza = faza - 1;
if (faza < 0) {
faza = 0;
return;
}
updateImage(-50, 50);
}
});
close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
faza = faza + 1;
if (faza > 5) {
faza = 5;
return;
}
updateImage(50, -50);
}
});
fourthmain.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick (View v){
startActivity(new Intent(SecondLvlActivity.this, FourthActivity.class));
}
});
}
protected void updateImage(int pixelShtora, int pixelShtora1) {
shtora.animate()
.xBy(pixelShtora)
.withEndAction(new Runnable() {
@Override
public void run() {
open.setEnabled(true);
close.setEnabled(true);
}
})
.withStartAction(new Runnable() {
@Override
public void run() {
open.setEnabled(false);
close.setEnabled(false);
}
})
.start();
shtora1.animate()
.xBy(pixelShtora1)
.start();
}
}
|
package mapsynq_automation;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import mapsynq.qa.pageobjects.MapsynqLiveIncidents;
import mapsynq.qa.testbase.BaseClass;
public class LiveIncidentPage extends BaseClass {
MapsynqLiveIncidents mapLive;
String thread;
public LiveIncidentPage() {
super();
}
@BeforeMethod
public void initilasation()
{
logger = report.startTest("MapsynqLiveIncidents");
init();
mapLive=new MapsynqLiveIncidents();
}
@Test
public void ClickandValidateIncident()
{
hideAdd("Hide the advatisement");
mapLive.clickIncident();
}
@AfterMethod
public void close()
{
dr.quit();
report.endTest(logger);
}
}
|
package com.tencent.mm.plugin.voiceprint.ui;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.tencent.mm.R;
public class NoiseDetectMaskView extends RelativeLayout {
ProgressBar eWx = null;
private Context mContext = null;
TextView oFU;
TextView oFV;
private b oFW;
private a oFX;
public NoiseDetectMaskView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
this.mContext = context;
this.mContext.getSystemService("layout_inflater");
LayoutInflater.from(this.mContext).inflate(R.i.noise_mask_view, this);
this.eWx = (ProgressBar) findViewById(R.h.noise_detect_progress);
this.oFU = (TextView) findViewById(R.h.noise_detect_hint);
this.oFV = (TextView) findViewById(R.h.noise_detect_retry);
this.oFV.setOnClickListener(new 1(this));
findViewById(R.h.left_btn).setOnClickListener(new 2(this));
}
public void setOnClickRetryCallback(b bVar) {
this.oFW = bVar;
}
public void setOnCancelDetectCallback(a aVar) {
this.oFX = aVar;
}
}
|
package com.chat.zipchat.Fragment;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.chat.zipchat.Activity.Payments.AddMoneyActivity;
import com.chat.zipchat.Activity.Payments.ReceiveMoneyActivity;
import com.chat.zipchat.Activity.Payments.SendMoneyActivity;
import com.chat.zipchat.Activity.Payments.TransHistoryActivity;
import com.chat.zipchat.Activity.Payments.WithdrawMoneyActivity;
import com.chat.zipchat.Adapter.Payment.SendTransAdapter;
import com.chat.zipchat.Model.GetAmountPojo;
import com.chat.zipchat.Model.GetMobileNumber.GetMobileNumberResponse;
import com.chat.zipchat.Model.GetXtoUPojo;
import com.chat.zipchat.Model.SentTransaction.SentTransListPojo;
import com.chat.zipchat.R;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import java.util.HashMap;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.chat.zipchat.Common.BaseClass.DOLLAR_SYMBOL;
import static com.chat.zipchat.Common.BaseClass.PopUpConvertedDateTime;
import static com.chat.zipchat.Common.BaseClass.UserId;
import static com.chat.zipchat.Common.BaseClass.apiInterfaceConvertion;
import static com.chat.zipchat.Common.BaseClass.apiInterfacePayment;
import static com.chat.zipchat.Common.BaseClass.isOnline;
import static com.chat.zipchat.Common.BaseClass.myLog;
import static com.chat.zipchat.Common.BaseClass.myToast;
import static com.chat.zipchat.Common.BaseClass.removeProgressDialog;
import static com.chat.zipchat.Common.BaseClass.showSimpleProgressDialog;
@SuppressLint("ValidFragment")
public class PaymentFragment extends Fragment implements View.OnClickListener {
Context mContext;
TextView mAvailableBalance, mSeeAll, mTxtNoTransaction;
LinearLayout mLlSend, mLlReceive, mLlAddMoney, mLlWithdraw;
RecyclerView mRvTransaction;
SendTransAdapter sendTransAdapter;
public PaymentFragment(Context mContext) {
this.mContext = mContext;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_payment, container, false);
mAvailableBalance = view.findViewById(R.id.mAvailableBalance);
mSeeAll = view.findViewById(R.id.mSeeAll);
mTxtNoTransaction = view.findViewById(R.id.mTxtNoTransaction);
mRvTransaction = view.findViewById(R.id.mRvTransaction);
mRvTransaction.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
mLlSend = view.findViewById(R.id.mLlSend);
mLlReceive = view.findViewById(R.id.mLlReceive);
mLlAddMoney = view.findViewById(R.id.mLlAddMoney);
mLlWithdraw = view.findViewById(R.id.mLlWithdraw);
mLlSend.setOnClickListener(this);
mLlReceive.setOnClickListener(this);
mLlAddMoney.setOnClickListener(this);
mLlWithdraw.setOnClickListener(this);
mSeeAll.setOnClickListener(this);
SendTransService();
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_payments, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.mToolScanner:
Scanning();
break;
}
return true;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.mLlSend:
Intent mSendMoney = new Intent(mContext, SendMoneyActivity.class);
startActivity(mSendMoney);
break;
case R.id.mLlReceive:
Intent mReceiveMoney = new Intent(mContext, ReceiveMoneyActivity.class);
startActivity(mReceiveMoney);
break;
case R.id.mLlAddMoney:
Intent mAddMoney = new Intent(mContext, AddMoneyActivity.class);
startActivity(mAddMoney);
break;
case R.id.mLlWithdraw:
Intent mWithdrawMoney = new Intent(mContext, WithdrawMoneyActivity.class);
startActivity(mWithdrawMoney);
break;
case R.id.mSeeAll:
Intent mTransHistory = new Intent(mContext, TransHistoryActivity.class);
startActivity(mTransHistory);
break;
}
}
private void SendTransService() {
if (isOnline(mContext)) {
showSimpleProgressDialog(mContext);
final Call<List<SentTransListPojo>> transactionResponseCall = apiInterfacePayment.sendTransactionList(UserId(mContext));
transactionResponseCall.enqueue(new Callback<List<SentTransListPojo>>() {
@Override
public void onResponse(Call<List<SentTransListPojo>> call, Response<List<SentTransListPojo>> response) {
removeProgressDialog();
if (response.isSuccessful()) {
if (response.body().size() > 0) {
mRvTransaction.setVisibility(View.VISIBLE);
mTxtNoTransaction.setVisibility(View.GONE);
sendTransAdapter = new SendTransAdapter(mContext, response.body(), PaymentFragment.this);
mRvTransaction.setAdapter(sendTransAdapter);
} else {
mRvTransaction.setVisibility(View.GONE);
mTxtNoTransaction.setVisibility(View.VISIBLE);
}
} else if (response.code() == 104) {
}
}
@Override
public void onFailure(Call<List<SentTransListPojo>> call, Throwable t) {
removeProgressDialog();
myLog("OnFailure", t.toString());
}
});
}
}
private void GetAmountService() {
if (isOnline(mContext)) {
final Call<List<GetAmountPojo>> getAmountResponseCall = apiInterfacePayment.getAmount(UserId(mContext));
getAmountResponseCall.enqueue(new Callback<List<GetAmountPojo>>() {
@Override
public void onResponse(Call<List<GetAmountPojo>> call, Response<List<GetAmountPojo>> response) {
if (response.isSuccessful()) {
if (response.body().size() > 0) {
GetXtoUService(Float.valueOf(response.body().get(0).getBalance()));
}
} else if (response.code() == 104) {
}
}
@Override
public void onFailure(Call<List<GetAmountPojo>> call, Throwable t) {
myLog("OnFailure", t.toString());
}
});
}
}
private void GetXtoUService(final Float Amount) {
if (isOnline(mContext)) {
final Call<GetXtoUPojo> transactionResponseCall = apiInterfaceConvertion.getXtoUConvertion();
transactionResponseCall.enqueue(new Callback<GetXtoUPojo>() {
@Override
public void onResponse(Call<GetXtoUPojo> call, Response<GetXtoUPojo> response) {
if (response.isSuccessful()) {
float USD = Float.valueOf(response.body().getUSD());
mAvailableBalance.setText("$ " + (USD * Amount));
} else if (response.code() == 104) {
}
}
@Override
public void onFailure(Call<GetXtoUPojo> call, Throwable t) {
myLog("OnFailure", t.toString());
}
});
}
}
public void mPopupDone(SentTransListPojo sentTransListPojo) {
final Dialog mPopupDoneDialog = new Dialog(getContext());
mPopupDoneDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mPopupDoneDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
mPopupDoneDialog.setContentView(R.layout.popup_transaction);
mPopupDoneDialog.setCancelable(false);
TextView mPopupAmount = mPopupDoneDialog.findViewById(R.id.mPopupAmount);
TextView mPopupNumber = mPopupDoneDialog.findViewById(R.id.mPopupNumber);
TextView mPopupSendAmount = mPopupDoneDialog.findViewById(R.id.mPopupSendAmount);
TextView mPopupTransactionFee = mPopupDoneDialog.findViewById(R.id.mPopupTransactionFee);
TextView mPopupTotalAmount = mPopupDoneDialog.findViewById(R.id.mPopupTotalAmount);
TextView mPopupDateTime = mPopupDoneDialog.findViewById(R.id.mPopupDateTime);
Button mPopupDone = mPopupDoneDialog.findViewById(R.id.mPopupDone);
mPopupAmount.setText(DOLLAR_SYMBOL + sentTransListPojo.getWalletAmount());
mPopupSendAmount.setText(DOLLAR_SYMBOL + sentTransListPojo.getWalletAmount());
mPopupTransactionFee.setText(DOLLAR_SYMBOL + sentTransListPojo.getWalletFee());
if (sentTransListPojo.getReceiver() != null) {
mPopupNumber.setText(sentTransListPojo.getReceiver().getFull_name());
float total = Float.valueOf(sentTransListPojo.getWalletAmount()) + Float.valueOf(sentTransListPojo.getWalletFee());
mPopupTotalAmount.setText(DOLLAR_SYMBOL + String.valueOf(total));
}
mPopupDateTime.setText("Sent on " + PopUpConvertedDateTime(sentTransListPojo.getCreatedTs()));
mPopupDone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPopupDoneDialog.dismiss();
}
});
mPopupDoneDialog.show();
}
@Override
public void onResume() {
super.onResume();
GetAmountService();
}
public void Scanning() {
IntentIntegrator qrScan = new IntentIntegrator(getActivity());
qrScan.setPrompt(getResources().getString(R.string.scan_code));
qrScan.setOrientationLocked(true);
qrScan.forSupportFragment(PaymentFragment.this).initiateScan();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (result != null) {
if (result.getContents() == null) {
myToast(mContext, getResources().getString(R.string.result_not_found));
}
}
if (result != null) {
if (result.getContents() == null) {
myToast(mContext, getResources().getString(R.string.result_not_found));
} else {
String mResult = result.getContents();
String newDisplayNumber = mResult.replaceAll("[^0-9]", "");
GetMobileNumber(newDisplayNumber);
}
}
}
private void GetMobileNumber(String number) {
if (isOnline(mContext)) {
showSimpleProgressDialog(mContext);
final Call<GetMobileNumberResponse> transactionResponseCall = apiInterfacePayment.getUserDetails(number);
transactionResponseCall.enqueue(new Callback<GetMobileNumberResponse>() {
@Override
public void onResponse(Call<GetMobileNumberResponse> call, Response<GetMobileNumberResponse> response) {
removeProgressDialog();
if (response.isSuccessful()) {
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("id", response.body().get_id().toString());
hashMap.put("number", response.body().getMobile_number());
Intent mSentMoney = new Intent(mContext, SendMoneyActivity.class);
mSentMoney.putExtra("userDetails", hashMap);
startActivity(mSentMoney);
} else if (response.code() == 104) {
}
}
@Override
public void onFailure(Call<GetMobileNumberResponse> call, Throwable t) {
removeProgressDialog();
myLog("OnFailure", t.toString());
}
});
}
}
}
|
package com.tencent.mm.plugin.wenote.ui.nativenote;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.plugin.wenote.model.a.p;
import com.tencent.mm.plugin.wenote.model.c;
import com.tencent.mm.plugin.wenote.model.g;
import com.tencent.mm.plugin.wenote.model.j;
import com.tencent.mm.plugin.wenote.model.nativenote.manager.h;
import com.tencent.mm.protocal.c.wn;
import com.tencent.mm.sdk.platformtools.x;
class b$1 implements OnClickListener {
final /* synthetic */ b quG;
b$1(b bVar) {
this.quG = bVar;
}
public final void onClick(View view) {
x.i("WNNoteBanner", "click WNNoteBanner");
p bZY = h.bZX().bZY();
if (bZY == null) {
x.i("WNNoteBanner", "keepTopItem is null");
this.quG.setVisibility(8);
} else if (bZY.qpf) {
if (bZY.qpi) {
com.tencent.mm.plugin.report.service.h.mEJ.h(14789, new Object[]{Integer.valueOf(3)});
} else {
com.tencent.mm.plugin.report.service.h.mEJ.h(14789, new Object[]{Integer.valueOf(2)});
}
x.i("WNNoteBanner", "isOpenFromSession: true");
j jVar = new j();
c.bZb().qnC = jVar;
wn wnVar = new wn();
wnVar.scene = 8;
jVar.a(bZY.qpk, Long.valueOf(bZY.qph), true, (Context) this.quG.qJS.get(), bZY.qpl, bZY.qpm, wnVar);
} else {
com.tencent.mm.plugin.report.service.h.mEJ.h(14789, new Object[]{Integer.valueOf(1)});
x.i("WNNoteBanner", "isOpenFromSession: false");
g gVar = new g();
c.bZb().qnC = gVar;
wn wnVar2 = new wn();
wnVar2.scene = 8;
gVar.a(bZY.qpg, (Context) this.quG.qJS.get(), Boolean.valueOf(true), bZY.qpl, bZY.qpm, wnVar2);
}
}
}
|
package hadoop_zookeeper_test;
import java.io.IOException;
import org.apache.log4j.Logger;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
/**
* @author movw
* @date 2018年8月17日 下午6:17:46
* @version 1.0
*/
public class ClientA {
/**
* Logger for this class
*/
private static final Logger logger = Logger.getLogger(ClientA.class);
// 定义常量
private static final String CONNECTSTRING = "192.168.67.167:2181";
private static final String PATH = "/atguigu/distributed";
private static final int SESSION_TIMEOUT = 50 * 1000;
// 定义实例变量
private ZooKeeper zk = null;
// 以下为业务方法
public ZooKeeper startZK() throws IOException {
return new ZooKeeper(CONNECTSTRING, SESSION_TIMEOUT, new Watcher() {
@Override
public void process(WatchedEvent event) {
}
});
}
public String getZNode(String path) throws KeeperException, InterruptedException {
byte[] byteArray = zk.getData(path, new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
triggerValue(path);
} catch (KeeperException | InterruptedException e) {
e.printStackTrace();
}
}
}, new Stat());
return new String(byteArray);
}
public boolean triggerValue(String path) throws KeeperException, InterruptedException {
byte[] byteArray = zk.getData(path, new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
triggerValue(path);
} catch (KeeperException | InterruptedException e) {
e.printStackTrace();
}
}
}, new Stat());
String newValue = new String(byteArray);
if ("ClientA".equals(newValue)) {
System.out.println("AAA System is run......");
}
return false;
}
public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
ClientA test = new ClientA();
test.setZk(test.startZK());
System.out.println("************: " + test.getZNode(PATH));
Thread.sleep(Long.MAX_VALUE);
}
// setter---getter
public ZooKeeper getZk() {
return zk;
}
public void setZk(ZooKeeper zk) {
this.zk = zk;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.